idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
7,200 | private ResourceReference parseDocumentLink ( StringBuilder content ) { String queryString = null ; String text = parseElementAfterString ( content , SEPARATOR_QUERYSTRING ) ; if ( text != null ) { queryString = removeEscapesFromExtraParts ( text ) ; } String anchor = null ; text = parseElementAfterString ( content , SEPARATOR_ANCHOR ) ; if ( text != null ) { anchor = removeEscapesFromExtraParts ( text ) ; } String unescapedReferenceString = removeEscapesFromReferencePart ( content . toString ( ) ) ; ResourceReference reference = untypedLinkReferenceParser . parse ( unescapedReferenceString ) ; reference . setTyped ( false ) ; if ( StringUtils . isNotBlank ( queryString ) ) { reference . setParameter ( DocumentResourceReference . QUERY_STRING , queryString ) ; } if ( StringUtils . isNotBlank ( anchor ) ) { reference . setParameter ( DocumentResourceReference . ANCHOR , anchor ) ; } return reference ; } | Construct a Document Link reference out of the passed content . |
7,201 | private ResourceReference parseURILinks ( String rawLink ) { ResourceReference result = null ; int uriSchemeDelimiterPos = rawLink . indexOf ( ':' ) ; if ( uriSchemeDelimiterPos > - 1 ) { String scheme = rawLink . substring ( 0 , uriSchemeDelimiterPos ) ; String reference = rawLink . substring ( uriSchemeDelimiterPos + 1 ) ; if ( getAllowedURIPrefixes ( ) . contains ( scheme ) ) { try { ResourceReferenceTypeParser parser = this . componentManagerProvider . get ( ) . getInstance ( ResourceReferenceTypeParser . class , scheme ) ; ResourceReference resourceReference = parser . parse ( reference ) ; if ( resourceReference != null ) { result = resourceReference ; } } catch ( ComponentLookupException e ) { } } else { ResourceReference resourceReference = this . urlResourceReferenceTypeParser . parse ( rawLink ) ; if ( resourceReference != null ) { resourceReference . setTyped ( false ) ; result = resourceReference ; } } } return result ; } | Check if the passed link references is an URI link reference . |
7,202 | private ResourceReference parseInterWikiLinks ( StringBuilder content ) { ResourceReference result = null ; String interWikiAlias = parseElementAfterString ( content , SEPARATOR_INTERWIKI ) ; if ( interWikiAlias != null ) { InterWikiResourceReference link = new InterWikiResourceReference ( removeEscapes ( content . toString ( ) ) ) ; link . setInterWikiAlias ( removeEscapes ( interWikiAlias ) ) ; result = link ; } return result ; } | Check if the passed link references is an interwiki link reference . |
7,203 | protected String parseElementAfterString ( StringBuilder content , String separator ) { String element = null ; int index = content . lastIndexOf ( separator ) ; while ( index != - 1 ) { if ( ! shouldEscape ( content , index ) ) { element = content . substring ( index + separator . length ( ) ) . trim ( ) ; content . delete ( index , content . length ( ) ) ; break ; } if ( index > 0 ) { index = content . lastIndexOf ( separator , index - 1 ) ; } else { break ; } } return element ; } | Find out the element located to the right of the passed separator . |
7,204 | private boolean shouldEscape ( StringBuilder content , int charPosition ) { int counter = 0 ; int pos = charPosition - 1 ; while ( pos > - 1 && content . charAt ( pos ) == ESCAPE_CHAR ) { counter ++ ; pos -- ; } return counter % 2 != 0 ; } | Count the number of escape chars before a given character and if that number is odd then that character should be escaped . |
7,205 | public void comment ( char [ ] array , int start , int length ) throws SAXException { fStack . onComment ( array , start , length ) ; } | Lexical handler methods |
7,206 | public void popListener ( Class < ? extends ChainingListener > listenerClass ) { if ( StackableChainingListener . class . isAssignableFrom ( listenerClass ) ) { this . listeners . get ( listenerClass ) . pop ( ) ; } } | Remove the last instance corresponding to the passed listener class if it s stackable in order to go back to the previous state . |
7,207 | public Service setSupportedServiceProfiles ( Iterable < ServiceProfile > profiles ) { if ( profiles == null ) { this . supportedServiceProfiles = null ; return this ; } Set < ServiceProfile > set = new TreeSet < ServiceProfile > ( ) ; for ( ServiceProfile profile : profiles ) { if ( profile != null ) { set . add ( profile ) ; } } int size = set . size ( ) ; if ( size == 0 ) { this . supportedServiceProfiles = null ; return this ; } ServiceProfile [ ] array = new ServiceProfile [ size ] ; this . supportedServiceProfiles = set . toArray ( array ) ; return this ; } | Set the supported service profiles . |
7,208 | public boolean supports ( ServiceProfile profile ) { if ( profile == null ) { return false ; } if ( supportedServiceProfiles == null ) { return false ; } for ( ServiceProfile supportedProfile : supportedServiceProfiles ) { if ( supportedProfile == profile ) { return true ; } } return false ; } | Check if this service supports the specified profile . |
7,209 | public boolean supportsAll ( ServiceProfile ... profiles ) { if ( profiles == null ) { return true ; } for ( ServiceProfile profile : profiles ) { if ( supports ( profile ) == false ) { return false ; } } return true ; } | Check if this service supports all the specified service profiles . |
7,210 | public static String parse ( String input ) { if ( input == null ) { return null ; } Matcher matcher = CHALLENGE_PATTERN . matcher ( input ) ; if ( matcher . matches ( ) ) { return matcher . group ( 1 ) ; } else { return extractFromFormParameters ( input ) ; } } | Extract the access token embedded in the input string . |
7,211 | public Scope setAttributes ( Iterable < Pair > attributes ) { if ( attributes == null ) { this . attributes = null ; return this ; } List < Pair > list = new ArrayList < Pair > ( ) ; for ( Pair attribute : attributes ) { if ( attribute == null || attribute . getKey ( ) == null ) { continue ; } list . add ( attribute ) ; } int size = list . size ( ) ; if ( size == 0 ) { this . attributes = null ; return this ; } Pair [ ] array = new Pair [ size ] ; this . attributes = list . toArray ( array ) ; return this ; } | Set attributes . |
7,212 | public static String [ ] extractNames ( Scope [ ] scopes ) { if ( scopes == null ) { return null ; } String [ ] names = new String [ scopes . length ] ; for ( int i = 0 ; i < scopes . length ; ++ i ) { Scope scope = scopes [ i ] ; names [ i ] = ( scope == null ) ? null : scope . getName ( ) ; } return names ; } | Extract scope names . |
7,213 | public static String encode ( String input ) { try { return URLEncoder . encode ( input , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return input ; } } | URL - encode the input with UTF - 8 . |
7,214 | public static String decode ( String input ) { try { return URLDecoder . decode ( input , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return input ; } } | URL - decode the input with UTF - 8 . |
7,215 | private void setResponse ( int statusCode , String statusMessage , String responseBody , Map < String , List < String > > responseHeaders ) { mStatusCode = statusCode ; mStatusMessage = statusMessage ; mResponseBody = responseBody ; mResponseHeaders = responseHeaders ; } | Set the data fields related to HTTP response information . |
7,216 | public BackchannelAuthenticationCompleteRequest setClaims ( Map < String , Object > claims ) { if ( claims == null || claims . size ( ) == 0 ) { this . claims = null ; } else { setClaims ( Utils . toJson ( claims ) ) ; } return this ; } | Set additional claims which will be embedded in the ID token . |
7,217 | private < TResponse > TResponse callServiceOwnerGetApi ( String path , Map < String , String > queryParams , Class < TResponse > responseClass ) throws AuthleteApiException { return callGetApi ( mServiceOwnerCredentials , path , queryParams , responseClass ) ; } | Call an API with HTTP GET method and Service Owner credentials . |
7,218 | private < TResponse > TResponse callServiceGetApi ( String path , Map < String , String > queryParams , Class < TResponse > responseClass ) throws AuthleteApiException { return callGetApi ( mServiceCredentials , path , queryParams , responseClass ) ; } | Call an API with HTTP GET method and Service credentials . |
7,219 | private < TResponse > TResponse callGetApi ( BasicCredentials credentials , String path , Map < String , String > queryParams , Class < TResponse > responseClass ) throws AuthleteApiException { return callApi ( HttpMethod . GET , credentials , path , queryParams , ( Object ) null , responseClass ) ; } | Call an API with HTTP GET method . |
7,220 | private < TResponse > TResponse callServiceOwnerPostApi ( String path , Map < String , String > queryParams , Object requestBody , Class < TResponse > responseClass ) throws AuthleteApiException { return callPostApi ( mServiceOwnerCredentials , path , queryParams , requestBody , responseClass ) ; } | Call an API with HTTP POST method and Service Owner credentials . |
7,221 | private < TResponse > TResponse callServicePostApi ( String path , Map < String , String > queryParams , Object requestBody , Class < TResponse > responseClass ) throws AuthleteApiException { return callPostApi ( mServiceCredentials , path , queryParams , requestBody , responseClass ) ; } | Call an API with HTTP POST method and Service credentials . |
7,222 | private < TResponse > TResponse callPostApi ( BasicCredentials credentials , String path , Map < String , String > queryParams , Object requestBody , Class < TResponse > responseClass ) throws AuthleteApiException { return callApi ( HttpMethod . POST , credentials , path , queryParams , requestBody , responseClass ) ; } | Call an API with HTTP POST method . |
7,223 | private < TResponse > void callServiceOwnerDeleteApi ( String path , Map < String , String > queryParams ) throws AuthleteApiException { callDeleteApi ( mServiceOwnerCredentials , path , queryParams ) ; } | Call an API with HTTP DELETE method and Service Owner credentials . |
7,224 | private < TResponse > void callServiceDeleteApi ( String path , Map < String , String > queryParams ) throws AuthleteApiException { callDeleteApi ( mServiceCredentials , path , queryParams ) ; } | Call an API with HTTP DELETE method and Service credentials . |
7,225 | private < TResponse > void callDeleteApi ( BasicCredentials credentials , String path , Map < String , String > queryParams ) throws AuthleteApiException { callApi ( HttpMethod . DELETE , credentials , path , queryParams , ( Object ) null , ( Class < TResponse > ) null ) ; } | Call an API with HTTP DELETE method . |
7,226 | private < TResponse > TResponse callApi ( HttpMethod method , BasicCredentials credentials , String path , Map < String , String > queryParams , Object requestBody , Class < TResponse > responseClass ) throws AuthleteApiException { HttpURLConnection con = createConnection ( method , credentials , mBaseUrl , path , queryParams , mSettings ) ; try { return communicate ( con , requestBody , responseClass ) ; } finally { con . disconnect ( ) ; } } | Call an API . |
7,227 | public static String join ( String [ ] strings , String delimiter ) { if ( strings == null ) { return null ; } if ( strings . length == 0 ) { return "" ; } boolean useDelimiter = ( delimiter != null && delimiter . length ( ) != 0 ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String string : strings ) { sb . append ( string ) ; if ( useDelimiter ) ; { sb . append ( delimiter ) ; } } if ( useDelimiter && sb . length ( ) != 0 ) { sb . setLength ( sb . length ( ) - delimiter . length ( ) ) ; } return sb . toString ( ) ; } | Concatenate string with the specified delimiter . |
7,228 | public static String stringifyScopeNames ( Scope [ ] scopes ) { if ( scopes == null ) { return null ; } String [ ] array = new String [ scopes . length ] ; for ( int i = 0 ; i < scopes . length ; ++ i ) { array [ i ] = ( scopes [ i ] == null ) ? null : scopes [ i ] . getName ( ) ; } return join ( array , " " ) ; } | Generate a list of scope names . |
7,229 | public QueryBuilder append ( @ SuppressWarnings ( "ParameterHidesMemberVariable" ) SqlQuery query ) { this . query . append ( query . getSql ( ) ) ; arguments . addAll ( query . getArguments ( ) ) ; return this ; } | Appends given query and its arguments to this query . |
7,230 | @ SuppressWarnings ( "unchecked" ) protected E buildConcreteInstance ( User user , Integer expirationTimeInMinutes ) { if ( expirationTimeInMinutes == null ) { return ( E ) new PasswordResetToken ( user ) ; } return ( E ) new PasswordResetToken ( user , expirationTimeInMinutes ) ; } | Builds a concrete instance of this class . |
7,231 | public void saveUser ( User user ) { LOG . trace ( "Trying to create a new user" ) ; final String pwHash = passwordEncoder . encode ( user . getPassword ( ) ) ; user . setPassword ( pwHash ) ; dao . saveOrUpdate ( user ) ; LOG . info ( "Created the user " + user . getAccountName ( ) ) ; } | Used to create a user . Implements special logic by encoding the password . |
7,232 | @ RequestMapping ( value = "/setLayersForMap.action" , method = RequestMethod . POST ) public java . util . Map < String , Object > setLayersForMap ( @ RequestParam ( "mapModuleId" ) Integer mapModuleId , @ RequestParam ( "layerIds" ) List < Integer > layerIds ) { try { if ( mapModuleId == null || layerIds == null || layerIds . isEmpty ( ) ) { throw new Exception ( ) ; } List < Layer > layers = this . service . setLayersForMap ( mapModuleId , layerIds ) ; return ResultSet . success ( layers ) ; } catch ( Exception e ) { return ResultSet . error ( COULD_NOT_SET_ERROR_MSG ) ; } } | Set layers for map |
7,233 | @ RequestMapping ( value = "/upload.action" , method = RequestMethod . POST ) public ResponseEntity < ? > uploadFile ( @ RequestParam ( "file" ) MultipartFile uploadedFile ) { LOG . debug ( "Requested to upload a multipart-file" ) ; Map < String , Object > responseMap = new HashMap < String , Object > ( ) ; try { E file = service . uploadFile ( uploadedFile ) ; LOG . info ( "Successfully uploaded file " + file . getFileName ( ) ) ; responseMap = ResultSet . success ( file ) ; } catch ( Exception e ) { LOG . error ( "Could not upload the file: " + e . getMessage ( ) ) ; responseMap = ResultSet . error ( "Could not upload the file: " + e . getMessage ( ) ) ; } final HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . setContentType ( MediaType . APPLICATION_JSON_UTF8 ) ; return new ResponseEntity < > ( responseMap , responseHeaders , HttpStatus . OK ) ; } | Persists a file as bytearray in the database |
7,234 | public static Response get ( String url , Credentials credentials , Header [ ] requestHeaders ) throws URISyntaxException , HttpException { return send ( new HttpGet ( url ) , credentials , requestHeaders ) ; } | Performs an HTTP GET on the given URL . |
7,235 | public static Response get ( URI uri ) throws URISyntaxException , HttpException { return send ( new HttpGet ( uri ) , null , null ) ; } | Performs an HTTP GET on the given URI . No credentials needed . |
7,236 | public static Response get ( URI uri , Credentials credentials , Header [ ] requestHeaders ) throws URISyntaxException , HttpException { return send ( new HttpGet ( uri ) , credentials , requestHeaders ) ; } | Performs an HTTP GET on the given URI . Basic auth is used if both username and pw are not null . |
7,237 | public static Response forwardGet ( URI uri , HttpServletRequest request , boolean forwardHeaders ) throws URISyntaxException , HttpException { Header [ ] headersToForward = null ; if ( request != null && forwardHeaders ) { headersToForward = HttpUtil . getHeadersFromRequest ( request ) ; } return send ( new HttpGet ( uri ) , null , headersToForward ) ; } | Forward GET request to uri based on given request |
7,238 | public static Response post ( String url , String password , String username ) throws URISyntaxException , UnsupportedEncodingException , HttpException { return postParams ( new HttpPost ( url ) , new ArrayList < NameValuePair > ( ) , new UsernamePasswordCredentials ( username , password ) , null ) ; } | Performs an HTTP POST on the given URL . Basic auth is used if both and password are not null . |
7,239 | public static Response post ( URI uri ) throws URISyntaxException , UnsupportedEncodingException , HttpException { return postParams ( new HttpPost ( uri ) , new ArrayList < NameValuePair > ( ) , null , null ) ; } | Performs an HTTP POST on the given URI . |
7,240 | public static Response forwardPost ( URI uri , HttpServletRequest request , boolean forwardHeaders ) throws URISyntaxException , HttpException { Header [ ] headersToForward = null ; if ( request != null && forwardHeaders ) { headersToForward = HttpUtil . getHeadersFromRequest ( request ) ; } String ctString = request . getContentType ( ) ; ContentType ct = ContentType . parse ( ctString ) ; String body = getRequestBody ( request ) ; return HttpUtil . postBody ( new HttpPost ( uri ) , body , ct , null , headersToForward ) ; } | Forward POST to uri based on given request |
7,241 | public static Response put ( URI uri , String body , ContentType contentType , String username , String password ) throws URISyntaxException , HttpException { return putBody ( new HttpPut ( uri ) , body , contentType , new UsernamePasswordCredentials ( username , password ) , null ) ; } | Performs an HTTP PUT on the given URL . |
7,242 | public static boolean isSaneRequest ( HttpServletRequest request ) { if ( request != null && request . getMethod ( ) != null ) { return true ; } return false ; } | Checks if request and request method are not null |
7,243 | private static Header [ ] removeHeaders ( Header [ ] headersToClean , String [ ] headersToRemove ) { ArrayList < Header > headers = new ArrayList < > ( ) ; if ( headersToClean == null ) { return null ; } for ( Header header : headersToClean ) { if ( ! StringUtils . equalsAnyIgnoreCase ( header . getName ( ) , headersToRemove ) ) { headers . add ( header ) ; } } LOG . debug ( "Removed the content-length and content-type headers as the HTTP Client lib will care " + "about them as soon as the entity is set on the POST object." ) ; Header [ ] headersArray = new Header [ headers . size ( ) ] ; headersArray = headers . toArray ( headersArray ) ; return headersArray ; } | Remove headers form header array that match Strings in headersToRemove |
7,244 | public RESTImport createImportJob ( String workSpaceName , String dataStoreName ) throws Exception { if ( StringUtils . isEmpty ( workSpaceName ) ) { throw new GeoServerRESTImporterException ( "No workspace given. Please provide a " + "workspace to import the data in." ) ; } RESTImport importJob = new RESTImport ( ) ; LOG . debug ( "Creating a new import job to import into workspace " + workSpaceName ) ; RESTTargetWorkspace targetWorkspace = new RESTTargetWorkspace ( workSpaceName ) ; importJob . setTargetWorkspace ( targetWorkspace ) ; if ( ! StringUtils . isEmpty ( dataStoreName ) ) { LOG . debug ( "The data will be imported into datastore " + dataStoreName ) ; RESTTargetDataStore targetDataStore = new RESTTargetDataStore ( dataStoreName , null ) ; importJob . setTargetStore ( targetDataStore ) ; } else { LOG . debug ( "No datastore given. A new datastore will be created in relation to the" + "input data." ) ; } Response httpResponse = HttpUtil . post ( this . addEndPoint ( "" ) , this . asJSON ( importJob ) , ContentType . APPLICATION_JSON , this . username , this . password ) ; HttpStatus responseStatus = httpResponse . getStatusCode ( ) ; if ( responseStatus == null || ! responseStatus . is2xxSuccessful ( ) ) { throw new GeoServerRESTImporterException ( "Import job cannot be " + "created. Is the GeoServer Importer extension installed?" ) ; } RESTImport restImport = ( RESTImport ) this . asEntity ( httpResponse . getBody ( ) , RESTImport . class ) ; LOG . debug ( "Successfully created the import job with ID " + restImport . getId ( ) ) ; return restImport ; } | Create a new import job . |
7,245 | public boolean createReprojectTransformTask ( Integer importJobId , Integer taskId , String sourceSrs , String targetSrs ) throws URISyntaxException , HttpException { RESTReprojectTransform transformTask = new RESTReprojectTransform ( ) ; if ( StringUtils . isNotEmpty ( sourceSrs ) ) { transformTask . setSource ( sourceSrs ) ; } transformTask . setTarget ( targetSrs ) ; return createTransformTask ( importJobId , taskId , transformTask ) ; } | Create a reprojection task . |
7,246 | public RESTImportTaskList uploadFile ( Integer importJobId , File file , String sourceSrs ) throws Exception { LOG . debug ( "Uploading file " + file . getName ( ) + " to import job " + importJobId ) ; Response httpResponse = HttpUtil . post ( this . addEndPoint ( importJobId + "/tasks" ) , file , this . username , this . password ) ; HttpStatus responseStatus = httpResponse . getStatusCode ( ) ; if ( responseStatus == null || ! responseStatus . is2xxSuccessful ( ) ) { throw new GeoServerRESTImporterException ( "Error while uploading the file." ) ; } LOG . debug ( "Successfully uploaded the file to import job " + importJobId ) ; RESTImportTaskList importTaskList = null ; try { importTaskList = mapper . readValue ( httpResponse . getBody ( ) , RESTImportTaskList . class ) ; LOG . debug ( "Imported file " + file . getName ( ) + " contains data for multiple layers." ) ; return importTaskList ; } catch ( Exception e ) { LOG . debug ( "Imported file " + file . getName ( ) + " likely contains data for single " + "layer. Will check this now." ) ; try { RESTImportTask importTask = mapper . readValue ( httpResponse . getBody ( ) , RESTImportTask . class ) ; if ( importTask != null ) { importTaskList = new RESTImportTaskList ( ) ; importTaskList . add ( importTask ) ; LOG . debug ( "Imported file " + file . getName ( ) + " contains data for a single layer." ) ; } return importTaskList ; } catch ( Exception ex ) { LOG . info ( "It seems that the SRS definition source file can not be interpreted by " + "GeoServer / GeoTools. Try to set SRS definition to " + sourceSrs + "." ) ; File updatedGeoTiff = null ; try { if ( ! StringUtils . isEmpty ( sourceSrs ) ) { updatedGeoTiff = addPrjFileToArchive ( file , sourceSrs ) ; } else { throw new GeoServerRESTImporterException ( "Could not set SRS definition " + "of GeoTIFF." ) ; } } catch ( ZipException ze ) { throw new GeoServerRESTImporterException ( "No valid ZIP file given containing " + "GeoTiff datasets." ) ; } if ( updatedGeoTiff != null ) { importTaskList = uploadFile ( importJobId , updatedGeoTiff , null ) ; return importTaskList ; } } } return null ; } | Upload an import file . |
7,247 | public boolean updateImportTask ( int importJobId , int importTaskId , AbstractRESTEntity updateTaskEntity ) throws Exception { LOG . debug ( "Updating the import task " + importTaskId + " in job " + importJobId + " with " + updateTaskEntity ) ; Response httpResponse = HttpUtil . put ( this . addEndPoint ( importJobId + "/tasks/" + importTaskId ) , this . asJSON ( updateTaskEntity ) , ContentType . APPLICATION_JSON , this . username , this . password ) ; boolean success = httpResponse . getStatusCode ( ) . equals ( HttpStatus . NO_CONTENT ) ; if ( success ) { LOG . debug ( "Successfully updated the task " + importTaskId ) ; } else { LOG . error ( "Unknown error occured while updating the task " + importTaskId ) ; } return success ; } | Updates the given import task . |
7,248 | public boolean deleteImportJob ( Integer importJobId ) throws URISyntaxException , HttpException { LOG . debug ( "Deleting the import job " + importJobId ) ; Response httpResponse = HttpUtil . delete ( this . addEndPoint ( importJobId . toString ( ) ) , this . username , this . password ) ; boolean success = httpResponse . getStatusCode ( ) . equals ( HttpStatus . NO_CONTENT ) ; if ( success ) { LOG . debug ( "Successfully deleted the import job " + importJobId ) ; } else { LOG . error ( "Unknown error occured while deleting the import job " + importJobId ) ; } return success ; } | Deletes an importJob . |
7,249 | public boolean runImportJob ( Integer importJobId ) throws UnsupportedEncodingException , URISyntaxException , HttpException { LOG . debug ( "Starting the import for job " + importJobId ) ; Response httpResponse = HttpUtil . post ( this . addEndPoint ( Integer . toString ( importJobId ) ) , this . username , this . password ) ; boolean success = httpResponse . getStatusCode ( ) . equals ( HttpStatus . NO_CONTENT ) ; if ( success ) { LOG . debug ( "Successfully started the import job " + importJobId ) ; } else { LOG . error ( "Unknown error occured while running the import job " + importJobId ) ; } return success ; } | Run a previously configured import job . |
7,250 | public RESTLayer getLayer ( Integer importJobId , Integer taskId ) throws Exception { Response httpResponse = HttpUtil . get ( this . addEndPoint ( importJobId + "/tasks/" + taskId + "/layer" ) , this . username , this . password ) ; return ( RESTLayer ) this . asEntity ( httpResponse . getBody ( ) , RESTLayer . class ) ; } | Get a layer . |
7,251 | public List < RESTLayer > getAllImportedLayers ( Integer importJobId , List < RESTImportTask > tasks ) throws Exception { ArrayList < RESTLayer > layers = new ArrayList < RESTLayer > ( ) ; for ( RESTImportTask task : tasks ) { RESTImportTask refreshedTask = this . getRESTImportTask ( importJobId , task . getId ( ) ) ; if ( refreshedTask . getState ( ) . equalsIgnoreCase ( "COMPLETE" ) ) { Response httpResponse = HttpUtil . get ( this . addEndPoint ( importJobId + "/tasks/" + task . getId ( ) + "/layer" ) , this . username , this . password ) ; RESTLayer layer = ( RESTLayer ) this . asEntity ( httpResponse . getBody ( ) , RESTLayer . class ) ; if ( layer != null ) { layers . add ( layer ) ; } } else if ( ( tasks . size ( ) == 1 ) && refreshedTask . getState ( ) . equalsIgnoreCase ( "ERROR" ) ) { throw new GeoServerRESTImporterException ( refreshedTask . getErrorMessage ( ) ) ; } } return layers ; } | fetch all created Layers of import job |
7,252 | public RESTData getDataOfImportTask ( Integer importJobId , Integer taskId ) throws Exception { final DeserializationFeature unwrapRootValueFeature = DeserializationFeature . UNWRAP_ROOT_VALUE ; boolean unwrapRootValueFeatureIsEnabled = mapper . isEnabled ( unwrapRootValueFeature ) ; Response httpResponse = HttpUtil . get ( this . addEndPoint ( importJobId + "/tasks/" + taskId + "/data" ) , this . username , this . password ) ; mapper . disable ( unwrapRootValueFeature ) ; final RESTData resultEntity = ( RESTData ) this . asEntity ( httpResponse . getBody ( ) , RESTData . class ) ; if ( unwrapRootValueFeatureIsEnabled ) { mapper . enable ( unwrapRootValueFeature ) ; } return resultEntity ; } | Get the data of an import task . |
7,253 | public RESTImportTask getRESTImportTask ( Integer importJobId , Integer taskId ) throws Exception { Response httpResponse = HttpUtil . get ( this . addEndPoint ( importJobId + "/tasks/" + taskId ) , this . username , this . password ) ; return ( RESTImportTask ) this . asEntity ( httpResponse . getBody ( ) , RESTImportTask . class ) ; } | Get an import task . |
7,254 | private boolean createTransformTask ( Integer importJobId , Integer taskId , RESTTransform transformTask ) throws URISyntaxException , HttpException { LOG . debug ( "Creating a new transform task for import job" + importJobId + " and task " + taskId ) ; mapper . disable ( SerializationFeature . WRAP_ROOT_VALUE ) ; Response httpResponse = HttpUtil . post ( this . addEndPoint ( importJobId + "/tasks/" + taskId + "/transforms" ) , this . asJSON ( transformTask ) , ContentType . APPLICATION_JSON , this . username , this . password ) ; mapper . enable ( SerializationFeature . WRAP_ROOT_VALUE ) ; if ( httpResponse . getStatusCode ( ) . equals ( HttpStatus . CREATED ) ) { LOG . debug ( "Successfully created the transform task" ) ; return true ; } else { LOG . error ( "Error while creating the transform task" ) ; return false ; } } | Helper method to create an importer transformTask |
7,255 | public static File addPrjFileToArchive ( File file , String targetCrs ) throws ZipException , IOException , NoSuchAuthorityCodeException , FactoryException { ZipFile zipFile = new ZipFile ( file ) ; CoordinateReferenceSystem decodedTargetCrs = CRS . decode ( targetCrs ) ; String targetCrsWkt = toSingleLineWKT ( decodedTargetCrs ) ; ArrayList < String > zipFileNames = new ArrayList < String > ( ) ; List < FileHeader > zipFileHeaders = zipFile . getFileHeaders ( ) ; for ( FileHeader zipFileHeader : zipFileHeaders ) { if ( FilenameUtils . getExtension ( zipFileHeader . getFileName ( ) ) . equalsIgnoreCase ( "prj" ) ) { continue ; } zipFileNames . add ( FilenameUtils . getBaseName ( zipFileHeader . getFileName ( ) ) ) ; } LOG . debug ( "Following files will be created and added to ZIP file: " + zipFileNames ) ; for ( String prefix : zipFileNames ) { File targetPrj = null ; try { targetPrj = File . createTempFile ( "TMP_" + prefix , ".prj" ) ; FileUtils . write ( targetPrj , targetCrsWkt , "UTF-8" ) ; ZipParameters params = new ZipParameters ( ) ; params . setSourceExternalStream ( true ) ; params . setCompressionLevel ( Zip4jConstants . DEFLATE_LEVEL_NORMAL ) ; params . setFileNameInZip ( prefix + ".prj" ) ; zipFile . addFile ( targetPrj , params ) ; } finally { if ( targetPrj != null ) { targetPrj . delete ( ) ; } } } return zipFile . getFile ( ) ; } | Add a projection file to a shapefile zip archive . |
7,256 | public static String toSingleLineWKT ( CoordinateReferenceSystem crs ) { String wkt = null ; try { Formattable formattable = ( Formattable ) crs ; wkt = formattable . toWKT ( 0 , false ) ; } catch ( ClassCastException e ) { wkt = crs . toWKT ( ) ; } wkt = wkt . replaceAll ( "\n" , "" ) . replaceAll ( " " , "" ) ; return wkt ; } | Turns the CRS into a single line WKT |
7,257 | private AbstractRESTEntity asEntity ( byte [ ] responseBody , Class < ? > clazz ) throws Exception { AbstractRESTEntity entity = null ; entity = ( AbstractRESTEntity ) mapper . readValue ( responseBody , clazz ) ; return entity ; } | Convert a byte array to an importer REST entity . |
7,258 | private String asJSON ( Object entity ) { String entityJson = null ; try { entityJson = this . mapper . writeValueAsString ( entity ) ; } catch ( Exception e ) { LOG . error ( "Could not parse as JSON: " + e . getMessage ( ) ) ; } return entityJson ; } | Convert an object to json . |
7,259 | private URI addEndPoint ( String endPoint ) throws URISyntaxException { if ( StringUtils . isEmpty ( endPoint ) || endPoint . equals ( "/" ) ) { return this . baseUri ; } if ( this . baseUri . getPath ( ) . endsWith ( "/" ) || endPoint . startsWith ( "/" ) ) { endPoint = this . baseUri . getPath ( ) + endPoint ; } else { endPoint = this . baseUri . getPath ( ) + "/" + endPoint ; } URI uri = null ; URIBuilder builder = new URIBuilder ( ) ; builder . setScheme ( this . baseUri . getScheme ( ) ) ; builder . setHost ( this . baseUri . getHost ( ) ) ; builder . setPort ( this . baseUri . getPort ( ) ) ; builder . setPath ( endPoint ) ; uri = builder . build ( ) ; return uri ; } | Add an endpoint . |
7,260 | public static final Map < String , Object > error ( String errorMsg , Map additionalReturnValuesMap ) { Map < String , Object > returnMap = new HashMap < String , Object > ( 3 ) ; returnMap . put ( "message" , errorMsg ) ; returnMap . put ( "additionalInfo" , additionalReturnValuesMap ) ; returnMap . put ( "success" , false ) ; return returnMap ; } | Method returning error message and additional return values |
7,261 | private int detectColumnIndexOfLocale ( String locale , CSVReader csvReader ) throws Exception { int indexOfLocale = - 1 ; List < String > headerLine = Arrays . asList ( ArrayUtils . nullToEmpty ( csvReader . readNext ( ) ) ) ; if ( headerLine == null || headerLine . isEmpty ( ) ) { throw new Exception ( "CSV locale file seems to be empty." ) ; } if ( headerLine . size ( ) < 3 ) { throw new Exception ( "CSV locale file is invalid: Not enough columns." ) ; } for ( int i = 2 ; i < headerLine . size ( ) ; i ++ ) { String columnName = headerLine . get ( i ) ; if ( locale . equalsIgnoreCase ( columnName ) ) { indexOfLocale = headerLine . indexOf ( columnName ) ; break ; } } if ( indexOfLocale < 0 ) { throw new Exception ( "Could not find locale " + locale + " in CSV file" ) ; } return indexOfLocale ; } | Extracts the column index of the given locale in the CSV file . |
7,262 | private boolean isInWhiteList ( URL url ) { final String host = url . getHost ( ) ; final int port = url . getPort ( ) ; final String protocol = url . getProtocol ( ) ; final int portToTest = ( port != - 1 ) ? port : ( StringUtils . equalsIgnoreCase ( protocol , "https" ) ? 443 : 80 ) ; List < String > matchingWhiteListEntries = proxyWhiteList . stream ( ) . filter ( ( String whitelistEntry ) -> { String whitelistHost ; int whitelistPort ; if ( StringUtils . contains ( whitelistEntry , ":" ) ) { whitelistHost = whitelistEntry . split ( ":" ) [ 0 ] ; whitelistPort = Integer . parseInt ( whitelistEntry . split ( ":" ) [ 1 ] ) ; } else { whitelistHost = whitelistEntry ; whitelistPort = - 1 ; } final int portToTestAgainst = ( whitelistPort != - 1 ) ? whitelistPort : ( StringUtils . equalsIgnoreCase ( protocol , "https" ) ? 443 : 80 ) ; final boolean portIsMatching = portToTestAgainst == portToTest ; final boolean domainIsMatching = StringUtils . equalsIgnoreCase ( host , whitelistHost ) || StringUtils . endsWith ( host , whitelistHost ) ; return ( portIsMatching && domainIsMatching ) ; } ) . collect ( Collectors . toList ( ) ) ; boolean isAllowed = ! matchingWhiteListEntries . isEmpty ( ) ; return isAllowed ; } | Helper method to check whether the URI is contained in the host whitelist provided in list of whitelisted hosts |
7,263 | @ RequestMapping ( value = "/endpointdoc" , method = RequestMethod . GET ) public Set < RequestMappingInfo > getEndpoints ( ) { return this . service . getEndpoints ( requestMappingHandlerMapping ) ; } | Provides an overview of all mapped endpoints . |
7,264 | public E findById ( ID id ) { LOG . trace ( "Finding " + entityClass . getSimpleName ( ) + " with ID " + id ) ; return ( E ) getSession ( ) . get ( entityClass , id ) ; } | Return the real object from the database . Returns null if the object does not exist . |
7,265 | public void saveOrUpdate ( E e ) { final Integer id = e . getId ( ) ; final boolean hasId = id != null ; String createOrUpdatePrefix = hasId ? "Updating" : "Creating a new" ; String idSuffix = hasId ? " with ID " + id : "" ; LOG . trace ( createOrUpdatePrefix + " instance of " + entityClass . getSimpleName ( ) + idSuffix ) ; e . setModified ( DateTime . now ( ) ) ; getSession ( ) . saveOrUpdate ( e ) ; } | Saves or updates the passed entity . |
7,266 | public void delete ( E e ) { LOG . trace ( "Deleting " + entityClass . getSimpleName ( ) + " with ID " + e . getId ( ) ) ; getSession ( ) . delete ( e ) ; } | Deletes the passed entity . |
7,267 | @ SuppressWarnings ( "unchecked" ) public List < E > findByCriteria ( Criterion ... criterion ) throws HibernateException { LOG . trace ( "Finding instances of " + entityClass . getSimpleName ( ) + " based on " + criterion . length + " criteria" ) ; Criteria criteria = createDistinctRootEntityCriteria ( criterion ) ; return criteria . list ( ) ; } | Gets the results that match a variable number of passed criterions . Call this method without arguments to find all entities . |
7,268 | @ SuppressWarnings ( "unchecked" ) public E findByUniqueCriteria ( Criterion ... criterion ) throws HibernateException { LOG . trace ( "Finding one unique " + entityClass . getSimpleName ( ) + " based on " + criterion . length + " criteria" ) ; Criteria criteria = createDistinctRootEntityCriteria ( criterion ) ; return ( E ) criteria . uniqueResult ( ) ; } | Gets the unique result that matches a variable number of passed criterions . |
7,269 | @ SuppressWarnings ( "unchecked" ) public PagingResult < E > findByCriteriaWithSortingAndPaging ( Integer firstResult , Integer maxResults , List < Order > sorters , Criterion ... criterion ) throws HibernateException { int nrOfSorters = sorters == null ? 0 : sorters . size ( ) ; LOG . trace ( "Finding instances of " + entityClass . getSimpleName ( ) + " based on " + criterion . length + " criteria" + " with " + nrOfSorters + " sorters" ) ; Criteria criteria = createDistinctRootEntityCriteria ( criterion ) ; if ( maxResults != null ) { LOG . trace ( "Limiting result set size to " + maxResults ) ; criteria . setMaxResults ( maxResults ) ; } if ( firstResult != null ) { LOG . trace ( "Setting the first result to be retrieved to " + firstResult ) ; criteria . setFirstResult ( firstResult ) ; } if ( sorters != null ) { for ( Order sortInfo : sorters ) { criteria . addOrder ( sortInfo ) ; } } return new PagingResult < E > ( criteria . list ( ) , getTotalCount ( criterion ) ) ; } | Gets the results that match a variable number of passed criterions considering the paging - and sort - info at the same time . |
7,270 | public Number getTotalCount ( Criterion ... criterion ) throws HibernateException { Criteria criteria = getSession ( ) . createCriteria ( entityClass ) ; addCriterionsToCriteria ( criteria , criterion ) ; criteria . setProjection ( Projections . rowCount ( ) ) ; return ( Long ) criteria . uniqueResult ( ) ; } | Returns the total count of db entries for the current type . |
7,271 | public void authenticate ( String username , String password ) { ldapTemplate . authenticate ( query ( ) . where ( "objectClass" ) . is ( "simpleSecurityObject" ) . and ( "cn" ) . is ( username ) , password ) ; LOGGER . info ( "Successfully authenticated " + username ) ; } | Authenticate against ldap . |
7,272 | public List < String > getGroups ( String username , String property ) { final List < String > result = new ArrayList < > ( ) ; ldapTemplate . search ( query ( ) . where ( "cn" ) . is ( username ) , new AttributesMapper < String > ( ) { public String mapFromAttributes ( Attributes attrs ) throws NamingException { NamingEnumeration < ? > ous = attrs . get ( property ) . getAll ( ) ; while ( ous . hasMore ( ) ) { result . add ( ( String ) ous . next ( ) ) ; } return "" ; } } ) ; return result ; } | Extract groups from ldap . |
7,273 | public void sendMail ( String from , String replyTo , String [ ] to , String [ ] cc , String [ ] bcc , String subject , String msg ) throws Exception { SimpleMailMessage simpleMailMassage = new SimpleMailMessage ( ) ; if ( from == null || from . isEmpty ( ) ) { from = defaultMailSender ; } simpleMailMassage . setFrom ( from ) ; simpleMailMassage . setReplyTo ( replyTo ) ; simpleMailMassage . setTo ( to ) ; simpleMailMassage . setBcc ( bcc ) ; simpleMailMassage . setCc ( cc ) ; simpleMailMassage . setSubject ( subject ) ; simpleMailMassage . setText ( msg ) ; sendMail ( simpleMailMassage ) ; } | Sends a SimpleMailMessage . |
7,274 | public void sendMimeMail ( String from , String replyTo , String [ ] to , String [ ] cc , String [ ] bcc , String subject , String msg , Boolean html , String attachmentFilename , File attachmentFile ) throws MessagingException , MailException { Boolean multipart = false ; if ( attachmentFilename != null && attachmentFile != null ) { multipart = true ; } MimeMessage mimeMailMessage = mailSender . createMimeMessage ( ) ; MimeMessageHelper mimeHelper = new MimeMessageHelper ( mimeMailMessage , multipart ) ; if ( from == null || from . isEmpty ( ) ) { from = defaultMailSender ; } mimeHelper . setFrom ( from ) ; mimeHelper . setTo ( to ) ; mimeHelper . setSubject ( subject ) ; mimeHelper . setText ( msg , html ) ; if ( replyTo != null && ! replyTo . isEmpty ( ) ) { mimeHelper . setReplyTo ( replyTo ) ; } if ( bcc != null && bcc . length > 0 ) { mimeHelper . setBcc ( bcc ) ; } if ( cc != null && cc . length > 0 ) { mimeHelper . setCc ( cc ) ; } if ( attachmentFilename != null && attachmentFile != null ) { mimeHelper . addAttachment ( attachmentFilename , attachmentFile ) ; } sendMail ( mimeMailMessage ) ; } | Sends a MimeMessage . |
7,275 | protected String transformEntityName ( EntityNaming entityNaming ) { String singular = super . transformEntityName ( entityNaming ) ; return transformToPluralForm ( singular ) ; } | Transforms an entity name to plural form . |
7,276 | public E registerUser ( E user , HttpServletRequest request ) throws Exception { String email = user . getEmail ( ) ; E existingUser = dao . findByEmail ( email ) ; if ( existingUser != null ) { final String errorMessage = "User with eMail '" + email + "' already exists." ; LOG . info ( errorMessage ) ; throw new Exception ( errorMessage ) ; } user = ( E ) this . persistNewUser ( user , true ) ; registrationTokenService . sendRegistrationActivationMail ( request , user ) ; return user ; } | Registers a new user . Initially the user will be inactive . An email with an activation link will be sent to the user . |
7,277 | public E persistNewUser ( E user , boolean encryptPassword ) { if ( user . getId ( ) != null ) { return user ; } if ( encryptPassword ) { user . setPassword ( passwordEncoder . encode ( user . getPassword ( ) ) ) ; } dao . saveOrUpdate ( user ) ; return user ; } | Persists a new user in the database . |
7,278 | public Object convertToEntityAttribute ( String dbData ) { if ( "true" . equalsIgnoreCase ( dbData ) ) { return true ; } else if ( "false" . equalsIgnoreCase ( dbData ) ) { return false ; } else if ( NumberUtils . isParsable ( dbData ) ) { if ( NumberUtils . isDigits ( dbData ) || ( dbData . startsWith ( "-" ) && NumberUtils . isDigits ( dbData . substring ( 1 ) ) ) ) { return Long . parseLong ( dbData ) ; } else { return Double . parseDouble ( dbData ) ; } } return dbData ; } | Converts a string value from the database to the best matching java primitive type . |
7,279 | public boolean hasPermission ( User user , E userGroup , Permission permission ) { if ( user != null && permission . equals ( Permission . READ ) && userGroup . getMembers ( ) . contains ( user ) ) { LOG . trace ( "Granting READ access on group where the user is member." ) ; return true ; } return super . hasPermission ( user , userGroup , permission ) ; } | Grants READ permission on groups where the user is a member . Uses default implementation otherwise . |
7,280 | public Identifier toPhysicalTableName ( Identifier tableIdentifier , JdbcEnvironment context ) { return convertToLimitedLowerCase ( context , tableIdentifier , tablePrefix ) ; } | Converts table names to lower case and limits the length if necessary . |
7,281 | public Identifier toPhysicalColumnName ( Identifier columnIdentifier , JdbcEnvironment context ) { return convertToLimitedLowerCase ( context , columnIdentifier , null ) ; } | Converts column names to lower case and limits the length if necessary . |
7,282 | protected Integer getIdentifierLengthLimit ( JdbcEnvironment context ) { String dialectName = context . getDialect ( ) . getClass ( ) . getSimpleName ( ) ; if ( dialectName . startsWith ( "Oracle" ) ) { return LENGTH_LIMIT_ORACLE ; } else if ( context . getDialect ( ) instanceof ShogunCoreOracleDialect ) { return LENGTH_LIMIT_ORACLE ; } else if ( dialectName . startsWith ( "PostgreSQL" ) ) { return LENGTH_LIMIT_POSTGRESQL ; } return null ; } | Determines the identifier length limit for the given JDBC context . Returns null if no limitation is necessary . |
7,283 | public String getParameterIgnoreCase ( String name ) { for ( Map . Entry < String , String [ ] > entry : customParameters . entrySet ( ) ) { if ( entry . getKey ( ) . equalsIgnoreCase ( name ) ) { return StringUtils . join ( entry . getValue ( ) , "," ) ; } } return null ; } | Get a parameter by name ignoring case . |
7,284 | public void initializeDatabaseContent ( ) { if ( this . shogunInitEnabled ) { LOG . info ( "Initializing SHOGun content" ) ; for ( PersistentObject object : objectsToCreate ) { if ( object instanceof User ) { initService . saveUser ( ( User ) object ) ; } else { initService . savePersistentObject ( object ) ; } } } else { LOG . info ( "Not initializing anything for SHOGun." ) ; } } | The method called on initialization |
7,285 | @ PreAuthorize ( "isAuthenticated()" ) public E uploadFile ( MultipartFile file ) throws Exception { if ( file == null ) { final String errMsg = "Upload failed. File is null." ; LOG . error ( errMsg ) ; throw new Exception ( errMsg ) ; } else if ( file . isEmpty ( ) ) { final String errMsg = "Upload failed. File is empty." ; LOG . error ( errMsg ) ; throw new Exception ( errMsg ) ; } InputStream is = null ; byte [ ] fileByteArray = null ; E fileToPersist = getEntityClass ( ) . newInstance ( ) ; try { is = file . getInputStream ( ) ; fileByteArray = IOUtils . toByteArray ( is ) ; } catch ( Exception e ) { throw new Exception ( "Could not create the bytearray: " + e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; } fileToPersist . setFile ( fileByteArray ) ; fileToPersist . setFileType ( file . getContentType ( ) ) ; fileToPersist . setFileName ( file . getOriginalFilename ( ) ) ; dao . saveOrUpdate ( fileToPersist ) ; return fileToPersist ; } | Method persists a given MultipartFile as a bytearray in the database |
7,286 | @ PreAuthorize ( "isAuthenticated()" ) public E saveImage ( MultipartFile file , boolean createThumbnail , Integer thumbnailTargetSize ) throws Exception { InputStream is = null ; ByteArrayInputStream bais = null ; E imageToPersist = null ; try { is = file . getInputStream ( ) ; byte [ ] imageByteArray = IOUtils . toByteArray ( is ) ; imageToPersist = getEntityClass ( ) . newInstance ( ) ; if ( createThumbnail ) { byte [ ] thumbnail = scaleImage ( imageByteArray , FilenameUtils . getExtension ( file . getOriginalFilename ( ) ) , thumbnailTargetSize ) ; imageToPersist . setThumbnail ( thumbnail ) ; } imageToPersist . setFile ( imageByteArray ) ; bais = new ByteArrayInputStream ( imageByteArray ) ; BufferedImage bimg = ImageIO . read ( bais ) ; imageToPersist . setWidth ( bimg . getWidth ( ) ) ; imageToPersist . setHeight ( bimg . getHeight ( ) ) ; imageToPersist . setFileType ( file . getContentType ( ) ) ; imageToPersist . setFileName ( file . getOriginalFilename ( ) ) ; dao . saveOrUpdate ( imageToPersist ) ; } catch ( Exception e ) { throw new Exception ( "Could not create the Image in DB: " + e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( bais ) ; } return imageToPersist ; } | Method persists a given Image as a bytearray in the database |
7,287 | public static byte [ ] scaleImage ( byte [ ] imageBytes , String outputFormat , Integer targetSize ) throws Exception { InputStream is = null ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] imageInBytes = null ; BufferedImage image = null ; BufferedImage resizedImage = null ; try { is = new ByteArrayInputStream ( imageBytes ) ; image = ImageIO . read ( is ) ; resizedImage = Scalr . resize ( image , targetSize ) ; ImageIO . write ( resizedImage , outputFormat , baos ) ; imageInBytes = baos . toByteArray ( ) ; } catch ( Exception e ) { throw new Exception ( "Error on resizing an image: " + e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( baos ) ; if ( image != null ) { image . flush ( ) ; } if ( resizedImage != null ) { resizedImage . flush ( ) ; } } return imageInBytes ; } | Scales an image by the given dimensions |
7,288 | private void addMasterJulLogRecords ( Container result ) { result . add ( new LogRecordContent ( "nodes/master/logs/all_memory_buffer.log" ) { public Iterable < LogRecord > getLogRecords ( ) { return SupportPlugin . getInstance ( ) . getAllLogRecords ( ) ; } } ) ; final File [ ] julLogFiles = SupportPlugin . getRootDirectory ( ) . listFiles ( new LogFilenameFilter ( ) ) ; if ( julLogFiles == null ) { LOGGER . log ( Level . WARNING , "Cannot add master java.util.logging logs to the bundle. Cannot access log files" ) ; return ; } for ( File file : julLogFiles ) { result . add ( new FileContent ( "nodes/master/logs/{0}" , new String [ ] { file . getName ( ) } , file ) ) ; } } | Adds j . u . l logging output that the support - core plugin captures . |
7,289 | private static String camelCaseToSentenceCase ( String camelCase ) { String name = StringUtils . join ( StringUtils . splitByCharacterTypeCamelCase ( camelCase ) , " " ) ; return name . substring ( 0 , 1 ) . toUpperCase ( Locale . ENGLISH ) + name . substring ( 1 ) . toLowerCase ( Locale . ENGLISH ) ; } | Converts aCamelCaseString into A sentence case string . |
7,290 | public static ContentMappings newInstance ( ) throws IOException { ContentMappings mappings = Persistence . load ( ContentMappings . class ) ; if ( mappings == null ) { mappings = ( ContentMappings ) new XmlProxy ( ) . readResolve ( ) ; } return mappings ; } | Constructs a new ContentMappings using an existing config file or default settings if not found . |
7,291 | public void doDownload ( StaplerRequest req , StaplerResponse rsp ) throws ServletException , IOException { doGenerateAllBundles ( req , rsp ) ; } | Generates a support bundle . |
7,292 | private boolean isBinary ( ) { try ( InputStream in = getInputStream ( ) ) { long size = Files . size ( file . toPath ( ) ) ; if ( size == 0 ) { return true ; } byte [ ] b = new byte [ ( size < StreamUtils . DEFAULT_PROBE_SIZE ? ( int ) size : StreamUtils . DEFAULT_PROBE_SIZE ) ] ; int read = in . read ( b ) ; if ( read != b . length ) { return true ; } return StreamUtils . isNonWhitespaceControlCharacter ( b ) ; } catch ( IOException e ) { return true ; } } | Check if the file is binary or not |
7,293 | private static String getVersion ( ) { Properties properties = new Properties ( ) ; try ( InputStream ins = HttpRosetteAPI . class . getClassLoader ( ) . getResourceAsStream ( "version.properties" ) ) { properties . load ( ins ) ; } catch ( IOException e ) { } return properties . getProperty ( "version" , "undefined" ) ; } | Returns the version of the binding . |
7,294 | private static byte [ ] getBytes ( InputStream is ) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ 4096 ] ; while ( true ) { int r = is . read ( buf ) ; if ( r == - 1 ) { out . flush ( ) ; return out . toByteArray ( ) ; } out . write ( buf , 0 , r ) ; } } | Returns a byte array from InputStream . |
7,295 | public SupportedLanguagesResponse getSupportedLanguages ( String endpoint ) throws HttpRosetteAPIException { if ( DOC_ENDPOINTS . contains ( endpoint ) || NAME_DEDUPLICATION_SERVICE_PATH . equals ( endpoint ) ) { return sendGetRequest ( urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH , SupportedLanguagesResponse . class ) ; } else { return null ; } } | Gets the set of language and script codes supported by the specified Rosette API endpoint . |
7,296 | public SupportedLanguagePairsResponse getSupportedLanguagePairs ( String endpoint ) throws HttpRosetteAPIException { if ( NAMES_ENDPOINTS . contains ( endpoint ) && ! NAME_DEDUPLICATION_SERVICE_PATH . equals ( endpoint ) ) { return sendGetRequest ( urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH , SupportedLanguagePairsResponse . class ) ; } else { return null ; } } | Gets the set of language script codes and transliteration scheme pairs supported by the specified Rosette API endpoint . |
7,297 | public < RequestType extends Request , ResponseType extends Response > Future < ResponseType > performAsync ( String endpoint , RequestType request , Class < ResponseType > responseClass ) throws HttpRosetteAPIException { throw new UnsupportedOperationException ( "Asynchronous operations are not yet supported" ) ; } | This method always throws UnsupportedOperationException . |
7,298 | private < T extends Object > T getResponse ( HttpResponse httpResponse , Class < T > clazz ) throws IOException , HttpRosetteAPIException { int status = httpResponse . getStatusLine ( ) . getStatusCode ( ) ; String encoding = headerValueOrNull ( httpResponse . getFirstHeader ( HttpHeaders . CONTENT_ENCODING ) ) ; try ( InputStream stream = httpResponse . getEntity ( ) . getContent ( ) ; InputStream inputStream = "gzip" . equalsIgnoreCase ( encoding ) ? new GZIPInputStream ( stream ) : stream ) { String ridHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-DocumentRequest-Id" ) ) ; if ( HTTP_OK != status ) { String ecHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-Status-Code" ) ) ; String emHeader = headerValueOrNull ( httpResponse . getFirstHeader ( "X-RosetteAPI-Status-Message" ) ) ; String responseContentType = headerValueOrNull ( httpResponse . getFirstHeader ( HttpHeaders . CONTENT_TYPE ) ) ; if ( "application/json" . equals ( responseContentType ) ) { ErrorResponse errorResponse = mapper . readValue ( inputStream , ErrorResponse . class ) ; if ( ridHeader != null ) { LOG . debug ( "DocumentRequest ID " + ridHeader ) ; } if ( ecHeader != null ) { errorResponse . setCode ( ecHeader ) ; } if ( 429 == status ) { String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. " + "This could be caused by multiple processes or threads making Rosette API calls in parallel, " + "or if your httpClient is configured with higher concurrency than your plan allows." ; if ( emHeader == null ) { emHeader = concurrencyMessage ; } else { emHeader = concurrencyMessage + System . lineSeparator ( ) + emHeader ; } } if ( emHeader != null ) { errorResponse . setMessage ( emHeader ) ; } throw new HttpRosetteAPIException ( errorResponse , status ) ; } else { String errorContent ; if ( inputStream != null ) { byte [ ] content = getBytes ( inputStream ) ; errorContent = new String ( content , "utf-8" ) ; } else { errorContent = "(no body)" ; } throw new HttpRosetteAPIException ( "Invalid error response (not json)" , ErrorResponse . builder ( ) . code ( "invalidErrorResponse" ) . message ( errorContent ) . build ( ) , status ) ; } } else { return mapper . readValue ( inputStream , clazz ) ; } } } | Gets response from HTTP connection according to the specified response class ; throws for an error response . |
7,299 | public static String findSecrets ( File xmlFile ) throws SAXException , IOException , TransformerException { XMLReader xr = new XMLFilterImpl ( XMLReaderFactory . createXMLReader ( ) ) { private String tagName = "" ; public void startElement ( String uri , String localName , String qName , Attributes atts ) throws SAXException { tagName = qName ; super . startElement ( uri , localName , qName , atts ) ; } public void endElement ( String uri , String localName , String qName ) throws SAXException { tagName = "" ; super . endElement ( uri , localName , qName ) ; } public void characters ( char [ ] ch , int start , int length ) throws SAXException { if ( ! "" . equals ( tagName ) ) { String value = new String ( ch , start , length ) . trim ( ) ; if ( ! "" . equals ( value ) && ! "{}" . equals ( value ) ) { if ( ( Secret . decrypt ( value ) ) != null || SecretBytes . isSecretBytes ( value ) ) { ch = SECRET_MARKER . toCharArray ( ) ; start = 0 ; length = ch . length ; } } } super . characters ( ch , start , length ) ; } } ; String str = FileUtils . readFileToString ( xmlFile ) ; Source src = createSafeSource ( xr , new InputSource ( new StringReader ( str ) ) ) ; final ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; Result res = new StreamResult ( result ) ; TransformerFactory factory = TransformerFactory . newInstance ( ) ; factory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer transformer = factory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , OUTPUT_ENCODING ) ; try { transformer . transform ( src , res ) ; return result . toString ( "UTF-8" ) ; } catch ( TransformerException e ) { if ( ENABLE_FALLBACK ) { return findSecretFallback ( str ) ; } else { throw e ; } } } | find the secret in the xml file and replace it with the place holder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.