idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
32,500 | public static int hash ( ByteBuffer buf , int seed ) { ByteOrder byteOrder = buf . order ( ) ; buf . order ( ByteOrder . LITTLE_ENDIAN ) ; int m = 0x5bd1e995 ; int r = 24 ; int h = seed ^ buf . remaining ( ) ; while ( buf . remaining ( ) >= 4 ) { int k = buf . getInt ( ) ; k *= m ; k ^= k >>> r ; k *= m ; h *= m ; h ^= k ; } if ( buf . remaining ( ) > 0 ) { ByteBuffer finish = ByteBuffer . allocate ( 4 ) . order ( ByteOrder . LITTLE_ENDIAN ) ; finish . put ( buf ) . rewind ( ) ; h ^= finish . getInt ( ) ; h *= m ; } h ^= h >>> 13 ; h *= m ; h ^= h >>> 15 ; buf . order ( byteOrder ) ; return h ; } | Hashes the bytes in a buffer from the current position to the limit . |
32,501 | public String getTopologyJsonPayload ( Set < Host > activeHosts ) { int count = NUM_RETRIER_ACROSS_NODES ; String response ; Exception lastEx = null ; do { try { response = getTopologyFromRandomNodeWithRetry ( activeHosts ) ; if ( response != null ) { return response ; } } catch ( Exception e ) { lastEx = e ; } finally { count -- ; } } while ( ( count > 0 ) ) ; if ( lastEx != null ) { if ( lastEx instanceof ConnectTimeoutException ) { throw new TimeoutException ( "Unable to obtain topology" , lastEx ) ; } throw new DynoException ( lastEx ) ; } else { throw new DynoException ( "Could not contact dynomite for token map" ) ; } } | Tries to get topology information by randomly trying across nodes . |
32,502 | public Host getRandomHost ( Set < Host > activeHosts ) { Random random = new Random ( ) ; List < Host > hostsUp = new ArrayList < Host > ( CollectionUtils . filter ( activeHosts , new Predicate < Host > ( ) { public boolean apply ( Host x ) { return x . isUp ( ) ; } } ) ) ; return hostsUp . get ( random . nextInt ( hostsUp . size ( ) ) ) ; } | Finds a random host from the set of active hosts to perform cluster_describe |
32,503 | private String getTopologyFromRandomNodeWithRetry ( Set < Host > activeHosts ) { int count = NUM_RETRIES_PER_NODE ; String nodeResponse ; Exception lastEx ; final Host randomHost = getRandomHost ( activeHosts ) ; do { try { lastEx = null ; nodeResponse = getResponseViaHttp ( randomHost . getHostName ( ) ) ; if ( nodeResponse != null ) { Logger . info ( "Received topology from " + randomHost ) ; return nodeResponse ; } } catch ( Exception e ) { Logger . info ( "cannot get topology from : " + randomHost ) ; lastEx = e ; } finally { count -- ; } } while ( ( count > 0 ) ) ; if ( lastEx != null ) { if ( lastEx instanceof ConnectTimeoutException ) { throw new TimeoutException ( "Unable to obtain topology" , lastEx ) . setHost ( randomHost ) ; } throw new DynoException ( String . format ( "Unable to obtain topology from %s" , randomHost ) , lastEx ) ; } else { throw new DynoException ( String . format ( "Could not contact dynomite manager for token map on %s" , randomHost ) ) ; } } | Tries multiple nodes and it only bubbles up the last node s exception . We want to bubble up the exception in order for the last node to be removed from the connection pool . |
32,504 | List < HostToken > parseTokenListFromJson ( String json ) { List < HostToken > hostTokens = new ArrayList < HostToken > ( ) ; JSONParser parser = new JSONParser ( ) ; try { JSONArray arr = ( JSONArray ) parser . parse ( json ) ; Iterator < ? > iter = arr . iterator ( ) ; while ( iter . hasNext ( ) ) { Object item = iter . next ( ) ; if ( ! ( item instanceof JSONObject ) ) { continue ; } JSONObject jItem = ( JSONObject ) item ; Long token = Long . parseLong ( ( String ) jItem . get ( "token" ) ) ; String hostname = ( String ) jItem . get ( "hostname" ) ; String ipAddress = ( String ) jItem . get ( "ip" ) ; String zone = ( String ) jItem . get ( "zone" ) ; String datacenter = ( String ) jItem . get ( "dc" ) ; String portStr = ( String ) jItem . get ( "port" ) ; String securePortStr = ( String ) jItem . get ( "secure_port" ) ; String hashtag = ( String ) jItem . get ( "hashtag" ) ; int port = Host . DEFAULT_PORT ; if ( portStr != null ) { port = Integer . valueOf ( portStr ) ; } int securePort = port ; if ( securePortStr != null ) { securePort = Integer . valueOf ( securePortStr ) ; } Host host = new Host ( hostname , ipAddress , port , securePort , zone , datacenter , Status . Up , hashtag ) ; if ( isLocalDatacenterHost ( host ) ) { HostToken hostToken = new HostToken ( token , host ) ; hostTokens . add ( hostToken ) ; } } } catch ( ParseException e ) { Logger . error ( "Failed to parse json response: " + json , e ) ; throw new RuntimeException ( e ) ; } return hostTokens ; } | package - private for Test |
32,505 | public void start ( final BaseCallback < Authentication , AuthenticationException > callback ) { credentialsRequest . start ( new BaseCallback < Credentials , AuthenticationException > ( ) { public void onSuccess ( final Credentials credentials ) { userInfoRequest . addHeader ( HEADER_AUTHORIZATION , "Bearer " + credentials . getAccessToken ( ) ) . start ( new BaseCallback < UserProfile , AuthenticationException > ( ) { public void onSuccess ( UserProfile profile ) { callback . onSuccess ( new Authentication ( profile , credentials ) ) ; } public void onFailure ( AuthenticationException error ) { callback . onFailure ( error ) ; } } ) ; } public void onFailure ( AuthenticationException error ) { callback . onFailure ( error ) ; } } ) ; } | Starts the log in request and then fetches the user s profile |
32,506 | public Authentication execute ( ) throws Auth0Exception { Credentials credentials = credentialsRequest . execute ( ) ; UserProfile profile = userInfoRequest . addHeader ( HEADER_AUTHORIZATION , "Bearer " + credentials . getAccessToken ( ) ) . execute ( ) ; return new Authentication ( profile , credentials ) ; } | Logs in the user with Auth0 and fetches it s profile . |
32,507 | public Map < String , Object > getExtraInfo ( ) { return extraInfo != null ? new HashMap < > ( extraInfo ) : Collections . < String , Object > emptyMap ( ) ; } | Returns extra information of the profile that is not part of the normalized profile |
32,508 | public SignUpRequest addAuthenticationParameters ( Map < String , Object > parameters ) { authenticationRequest . addAuthenticationParameters ( parameters ) ; return this ; } | Add additional parameters sent when logging the user in |
32,509 | public void start ( final BaseCallback < Credentials , AuthenticationException > callback ) { signUpRequest . start ( new BaseCallback < DatabaseUser , AuthenticationException > ( ) { public void onSuccess ( final DatabaseUser user ) { authenticationRequest . start ( callback ) ; } public void onFailure ( AuthenticationException error ) { callback . onFailure ( error ) ; } } ) ; } | Starts to execute create user request and then logs the user in . |
32,510 | public void bindService ( ) { Log . v ( TAG , "Trying to bind the service" ) ; Context context = this . context . get ( ) ; isBound = false ; if ( context != null && preferredPackage != null ) { isBound = CustomTabsClient . bindCustomTabsService ( context , preferredPackage , this ) ; } Log . v ( TAG , "Bind request result: " + isBound ) ; } | Attempts to bind the Custom Tabs Service to the Context . |
32,511 | public void unbindService ( ) { Log . v ( TAG , "Trying to unbind the service" ) ; Context context = this . context . get ( ) ; if ( isBound && context != null ) { context . unbindService ( this ) ; isBound = false ; } } | Attempts to unbind the Custom Tabs Service from the Context . |
32,512 | public void getToken ( String authorizationCode , final AuthCallback callback ) { apiClient . token ( authorizationCode , redirectUri ) . setCodeVerifier ( codeVerifier ) . start ( new BaseCallback < Credentials , AuthenticationException > ( ) { public void onSuccess ( Credentials payload ) { callback . onSuccess ( payload ) ; } public void onFailure ( AuthenticationException error ) { if ( "Unauthorized" . equals ( error . getDescription ( ) ) ) { Log . e ( TAG , "Please go to 'https://manage.auth0.com/#/applications/" + apiClient . getClientId ( ) + "/settings' and set 'Client Type' to 'Native' to enable PKCE." ) ; } callback . onFailure ( error ) ; } } ) ; } | Performs a request to the Auth0 API to get the OAuth Token and end the PKCE flow . The instance of this class must be disposed after this method is called . |
32,513 | private boolean checkPermissions ( Activity activity ) { String [ ] permissions = getRequiredAndroidPermissions ( ) ; return handler . areAllPermissionsGranted ( activity , permissions ) ; } | Checks if all the required Android Manifest . permissions have already been granted . |
32,514 | private void requestPermissions ( Activity activity , int requestCode ) { String [ ] permissions = getRequiredAndroidPermissions ( ) ; handler . requestPermissions ( activity , permissions , requestCode ) ; } | Starts the async Permission Request . The caller activity will be notified of the result on the onRequestPermissionsResult method from the ActivityCompat . OnRequestPermissionsResultCallback interface . |
32,515 | public DelegationRequest < T > addParameters ( Map < String , Object > parameters ) { request . addParameters ( parameters ) ; return this ; } | Add additional parameters to be sent in the request |
32,516 | public DelegationRequest < T > setScope ( String scope ) { request . addParameter ( ParameterBuilder . SCOPE_KEY , scope ) ; return this ; } | Set the scope used to make the delegation |
32,517 | @ SuppressWarnings ( "WeakerAccess" ) private ParameterizableRequest < Void , AuthenticationException > passwordless ( ) { HttpUrl url = HttpUrl . parse ( auth0 . getDomainUrl ( ) ) . newBuilder ( ) . addPathSegment ( PASSWORDLESS_PATH ) . addPathSegment ( START_PATH ) . build ( ) ; final Map < String , Object > parameters = ParameterBuilder . newBuilder ( ) . setClientId ( getClientId ( ) ) . asDictionary ( ) ; return factory . POST ( url , client , gson , authErrorBuilder ) . addParameters ( parameters ) ; } | Start a custom passwordless flow |
32,518 | public AuthenticationRequest setConnection ( String connection ) { if ( ! hasLegacyPath ( ) ) { Log . w ( TAG , "Not setting the 'connection' parameter as the request is using a OAuth 2.0 API Authorization endpoint that doesn't support it." ) ; return this ; } addParameter ( CONNECTION_KEY , connection ) ; return this ; } | Sets the connection parameter . |
32,519 | public AuthenticationRequest setRealm ( String realm ) { if ( hasLegacyPath ( ) ) { Log . w ( TAG , "Not setting the 'realm' parameter as the request is using a Legacy Authorization API endpoint that doesn't support it." ) ; return this ; } addParameter ( REALM_KEY , realm ) ; return this ; } | Sets the realm parameter . A realm identifies the host against which the authentication will be made and usually helps to know which username and password to use . |
32,520 | public DatabaseConnectionRequest < T , U > addParameters ( Map < String , Object > parameters ) { request . addParameters ( parameters ) ; return this ; } | Add the given parameters to the request |
32,521 | public DatabaseConnectionRequest < T , U > addParameter ( String name , Object value ) { request . addParameter ( name , value ) ; return this ; } | Add a parameter by name to the request |
32,522 | public DatabaseConnectionRequest < T , U > setConnection ( String connection ) { request . addParameter ( ParameterBuilder . CONNECTION_KEY , connection ) ; return this ; } | Set the Auth0 Database Connection used for this request using its name . |
32,523 | public OkHttpClient createClient ( boolean loggingEnabled , boolean tls12Enforced , int connectTimeout , int readTimeout , int writeTimeout ) { return modifyClient ( new OkHttpClient ( ) , loggingEnabled , tls12Enforced , connectTimeout , readTimeout , writeTimeout ) ; } | This method creates an instance of OKHttpClient according to the provided parameters . It is used internally and is not intended to be used directly . |
32,524 | private void enforceTls12 ( OkHttpClient client ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . JELLY_BEAN || Build . VERSION . SDK_INT > Build . VERSION_CODES . LOLLIPOP ) { return ; } try { SSLContext sc = SSLContext . getInstance ( "TLSv1.2" ) ; sc . init ( null , null , null ) ; client . setSslSocketFactory ( new TLS12SocketFactory ( sc . getSocketFactory ( ) ) ) ; ConnectionSpec cs = new ConnectionSpec . Builder ( ConnectionSpec . MODERN_TLS ) . tlsVersions ( TlsVersion . TLS_1_2 ) . build ( ) ; List < ConnectionSpec > specs = new ArrayList < > ( ) ; specs . add ( cs ) ; specs . add ( ConnectionSpec . COMPATIBLE_TLS ) ; specs . add ( ConnectionSpec . CLEARTEXT ) ; client . setConnectionSpecs ( specs ) ; } catch ( NoSuchAlgorithmException | KeyManagementException e ) { Log . e ( TAG , "Error while setting TLS 1.2" , e ) ; } } | Enable TLS 1 . 2 on the OkHttpClient on API 16 - 21 which is supported but not enabled by default . |
32,525 | public ParameterBuilder addAll ( Map < String , Object > parameters ) { if ( parameters != null ) { for ( String k : parameters . keySet ( ) ) { if ( parameters . get ( k ) != null ) { this . parameters . put ( k , parameters . get ( k ) ) ; } } } return this ; } | Adds all parameter from a map |
32,526 | public boolean isValid ( int expectedRequestCode ) { Uri uri = intent != null ? intent . getData ( ) : null ; if ( uri == null ) { Log . d ( TAG , "Result is invalid: Received Intent's Uri is null." ) ; return false ; } if ( requestCode == MISSING_REQUEST_CODE ) { return true ; } boolean fromRequest = getRequestCode ( ) == expectedRequestCode ; if ( ! fromRequest ) { Log . d ( TAG , String . format ( "Result is invalid: Received Request Code doesn't match the expected one. Was %d but expected %d" , getRequestCode ( ) , expectedRequestCode ) ) ; } return fromRequest && resultCode == Activity . RESULT_OK ; } | Checks if the received data is valid and can be parsed . |
32,527 | public boolean hasValidCredentials ( ) { String accessToken = storage . retrieveString ( KEY_ACCESS_TOKEN ) ; String refreshToken = storage . retrieveString ( KEY_REFRESH_TOKEN ) ; String idToken = storage . retrieveString ( KEY_ID_TOKEN ) ; Long expiresAt = storage . retrieveLong ( KEY_EXPIRES_AT ) ; return ! ( isEmpty ( accessToken ) && isEmpty ( idToken ) || expiresAt == null || expiresAt <= getCurrentTimeInMillis ( ) && refreshToken == null ) ; } | Checks if a non - expired pair of credentials can be obtained from this manager . |
32,528 | public void clearCredentials ( ) { storage . remove ( KEY_ACCESS_TOKEN ) ; storage . remove ( KEY_REFRESH_TOKEN ) ; storage . remove ( KEY_ID_TOKEN ) ; storage . remove ( KEY_TOKEN_TYPE ) ; storage . remove ( KEY_EXPIRES_AT ) ; storage . remove ( KEY_SCOPE ) ; } | Removes the credentials from the storage if present . |
32,529 | public void clearCredentials ( ) { storage . remove ( KEY_CREDENTIALS ) ; storage . remove ( KEY_EXPIRES_AT ) ; storage . remove ( KEY_CAN_REFRESH ) ; Log . d ( TAG , "Credentials were just removed from the storage" ) ; } | Delete the stored credentials |
32,530 | public boolean hasValidCredentials ( ) { String encryptedEncoded = storage . retrieveString ( KEY_CREDENTIALS ) ; Long expiresAt = storage . retrieveLong ( KEY_EXPIRES_AT ) ; Boolean canRefresh = storage . retrieveBoolean ( KEY_CAN_REFRESH ) ; return ! ( isEmpty ( encryptedEncoded ) || expiresAt == null || expiresAt <= getCurrentTimeInMillis ( ) && ( canRefresh == null || ! canRefresh ) ) ; } | Returns whether this manager contains a valid non - expired pair of credentials . |
32,531 | public boolean hasNext ( ) { if ( ! members . hasNext ( ) ) { try { getNextEntries ( ) ; } catch ( final Exception ignored ) { LOG . error ( "An error occured while getting next entries" , ignored ) ; } } return members . hasNext ( ) ; } | Returns true if more entries are available . |
32,532 | public ClientEntry next ( ) { if ( hasNext ( ) ) { final Entry romeEntry = members . next ( ) ; try { if ( ! romeEntry . isMediaEntry ( ) ) { return new ClientEntry ( null , collection , romeEntry , true ) ; } else { return new ClientMediaEntry ( null , collection , romeEntry , true ) ; } } catch ( final ProponoException e ) { throw new RuntimeException ( "Unexpected exception creating ClientEntry or ClientMedia" , e ) ; } } throw new NoSuchElementException ( ) ; } | Get next entry in collection . |
32,533 | public ClientEntry getEntry ( final String uri ) throws ProponoException { final GetMethod method = new GetMethod ( uri ) ; authStrategy . addAuthentication ( httpClient , method ) ; try { httpClient . executeMethod ( method ) ; if ( method . getStatusCode ( ) != 200 ) { throw new ProponoException ( "ERROR HTTP status code=" + method . getStatusCode ( ) ) ; } final Entry romeEntry = Atom10Parser . parseEntry ( new InputStreamReader ( method . getResponseBodyAsStream ( ) ) , uri , Locale . US ) ; if ( ! romeEntry . isMediaEntry ( ) ) { return new ClientEntry ( service , this , romeEntry , false ) ; } else { return new ClientMediaEntry ( service , this , romeEntry , false ) ; } } catch ( final Exception e ) { throw new ProponoException ( "ERROR: getting or parsing entry/media, HTTP code: " , e ) ; } finally { method . releaseConnection ( ) ; } } | Get full entry specified by entry edit URI . Note that entry may or may not be associated with this collection . |
32,534 | public ClientMediaEntry createMediaEntry ( final String title , final String slug , final String contentType , final byte [ ] bytes ) throws ProponoException { if ( ! isWritable ( ) ) { throw new ProponoException ( "Collection is not writable" ) ; } return new ClientMediaEntry ( service , this , title , slug , contentType , bytes ) ; } | Create new media entry assocaited with collection but do not save . server . Depending on the Atom server you may or may not be able to persist the properties of the entry that is returned . |
32,535 | public ClientMediaEntry createMediaEntry ( final String title , final String slug , final String contentType , final InputStream is ) throws ProponoException { if ( ! isWritable ( ) ) { throw new ProponoException ( "Collection is not writable" ) ; } return new ClientMediaEntry ( service , this , title , slug , contentType , is ) ; } | Create new media entry assocaited with collection but do not save . server . Depending on the Atom server you may or may not be able to . persist the properties of the entry that is returned . |
32,536 | public Module parse ( final Element elem , final Locale locale ) { final AppModule m = new AppModuleImpl ( ) ; final Element control = elem . getChild ( "control" , getContentNamespace ( ) ) ; if ( control != null ) { final Element draftElem = control . getChild ( "draft" , getContentNamespace ( ) ) ; if ( draftElem != null ) { if ( "yes" . equals ( draftElem . getText ( ) ) ) { m . setDraft ( Boolean . TRUE ) ; } if ( "no" . equals ( draftElem . getText ( ) ) ) { m . setDraft ( Boolean . FALSE ) ; } } } final Element edited = elem . getChild ( "edited" , getContentNamespace ( ) ) ; if ( edited != null ) { try { m . setEdited ( DateParser . parseW3CDateTime ( edited . getTextTrim ( ) , locale ) ) ; } catch ( final Exception ignored ) { } } return m ; } | Parse JDOM element into module |
32,537 | public InputStream getAsStream ( ) throws ProponoException { if ( getContents ( ) != null && ! getContents ( ) . isEmpty ( ) ) { final Content c = getContents ( ) . get ( 0 ) ; if ( c . getSrc ( ) != null ) { return getResourceAsStream ( ) ; } else if ( inputStream != null ) { return inputStream ; } else if ( bytes != null ) { return new ByteArrayInputStream ( bytes ) ; } else { throw new ProponoException ( "ERROR: no src URI or binary data to return" ) ; } } else { throw new ProponoException ( "ERROR: no content found in entry" ) ; } } | Get media resource as an InputStream should work regardless of whether you set the media resource data as an InputStream or as a byte array . |
32,538 | public void update ( ) throws ProponoException { if ( partial ) { throw new ProponoException ( "ERROR: attempt to update partial entry" ) ; } EntityEnclosingMethod method = null ; final Content updateContent = getContents ( ) . get ( 0 ) ; try { if ( getMediaLinkURI ( ) != null && getBytes ( ) != null ) { method = new PutMethod ( getMediaLinkURI ( ) ) ; if ( inputStream != null ) { method . setRequestEntity ( new InputStreamRequestEntity ( inputStream ) ) ; } else { method . setRequestEntity ( new InputStreamRequestEntity ( new ByteArrayInputStream ( getBytes ( ) ) ) ) ; } method . setRequestHeader ( "Content-type" , updateContent . getType ( ) ) ; } else if ( getEditURI ( ) != null ) { method = new PutMethod ( getEditURI ( ) ) ; final StringWriter sw = new StringWriter ( ) ; Atom10Generator . serializeEntry ( this , sw ) ; method . setRequestEntity ( new StringRequestEntity ( sw . toString ( ) , null , null ) ) ; method . setRequestHeader ( "Content-type" , "application/atom+xml; charset=utf8" ) ; } else { throw new ProponoException ( "ERROR: media entry has no edit URI or media-link URI" ) ; } getCollection ( ) . addAuthentication ( method ) ; method . addRequestHeader ( "Title" , getTitle ( ) ) ; getCollection ( ) . getHttpClient ( ) . executeMethod ( method ) ; if ( inputStream != null ) { inputStream . close ( ) ; } final InputStream is = method . getResponseBodyAsStream ( ) ; if ( method . getStatusCode ( ) != 200 && method . getStatusCode ( ) != 201 ) { throw new ProponoException ( "ERROR HTTP status=" + method . getStatusCode ( ) + " : " + Utilities . streamToString ( is ) ) ; } } catch ( final Exception e ) { throw new ProponoException ( "ERROR: saving media entry" ) ; } if ( method . getStatusCode ( ) != 201 ) { throw new ProponoException ( "ERROR HTTP status=" + method . getStatusCode ( ) ) ; } } | Update entry on server . |
32,539 | public final synchronized void setSyndFeed ( final SyndFeed feed ) { super . setSyndFeed ( feed ) ; changedMap . clear ( ) ; final List < SyndEntry > entries = feed . getEntries ( ) ; for ( final SyndEntry entry : entries ) { final String currentEntryTag = computeEntryTag ( entry ) ; final String previousEntryTag = entryTagsMap . get ( entry . getUri ( ) ) ; if ( previousEntryTag == null || ! currentEntryTag . equals ( previousEntryTag ) ) { changedMap . put ( entry . getUri ( ) , Boolean . TRUE ) ; } entryTagsMap . put ( entry . getUri ( ) , currentEntryTag ) ; } } | Overrides super class method to update changedMap and entryTagsMap for tracking changed entries . |
32,540 | public void setContent ( final String contentString , final String type ) { final Content newContent = new Content ( ) ; newContent . setType ( type == null ? Content . HTML : type ) ; newContent . setValue ( contentString ) ; final ArrayList < Content > contents = new ArrayList < Content > ( ) ; contents . add ( newContent ) ; setContents ( contents ) ; } | Set content of entry . |
32,541 | public void setContent ( final Content c ) { final ArrayList < Content > contents = new ArrayList < Content > ( ) ; contents . add ( c ) ; setContents ( contents ) ; } | Convenience method to set first content object in content collection . Atom 1 . 0 allows only one content element per entry . |
32,542 | public Content getContent ( ) { if ( getContents ( ) != null && ! getContents ( ) . isEmpty ( ) ) { final Content c = getContents ( ) . get ( 0 ) ; return c ; } return null ; } | Convenience method to get first content object in content collection . Atom 1 . 0 allows only one content element per entry . |
32,543 | public void remove ( ) throws ProponoException { if ( getEditURI ( ) == null ) { throw new ProponoException ( "ERROR: cannot delete unsaved entry" ) ; } final DeleteMethod method = new DeleteMethod ( getEditURI ( ) ) ; addAuthentication ( method ) ; try { getHttpClient ( ) . executeMethod ( method ) ; } catch ( final IOException ex ) { throw new ProponoException ( "ERROR: removing entry, HTTP code" , ex ) ; } finally { method . releaseConnection ( ) ; } } | Remove entry from server . |
32,544 | public String getEditURI ( ) { for ( int i = 0 ; i < getOtherLinks ( ) . size ( ) ; i ++ ) { final Link link = getOtherLinks ( ) . get ( i ) ; if ( link . getRel ( ) != null && link . getRel ( ) . equals ( "edit" ) ) { return link . getHrefResolved ( ) ; } } return null ; } | Get the URI that can be used to edit the entry via HTTP PUT or DELETE . |
32,545 | public void setDefaultContentIndex ( final Integer defaultContentIndex ) { for ( int i = 0 ; i < getContents ( ) . length ; i ++ ) { if ( i == defaultContentIndex . intValue ( ) ) { getContents ( ) [ i ] . setDefaultContent ( true ) ; } else { getContents ( ) [ i ] . setDefaultContent ( false ) ; } } this . defaultContentIndex = defaultContentIndex ; } | Default content index MediaContent . |
32,546 | public Element workspaceToElement ( ) { final Workspace space = this ; final Element element = new Element ( "workspace" , AtomService . ATOM_PROTOCOL ) ; final Element titleElem = new Element ( "title" , AtomService . ATOM_FORMAT ) ; titleElem . setText ( space . getTitle ( ) ) ; if ( space . getTitleType ( ) != null && ! space . getTitleType ( ) . equals ( "TEXT" ) ) { titleElem . setAttribute ( "type" , space . getTitleType ( ) , AtomService . ATOM_FORMAT ) ; } element . addContent ( titleElem ) ; for ( final Collection col : space . getCollections ( ) ) { element . addContent ( col . collectionToElement ( ) ) ; } return element ; } | Serialize an AtomService . DefaultWorkspace object into an XML element |
32,547 | protected void parseWorkspaceElement ( final Element element ) throws ProponoException { final Element titleElem = element . getChild ( "title" , AtomService . ATOM_FORMAT ) ; setTitle ( titleElem . getText ( ) ) ; if ( titleElem . getAttribute ( "type" , AtomService . ATOM_FORMAT ) != null ) { setTitleType ( titleElem . getAttribute ( "type" , AtomService . ATOM_FORMAT ) . getValue ( ) ) ; } final List < Element > collections = element . getChildren ( "collection" , AtomService . ATOM_PROTOCOL ) ; for ( final Element e : collections ) { addCollection ( new Collection ( e ) ) ; } } | Deserialize a Atom workspace XML element into an object |
32,548 | public Workspace findWorkspace ( final String title ) { for ( final Object element : workspaces ) { final Workspace ws = ( Workspace ) element ; if ( title . equals ( ws . getTitle ( ) ) ) { return ws ; } } return null ; } | Find workspace by title . |
32,549 | public Document serviceToDocument ( ) { final AtomService service = this ; final Document doc = new Document ( ) ; final Element root = new Element ( "service" , ATOM_PROTOCOL ) ; doc . setRootElement ( root ) ; final List < Workspace > spaces = service . getWorkspaces ( ) ; for ( final Workspace space : spaces ) { root . addContent ( space . workspaceToElement ( ) ) ; } return doc ; } | Serialize an AtomService object into an XML document |
32,550 | public synchronized void sortOnProperty ( final Object value , final boolean ascending , final ValueStrategy strategy ) { final int elementCount = size ( ) ; for ( int i = 0 ; i < elementCount - 1 ; i ++ ) { for ( int j = i + 1 ; j < elementCount ; j ++ ) { final T entry1 = get ( i ) ; final T entry2 = get ( j ) ; final EntryValue oc1 = strategy . getValue ( entry1 , value ) ; final EntryValue oc2 = strategy . getValue ( entry2 , value ) ; if ( oc1 != oc2 ) { final boolean bothNotNull = oc1 != null && oc2 != null ; if ( ascending ) { if ( oc2 == null || bothNotNull && oc2 . compareTo ( oc1 ) < 0 ) { set ( i , entry2 ) ; set ( j , entry1 ) ; } } else { if ( oc1 == null || bothNotNull && oc1 . compareTo ( oc2 ) < 0 ) { set ( i , entry2 ) ; set ( j , entry1 ) ; } } } } } } | performs a selection sort on all the beans in the List |
32,551 | public InputStream getAsStream ( ) throws BlogClientException { final HttpClient httpClient = new HttpClient ( ) ; final GetMethod method = new GetMethod ( permalink ) ; try { httpClient . executeMethod ( method ) ; } catch ( final Exception e ) { throw new BlogClientException ( "ERROR: error reading file" , e ) ; } if ( method . getStatusCode ( ) != 200 ) { throw new BlogClientException ( "ERROR HTTP status=" + method . getStatusCode ( ) ) ; } try { return method . getResponseBodyAsStream ( ) ; } catch ( final Exception e ) { throw new BlogClientException ( "ERROR: error reading file" , e ) ; } } | Get media resource as input stream . |
32,552 | protected SAXBuilder createSAXBuilder ( ) { SAXBuilder saxBuilder ; if ( validate ) { saxBuilder = new SAXBuilder ( XMLReaders . DTDVALIDATING ) ; } else { saxBuilder = new SAXBuilder ( XMLReaders . NONVALIDATING ) ; } saxBuilder . setEntityResolver ( RESOLVER ) ; try { final XMLReader parser = saxBuilder . createParser ( ) ; setFeature ( saxBuilder , parser , "http://xml.org/sax/features/external-general-entities" , false ) ; setFeature ( saxBuilder , parser , "http://xml.org/sax/features/external-parameter-entities" , false ) ; setFeature ( saxBuilder , parser , "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; if ( ! allowDoctypes ) { setFeature ( saxBuilder , parser , "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; } } catch ( final JDOMException e ) { throw new IllegalStateException ( "JDOM could not create a SAX parser" , e ) ; } saxBuilder . setExpandEntities ( false ) ; return saxBuilder ; } | Creates and sets up a org . jdom2 . input . SAXBuilder for parsing . |
32,553 | public String getRootCauseMessage ( ) { String rcmessage = null ; if ( getRootCause ( ) != null ) { if ( getRootCause ( ) . getCause ( ) != null ) { rcmessage = getRootCause ( ) . getCause ( ) . getMessage ( ) ; } rcmessage = rcmessage == null ? getRootCause ( ) . getMessage ( ) : rcmessage ; rcmessage = rcmessage == null ? super . getMessage ( ) : rcmessage ; rcmessage = rcmessage == null ? "NONE" : rcmessage ; } return rcmessage ; } | Get root cause message . |
32,554 | public String getHrefResolved ( ) { if ( Atom10Parser . isAbsoluteURI ( href ) ) { return href ; } else if ( baseURI != null && categoriesElement != null ) { return Atom10Parser . resolveURI ( baseURI , categoriesElement , href ) ; } return null ; } | Get unresolved URI of the collection or null if impossible to determine |
32,555 | public static < T > List < T > createWhenNull ( final List < T > list ) { if ( list == null ) { return new ArrayList < T > ( ) ; } else { return list ; } } | Returns the list when it is not null . Returns a new list otherwise . |
32,556 | public static < T > List < T > create ( final T item ) { final List < T > list = new ArrayList < T > ( ) ; list . add ( item ) ; return list ; } | Creates a new List with the given item as the first entry . |
32,557 | public static < T > T firstEntry ( final List < T > list ) { if ( list != null && ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } else { return null ; } } | Extracts the first entry of the list when it is not null and contains values . |
32,558 | public static boolean sizeIs ( final List < ? > list , final int size ) { if ( size == 0 ) { return list == null || list . isEmpty ( ) ; } else { return list != null && list . size ( ) == size ; } } | Checks whether the list has the given size . A null list is treated like a list without entries . |
32,559 | public static < T > List < T > emptyToNull ( final List < T > list ) { if ( isEmpty ( list ) ) { return null ; } else { return list ; } } | Returns null when the given list is empty or null |
32,560 | public static Long parseLong ( final String str ) { if ( null != str ) { try { return new Long ( Long . parseLong ( str . trim ( ) ) ) ; } catch ( final Exception e ) { } } return null ; } | Parses a Long out of a string . |
32,561 | public static Float parseFloat ( final String str ) { if ( null != str ) { try { return new Float ( Float . parseFloat ( str . trim ( ) ) ) ; } catch ( final Exception e ) { } } return null ; } | Parse a Float from a String without exceptions . If the String is not a Float then null is returned |
32,562 | public static float parseFloat ( final String str , final float def ) { final Float result = parseFloat ( str ) ; if ( result == null ) { return def ; } else { return result . floatValue ( ) ; } } | Parse a float from a String with a default value |
32,563 | public static long parseLong ( final String str , final long def ) { final Long ret = parseLong ( str ) ; if ( ret == null ) { return def ; } else { return ret . longValue ( ) ; } } | Parses a long out of a string . |
32,564 | public static PropertiesLoader getPropertiesLoader ( ) { synchronized ( PropertiesLoader . class ) { final ClassLoader classLoader = ConfigurableClassLoader . INSTANCE . getClassLoader ( ) ; PropertiesLoader loader = clMap . get ( classLoader ) ; if ( loader == null ) { try { loader = new PropertiesLoader ( MASTER_PLUGIN_FILE , EXTRA_PLUGIN_FILE ) ; clMap . put ( classLoader , loader ) ; } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } } return loader ; } } | Returns the PropertiesLoader singleton used by ROME to load plugin components . |
32,565 | public static void serializeEntry ( final Entry entry , final Writer writer ) throws IllegalArgumentException , FeedException , IOException { final List < Entry > entries = new ArrayList < Entry > ( ) ; entries . add ( entry ) ; final Feed feed1 = new Feed ( ) ; feed1 . setFeedType ( "atom_1.0" ) ; feed1 . setEntries ( entries ) ; final WireFeedOutput wireFeedOutput = new WireFeedOutput ( ) ; final Document feedDoc = wireFeedOutput . outputJDom ( feed1 ) ; final Element entryElement = feedDoc . getRootElement ( ) . getChildren ( ) . get ( 0 ) ; final XMLOutputter outputter = new XMLOutputter ( ) ; outputter . output ( entryElement , writer ) ; } | Utility method to serialize an entry to writer . |
32,566 | public SyndFeed retrieveFeed ( final String userAgent , final URL feedUrl ) throws IllegalArgumentException , IOException , FeedException , FetcherException { if ( feedUrl == null ) { throw new IllegalArgumentException ( "null is not a valid URL" ) ; } final URLConnection connection = feedUrl . openConnection ( ) ; if ( ! ( connection instanceof HttpURLConnection ) ) { throw new IllegalArgumentException ( feedUrl . toExternalForm ( ) + " is not a valid HTTP Url" ) ; } final HttpURLConnection httpConnection = ( HttpURLConnection ) connection ; if ( connectTimeout >= 0 ) { httpConnection . setConnectTimeout ( connectTimeout ) ; } final FeedFetcherCache cache = getFeedInfoCache ( ) ; if ( cache != null ) { SyndFeedInfo syndFeedInfo = cache . getFeedInfo ( feedUrl ) ; setRequestHeaders ( connection , syndFeedInfo , userAgent ) ; httpConnection . connect ( ) ; try { fireEvent ( FetcherEvent . EVENT_TYPE_FEED_POLLED , connection ) ; if ( syndFeedInfo == null ) { syndFeedInfo = new SyndFeedInfo ( ) ; retrieveAndCacheFeed ( feedUrl , syndFeedInfo , httpConnection ) ; } else { final int responseCode = httpConnection . getResponseCode ( ) ; if ( responseCode != HttpURLConnection . HTTP_NOT_MODIFIED ) { retrieveAndCacheFeed ( feedUrl , syndFeedInfo , httpConnection ) ; } else { fireEvent ( FetcherEvent . EVENT_TYPE_FEED_UNCHANGED , connection ) ; } } return syndFeedInfo . getSyndFeed ( ) ; } finally { httpConnection . disconnect ( ) ; } } else { fireEvent ( FetcherEvent . EVENT_TYPE_FEED_POLLED , connection ) ; InputStream inputStream = null ; setRequestHeaders ( connection , null , userAgent ) ; httpConnection . connect ( ) ; try { inputStream = httpConnection . getInputStream ( ) ; return getSyndFeedFromStream ( inputStream , connection ) ; } catch ( final java . io . IOException e ) { handleErrorCodes ( ( ( HttpURLConnection ) connection ) . getResponseCode ( ) ) ; } finally { IO . close ( inputStream ) ; httpConnection . disconnect ( ) ; } return null ; } } | Retrieve a feed over HTTP |
32,567 | private static Object newInstance ( final String className , ClassLoader cl , final boolean doFallback ) throws ConfigurationError { try { Class < ? > providerClass ; if ( cl == null ) { providerClass = Class . forName ( className ) ; } else { try { providerClass = cl . loadClass ( className ) ; } catch ( final ClassNotFoundException x ) { if ( doFallback ) { cl = FactoryFinder . class . getClassLoader ( ) ; providerClass = cl . loadClass ( className ) ; } else { throw x ; } } } final Object instance = providerClass . newInstance ( ) ; dPrint ( "created new instance of " + providerClass + " using ClassLoader: " + cl ) ; return instance ; } catch ( final ClassNotFoundException x ) { throw new ConfigurationError ( "Provider " + className + " not found" , x ) ; } catch ( final Exception x ) { throw new ConfigurationError ( "Provider " + className + " could not be instantiated: " + x , x ) ; } } | Create an instance of a class using the specified ClassLoader and optionally fall back to the current ClassLoader if not found . |
32,568 | static Object find ( final String factoryId , final String fallbackClassName ) throws ConfigurationError { ClassLoader classLoader = ss . getContextClassLoader ( ) ; if ( classLoader == null ) { classLoader = FactoryFinder . class . getClassLoader ( ) ; } dPrint ( "find factoryId =" + factoryId ) ; try { final String systemProp = ss . getSystemProperty ( factoryId ) ; if ( systemProp != null ) { dPrint ( "found system property, value=" + systemProp ) ; return newInstance ( systemProp , classLoader , true ) ; } } catch ( final SecurityException se ) { } try { final String configFile = "/propono.properties" ; String factoryClassName = null ; if ( firstTime ) { synchronized ( cacheProps ) { if ( firstTime ) { try { final InputStream is = FactoryFinder . class . getResourceAsStream ( configFile ) ; firstTime = false ; if ( is != null ) { dPrint ( "Read properties file: " + configFile ) ; cacheProps . load ( is ) ; } } catch ( final Exception intentionallyIgnored ) { } } } } factoryClassName = cacheProps . getProperty ( factoryId ) ; if ( factoryClassName != null ) { dPrint ( "found in $java.home/propono.properties, value=" + factoryClassName ) ; return newInstance ( factoryClassName , classLoader , true ) ; } } catch ( final Exception ex ) { if ( debug ) { ex . printStackTrace ( ) ; } } final Object provider = findJarServiceProvider ( factoryId ) ; if ( provider != null ) { return provider ; } if ( fallbackClassName == null ) { throw new ConfigurationError ( "Provider for " + factoryId + " cannot be found" , null ) ; } dPrint ( "loaded from fallback value: " + fallbackClassName ) ; return newInstance ( fallbackClassName , classLoader , true ) ; } | Finds the implementation Class object in the specified order . Main entry point . |
32,569 | public static Double parse ( final String s ) { Double parsed = null ; try { if ( s != null ) { parsed = Double . parseDouble ( s ) ; } } catch ( final NumberFormatException e ) { } return parsed ; } | Converts a String into an Double . |
32,570 | public static PriceTypeEnumeration findByValue ( final String value ) { if ( value . equalsIgnoreCase ( "negotiable" ) ) { return PriceTypeEnumeration . NEGOTIABLE ; } else { return PriceTypeEnumeration . STARTING ; } } | Returns a PriceTypeEnumeration based on the String value or null . |
32,571 | protected void populateChannel ( final Channel channel , final Element eChannel ) { final String title = channel . getTitle ( ) ; if ( title != null ) { eChannel . addContent ( generateSimpleElement ( "title" , title ) ) ; } final String link = channel . getLink ( ) ; if ( link != null ) { eChannel . addContent ( generateSimpleElement ( "link" , link ) ) ; } final String description = channel . getDescription ( ) ; if ( description != null ) { eChannel . addContent ( generateSimpleElement ( "description" , description ) ) ; } } | Populates the given channel with parsed data from the ROME element that holds the channel data . |
32,572 | protected SyndEntry createSyndEntry ( final Item item , final boolean preserveWireItem ) { final SyndEntry syndEntry = super . createSyndEntry ( item , preserveWireItem ) ; final Description desc = item . getDescription ( ) ; if ( desc != null ) { final SyndContent descContent = new SyndContentImpl ( ) ; descContent . setType ( desc . getType ( ) ) ; descContent . setValue ( desc . getValue ( ) ) ; syndEntry . setDescription ( descContent ) ; } final Content cont = item . getContent ( ) ; if ( cont != null ) { final SyndContent contContent = new SyndContentImpl ( ) ; contContent . setType ( cont . getType ( ) ) ; contContent . setValue ( cont . getValue ( ) ) ; final List < SyndContent > contents = new ArrayList < SyndContent > ( ) ; contents . add ( contContent ) ; syndEntry . setContents ( contents ) ; } return syndEntry ; } | rss . description - > synd . description |
32,573 | protected void doDelete ( final HttpServletRequest req , final HttpServletResponse res ) throws ServletException , IOException { LOG . debug ( "Entering" ) ; final AtomHandler handler = createAtomRequestHandler ( req , res ) ; final String userName = handler . getAuthenticatedUsername ( ) ; if ( userName != null ) { final AtomRequest areq = new AtomRequestImpl ( req ) ; try { if ( handler . isEntryURI ( areq ) ) { handler . deleteEntry ( areq ) ; res . setStatus ( HttpServletResponse . SC_OK ) ; } else { res . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; } } catch ( final AtomException ae ) { res . sendError ( ae . getStatus ( ) , ae . getMessage ( ) ) ; LOG . debug ( "An error occured while processing DELETE" , ae ) ; } catch ( final Exception e ) { res . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , e . getMessage ( ) ) ; LOG . debug ( "An error occured while processing DELETE" , e ) ; } } else { res . setHeader ( "WWW-Authenticate" , "BASIC realm=\"AtomPub\"" ) ; res . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; } LOG . debug ( "Exiting" ) ; } | Handle Atom DELETE by calling appropriate handler . |
32,574 | public String getAttributeValue ( final String name ) { final List < Attribute > attributes = Collections . synchronizedList ( getAttributes ( ) ) ; for ( int i = 0 ; i < attributes . size ( ) ; i ++ ) { final Attribute a = attributes . get ( i ) ; if ( a . getName ( ) != null && a . getName ( ) . equals ( name ) ) { return a . getValue ( ) ; } } return null ; } | Returns the value of an attribute on the outline or null . |
32,575 | public void sendUpdateNotification ( final String hub , final String topic ) throws NotificationException { try { final StringBuilder sb = new StringBuilder ( "hub.mode=publish&hub.url=" ) . append ( URLEncoder . encode ( topic , "UTF-8" ) ) ; final URL hubUrl = new URL ( hub ) ; final HttpURLConnection connection = ( HttpURLConnection ) hubUrl . openConnection ( ) ; connection . setRequestProperty ( "User-Agent" , "ROME-Certiorem" ) ; connection . setRequestProperty ( "ContentType" , "application/x-www-form-urlencoded" ) ; connection . setDoOutput ( true ) ; connection . connect ( ) ; final OutputStream os = connection . getOutputStream ( ) ; os . write ( sb . toString ( ) . getBytes ( "UTF-8" ) ) ; os . close ( ) ; final int rc = connection . getResponseCode ( ) ; connection . disconnect ( ) ; if ( rc != 204 ) { throw new NotificationException ( "Server returned an unexcepted response code: " + rc + " " + connection . getResponseMessage ( ) ) ; } } catch ( final UnsupportedEncodingException ex ) { LOG . error ( "Could not encode URL" , ex ) ; throw new NotificationException ( "Could not encode URL" , ex ) ; } catch ( final IOException ex ) { LOG . error ( "Communication error" , ex ) ; throw new NotificationException ( "Unable to communicate with " + hub , ex ) ; } } | Sends the HUB url a notification of a change in topic |
32,576 | public void sendUpdateNotification ( final String topic , final SyndFeed feed ) throws NotificationException { for ( final SyndLink link : feed . getLinks ( ) ) { if ( "hub" . equals ( link . getRel ( ) ) ) { sendUpdateNotification ( link . getRel ( ) , topic ) ; return ; } } throw new NotificationException ( "Hub link not found." ) ; } | Sends a notification for a feed located at topic . The feed MUST contain rel = hub . |
32,577 | public void sendUpdateNotification ( final SyndFeed feed ) throws NotificationException { SyndLink hub = null ; SyndLink self = null ; for ( final SyndLink link : feed . getLinks ( ) ) { if ( "hub" . equals ( link . getRel ( ) ) ) { hub = link ; } if ( "self" . equals ( link . getRel ( ) ) ) { self = link ; } if ( hub != null && self != null ) { break ; } } if ( hub == null ) { throw new NotificationException ( "A link rel='hub' was not found in the feed." ) ; } if ( self == null ) { throw new NotificationException ( "A link rel='self' was not found in the feed." ) ; } sendUpdateNotification ( hub . getRel ( ) , self . getHref ( ) ) ; } | Sends a notification for a feed . The feed MUST contain rel = hub and rel = self links . |
32,578 | public void sendUpdateNotificationAsyncronously ( final String hub , final String topic , final AsyncNotificationCallback callback ) { final Runnable r = new Runnable ( ) { public void run ( ) { try { sendUpdateNotification ( hub , topic ) ; callback . onSuccess ( ) ; } catch ( final Throwable t ) { callback . onFailure ( t ) ; } } } ; if ( executor != null ) { executor . execute ( r ) ; } else { new Thread ( r ) . start ( ) ; } } | Sends the HUB url a notification of a change in topic asynchronously |
32,579 | public Categories getCategories ( final AtomRequest areq ) throws AtomException { LOG . debug ( "getCollection" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; return col . getCategories ( true ) . get ( 0 ) ; } | Returns null because we use in - line categories . |
32,580 | public Feed getCollection ( final AtomRequest areq ) throws AtomException { LOG . debug ( "getCollection" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; return col . getFeedDocument ( ) ; } | Get collection specified by pathinfo . |
32,581 | public Entry postEntry ( final AtomRequest areq , final Entry entry ) throws AtomException { LOG . debug ( "postEntry" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; try { return col . addEntry ( entry ) ; } catch ( final Exception fe ) { fe . printStackTrace ( ) ; throw new AtomException ( fe ) ; } } | Create a new entry specified by pathInfo and posted entry . We save the submitted Atom entry verbatim but we do set the id and reset the update time . |
32,582 | public void putEntry ( final AtomRequest areq , final Entry entry ) throws AtomException { LOG . debug ( "putEntry" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final String fileName = pathInfo [ 2 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; try { col . updateEntry ( entry , fileName ) ; } catch ( final Exception fe ) { throw new AtomException ( fe ) ; } } | Update entry specified by pathInfo and posted entry . |
32,583 | public void deleteEntry ( final AtomRequest areq ) throws AtomException { LOG . debug ( "deleteEntry" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final String fileName = pathInfo [ 2 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; try { col . deleteEntry ( fileName ) ; } catch ( final Exception e ) { final String msg = "ERROR in atom.deleteResource" ; LOG . error ( msg , e ) ; throw new AtomException ( msg ) ; } } | Delete entry specified by pathInfo . |
32,584 | public Entry postMedia ( final AtomRequest areq , final Entry entry ) throws AtomException { final String slug = areq . getHeader ( "Slug" ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "postMedia - title: " + entry . getTitle ( ) + " slug:" + slug ) ; } try { final File tempFile = null ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; try { col . addMediaEntry ( entry , slug , areq . getInputStream ( ) ) ; } catch ( final Exception e ) { e . printStackTrace ( ) ; final String msg = "ERROR reading posted file" ; LOG . error ( msg , e ) ; throw new AtomException ( msg , e ) ; } finally { if ( tempFile != null ) { tempFile . delete ( ) ; } } } catch ( final Exception re ) { throw new AtomException ( "ERROR: posting media" ) ; } return entry ; } | Store media data in collection specified by pathInfo create an Atom media - link entry to store metadata for the new media file and return that entry to the caller . |
32,585 | public void putMedia ( final AtomRequest areq ) throws AtomException { LOG . debug ( "putMedia" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; final String fileName = pathInfo [ 3 ] ; final FileBasedCollection col = service . findCollectionByHandle ( handle , collection ) ; try { col . updateMediaEntry ( fileName , areq . getContentType ( ) , areq . getInputStream ( ) ) ; } catch ( final Exception re ) { throw new AtomException ( "ERROR: posting media" ) ; } } | Update the media file part of a media - link entry . |
32,586 | public boolean isAtomServiceURI ( final AtomRequest areq ) { final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; if ( pathInfo . length == 0 ) { return true ; } return false ; } | Return true if specified pathinfo represents URI of service doc . |
32,587 | public boolean isCategoriesURI ( final AtomRequest areq ) { LOG . debug ( "isCategoriesDocumentURI" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; if ( pathInfo . length == 3 && "categories" . equals ( pathInfo [ 2 ] ) ) { return true ; } return false ; } | Return true if specified pathinfo represents URI of category doc . |
32,588 | public boolean isCollectionURI ( final AtomRequest areq ) { LOG . debug ( "isCollectionURI" ) ; final String [ ] pathInfo = StringUtils . split ( areq . getPathInfo ( ) , "/" ) ; if ( pathInfo . length == 2 ) { final String handle = pathInfo [ 0 ] ; final String collection = pathInfo [ 1 ] ; if ( service . findCollectionByHandle ( handle , collection ) != null ) { return true ; } } return false ; } | Return true if specified pathinfo represents URI of a collection . |
32,589 | public String authenticateBASIC ( final HttpServletRequest request ) { LOG . debug ( "authenticateBASIC" ) ; boolean valid = false ; String userID = null ; String password = null ; try { final String authHeader = request . getHeader ( "Authorization" ) ; if ( authHeader != null ) { final StringTokenizer st = new StringTokenizer ( authHeader ) ; if ( st . hasMoreTokens ( ) ) { final String basic = st . nextToken ( ) ; if ( basic . equalsIgnoreCase ( "Basic" ) ) { final String credentials = st . nextToken ( ) ; final String userPass = new String ( Base64 . decodeBase64 ( credentials . getBytes ( ) ) ) ; final int p = userPass . indexOf ( ":" ) ; if ( p != - 1 ) { userID = userPass . substring ( 0 , p ) ; password = userPass . substring ( p + 1 ) ; valid = validateUser ( userID , password ) ; } } } } } catch ( final Exception e ) { LOG . debug ( "An error occured while processing Basic authentication" , e ) ; } if ( valid ) { return userID ; } return null ; } | BASIC authentication . |
32,590 | public boolean isMediaEntry ( ) { boolean mediaEntry = false ; final List < Link > links = getOtherLinks ( ) ; for ( final Link link : links ) { if ( "edit-media" . equals ( link . getRel ( ) ) ) { mediaEntry = true ; break ; } } return mediaEntry ; } | Returns true if entry is a media entry i . e . has rel = edit - media . |
32,591 | protected void enqueueNotification ( final Notification not ) { final Runnable r = new Runnable ( ) { public void run ( ) { not . lastRun = System . currentTimeMillis ( ) ; final SubscriptionSummary summary = postNotification ( not . subscriber , not . mimeType , not . payload ) ; if ( ! summary . isLastPublishSuccessful ( ) ) { not . retryCount ++ ; if ( not . retryCount <= 5 ) { retry ( not ) ; } } not . callback . onSummaryInfo ( summary ) ; } } ; exeuctor . execute ( r ) ; } | Enqueues a notification to run . If the notification fails it will be retried every two minutes until 5 attempts are completed . Notifications to the same callback should be delivered successfully in order . |
32,592 | protected void retry ( final Notification not ) { if ( ! pendings . contains ( not . subscriber . getCallback ( ) ) ) { pendings . add ( not . subscriber . getCallback ( ) ) ; timer . schedule ( new TimerTask ( ) { public void run ( ) { pendings . remove ( not . subscriber . getCallback ( ) ) ; enqueueNotification ( not ) ; } } , TWO_MINUTES ) ; } else { timer . schedule ( new TimerTask ( ) { public void run ( ) { retry ( not ) ; } } , TWO_MINUTES ) ; } } | Schedules a notification to retry in two minutes . |
32,593 | protected List < Element > getItems ( final Element rssRoot ) { final Element eChannel = rssRoot . getChild ( "channel" , getRSSNamespace ( ) ) ; if ( eChannel != null ) { return eChannel . getChildren ( "item" , getRSSNamespace ( ) ) ; } else { return Collections . emptyList ( ) ; } } | It looks for the item elements under the channel elemment . |
32,594 | protected Element getImage ( final Element rssRoot ) { final Element eChannel = rssRoot . getChild ( "channel" , getRSSNamespace ( ) ) ; if ( eChannel != null ) { return eChannel . getChild ( "image" , getRSSNamespace ( ) ) ; } else { return null ; } } | It looks for the image elements under the channel elemment . |
32,595 | protected Element getTextInput ( final Element rssRoot ) { final String elementName = getTextInputLabel ( ) ; final Element eChannel = rssRoot . getChild ( "channel" , getRSSNamespace ( ) ) ; if ( eChannel != null ) { return eChannel . getChild ( elementName , getRSSNamespace ( ) ) ; } else { return null ; } } | It looks for the textinput elements under the channel elemment . |
32,596 | public List < Category > getCategories ( ) { return categories == null ? ( categories = new ArrayList < Category > ( ) ) : categories ; } | The parent categories for this feed |
32,597 | public static Long parseDecimal ( final String s ) { Long parsed = null ; try { if ( s != null ) { parsed = ( long ) Double . parseDouble ( s ) ; } } catch ( final NumberFormatException e ) { } return parsed ; } | Converts a String into a Long by first parsing it as Double and then casting it to Long . |
32,598 | public void add ( final double latitude , final double longitude ) { ensureCapacity ( size + 1 ) ; this . longitude [ size ] = longitude ; this . latitude [ size ] = latitude ; ++ size ; } | Add a position at the end of the list |
32,599 | public void insert ( final int pos , final double latitude , final double longitude ) { ensureCapacity ( size + 1 ) ; System . arraycopy ( this . longitude , pos , this . longitude , pos + 1 , size - pos ) ; System . arraycopy ( this . latitude , pos , this . latitude , pos + 1 , size - pos ) ; this . longitude [ pos ] = longitude ; this . latitude [ pos ] = latitude ; ++ size ; } | Add a position at a given index in the list . The rest of the list is shifted one place to the right |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.