idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,100
private void setReservable ( ChargingStationId chargingStationId , boolean reservable ) { ChargingStation chargingStation = repository . findOne ( chargingStationId . getId ( ) ) ; if ( chargingStation != null ) { chargingStation . setReservable ( reservable ) ; repository . createOrUpdate ( chargingStation ) ; } }
Makes a charging station reservable or not reservable .
2,101
public boolean isAuthorized ( ChargingStationId chargingStationId , UserIdentity userIdentity , Class commandClass ) { boolean isAuthorized = commandAuthorizationRepository . find ( chargingStationId . getId ( ) , userIdentity . getId ( ) , commandClass ) != null ; if ( ! isAuthorized ) { isAuthorized = commandAuthorizationRepository . find ( chargingStationId . getId ( ) , userIdentity . getId ( ) , AllPermissions . class ) != null ; } return isAuthorized ; }
Checks if a user identity has access to a command class for a certain charging station .
2,102
private Boolean messageIdHeaderExists ( List < SoapHeader > headers ) { for ( SoapHeader header : headers ) { if ( header . getName ( ) . getLocalPart ( ) . equalsIgnoreCase ( LOCAL_NAME ) ) { return true ; } } return false ; }
Checks if the MessageID header exists in the list of headers .
2,103
public WampMessage parseMessage ( ChargingStationId chargingStationId , Reader reader ) throws IOException { String rawMessage = this . convertToString ( reader ) ; String trimmedMessage = this . removeBrackets ( rawMessage ) ; int payloadStart = trimmedMessage . indexOf ( "{" ) ; String payload = payloadStart > 0 ? trimmedMessage . substring ( payloadStart ) : null ; String metaData = payloadStart > 0 ? trimmedMessage . substring ( 0 , payloadStart ) : trimmedMessage ; String [ ] metaDataParts = metaData . split ( "," ) ; int messageType = Integer . parseInt ( removeQuotesAndTrim ( metaDataParts [ 0 ] ) ) ; String callId = removeQuotes ( removeQuotesAndTrim ( metaDataParts [ 1 ] ) ) ; WampMessage wampMessage ; switch ( messageType ) { case WampMessage . CALL : MessageProcUri procUri = MessageProcUri . fromValue ( removeQuotesAndTrim ( metaDataParts [ 2 ] ) ) ; wampMessage = new WampMessage ( messageType , callId , procUri , payload ) ; if ( wampMessageHandler != null ) { wampMessageHandler . handleWampCall ( chargingStationId . getId ( ) , rawMessage , callId ) ; } break ; case WampMessage . CALL_RESULT : wampMessage = new WampMessage ( messageType , callId , payload ) ; if ( wampMessageHandler != null ) { wampMessageHandler . handleWampCallResult ( chargingStationId . getId ( ) , rawMessage , callId ) ; } break ; case WampMessage . CALL_ERROR : String errorCode = removeQuotes ( metaDataParts [ 2 ] ) ; String errorDescription = removeQuotes ( metaDataParts [ 3 ] ) ; String errorDetails = removeQuotes ( metaDataParts [ 4 ] ) ; wampMessage = new WampMessage ( messageType , callId , errorCode , errorDescription , errorDetails ) ; if ( wampMessageHandler != null ) { wampMessageHandler . handleWampCallError ( chargingStationId . getId ( ) , rawMessage , callId ) ; } break ; default : if ( wampMessageHandler != null ) { wampMessageHandler . handle ( chargingStationId . getId ( ) , rawMessage ) ; } throw new IllegalArgumentException ( String . format ( "Unknown WAMP messageType: %s" , messageType ) ) ; } return wampMessage ; }
Parses a CALL RESULT or ERROR message and constructs a WampMessage
2,104
private String convertToString ( Reader reader ) throws IOException { StringBuilder stringBuilder = new StringBuilder ( ) ; int numChars ; char [ ] chars = new char [ 50 ] ; do { numChars = reader . read ( chars , 0 , chars . length ) ; if ( numChars > 0 ) { stringBuilder . append ( chars , 0 , numChars ) ; } } while ( numChars != - 1 ) ; return stringBuilder . toString ( ) ; }
Constructs a String by reading the characters from the Reader
2,105
private String removeQuotes ( String toReplace ) { String noQuotes = toReplace . replaceAll ( "\"" , "" ) ; noQuotes = noQuotes . replaceAll ( "'" , "" ) ; return noQuotes ; }
Removes all single and double quotes from the given String .
2,106
public AuthorizeRequest getAuthorizeRequest ( ) { AuthorizeRequest authorizeRequest = new AuthorizeRequest ( ) ; authorizeRequest . setPmsIdentifier ( this . pmsIdentifier ) ; authorizeRequest . setUserIdentifier ( this . userIdentifier ) ; authorizeRequest . setServiceTypeIdentifier ( ServiceType . fromValue ( this . serviceTypeIdentifier . value ( ) ) ) ; authorizeRequest . setLocalServiceIdentifier ( this . localServiceIdentifier ) ; authorizeRequest . setConnectorIdentifier ( this . connectorIdentifier ) ; return authorizeRequest ; }
The type of service this local service provides
2,107
protected void extractBeanValues ( final Object source , final String [ ] nameMapping ) throws SuperCsvReflectionException { Objects . requireNonNull ( nameMapping , "the nameMapping array can't be null as it's used to map from fields to columns" ) ; beanValues . clear ( ) ; for ( int i = 0 ; i < nameMapping . length ; i ++ ) { final String fieldName = nameMapping [ i ] ; if ( fieldName == null ) { beanValues . add ( null ) ; } else { Method getMethod = cache . getGetMethod ( source , fieldName ) ; try { beanValues . add ( getMethod . invoke ( source ) ) ; } catch ( final Exception e ) { throw new SuperCsvReflectionException ( String . format ( "error extracting bean value for field %s" , fieldName ) , e ) ; } } } }
Extracts the bean values using the supplied name mapping array .
2,108
public Reservation findByChargingStationIdEvseIdUserId ( ChargingStationId chargingStationId , EvseId evseid , UserIdentity UserId ) throws NoResultException { EntityManager entityManager = getEntityManager ( ) ; try { return entityManager . createQuery ( "SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Reservation AS t WHERE t.chargingStationId = :chargingStationId AND evseId = :evseId AND userId = :userId" , Reservation . class ) . setParameter ( "chargingStationId" , chargingStationId . getId ( ) ) . setParameter ( "evseId" , evseid ) . setParameter ( "userId" , UserId . getId ( ) ) . getSingleResult ( ) ; } finally { entityManager . close ( ) ; } }
find reservations by chargingstationid evseid and userId
2,109
private int numberFromTransactionIdString ( ChargingStationId chargingStationId , String protocol , String transactionId ) { String transactionIdPartBeforeNumber = String . format ( "%s_%s_" , chargingStationId . getId ( ) , protocol ) ; try { return Integer . parseInt ( transactionId . substring ( transactionIdPartBeforeNumber . length ( ) ) ) ; } catch ( NumberFormatException e ) { throw new NumberFormatException ( String . format ( "Cannot retrieve transaction number from string [%s]" , transactionId ) ) ; } }
Retrieves the number from a transaction id string . ChargingStationId and protocol are passed to make a better guess at the number .
2,110
@ Path ( "/session" ) public Response getSession ( String authorizationIdentifier ) { return Response . ok ( ) . entity ( sourceSessionRepository . findSessionInfoByAuthorizationId ( authorizationIdentifier ) ) . build ( ) ; }
Polling of the sessionInfo
2,111
public Evse createEvse ( Long chargingStationTypeId , Evse evse ) throws ResourceAlreadyExistsException { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; if ( getEvseByIdentifier ( chargingStationType , evse . getIdentifier ( ) ) != null ) { throw new ResourceAlreadyExistsException ( String . format ( "Evse with identifier '%s' already exists." , evse . getIdentifier ( ) ) ) ; } chargingStationType . getEvses ( ) . add ( evse ) ; chargingStationType = chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; return getEvseByIdentifier ( chargingStationType , evse . getIdentifier ( ) ) ; }
Creates a Evse in a charging station type .
2,112
public Set < Evse > getEvses ( Long chargingStationTypeId ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; return chargingStationType . getEvses ( ) ; }
Gets the Evses of a charging station type .
2,113
public ChargingStationType updateChargingStationType ( Long id , ChargingStationType chargingStationType ) { chargingStationType . setId ( id ) ; return chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; }
Update a charging station type .
2,114
public Set < Connector > getConnectors ( Long chargingStationTypeId , Long evseId ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse evse = getEvseById ( chargingStationType , evseId ) ; return evse . getConnectors ( ) ; }
Gets the connectors for a charging station type evse .
2,115
public Connector createConnector ( Long chargingStationTypeId , Long evseId , Connector connector ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse evse = getEvseById ( chargingStationType , evseId ) ; Set < Connector > originalConnectors = ImmutableSet . copyOf ( evse . getConnectors ( ) ) ; evse . getConnectors ( ) . add ( connector ) ; chargingStationType = chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; Set < Connector > newConnectors = getEvseById ( chargingStationType , evseId ) . getConnectors ( ) ; Set < Connector > diffConnectors = Sets . difference ( newConnectors , originalConnectors ) ; if ( diffConnectors . size ( ) == 1 ) { return Iterables . get ( diffConnectors , 0 ) ; } else { return null ; } }
Creates a connector in a charging station type evse .
2,116
public Connector updateConnector ( Long chargingStationTypeId , Long evseId , Connector connector ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse evse = getEvseById ( chargingStationType , evseId ) ; Connector existingConnector = getConnectorById ( evse , connector . getId ( ) , false ) ; if ( existingConnector != null ) { evse . getConnectors ( ) . remove ( existingConnector ) ; } evse . getConnectors ( ) . add ( connector ) ; chargingStationType = chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; evse = getEvseById ( chargingStationType , evseId ) ; return getConnectorById ( evse , connector . getId ( ) ) ; }
Update a connector .
2,117
public Connector getConnector ( Long chargingStationTypeId , Long evseId , Long id ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse evse = getEvseById ( chargingStationType , evseId ) ; return getConnectorById ( evse , id ) ; }
Find a connector based on its id .
2,118
public void deleteConnector ( Long chargingStationTypeId , Long evseId , Long id ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse evse = getEvseById ( chargingStationType , evseId ) ; Connector connector = getConnectorById ( evse , id ) ; evse . getConnectors ( ) . remove ( connector ) ; chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; }
Delete a connector .
2,119
public Evse updateEvse ( Long chargingStationTypeId , Evse evse ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; Evse existingEvse = getEvseById ( chargingStationType , evse . getId ( ) ) ; chargingStationType . getEvses ( ) . remove ( existingEvse ) ; chargingStationType . getEvses ( ) . add ( evse ) ; ChargingStationType updatedChargingStationType = chargingStationTypeRepository . createOrUpdate ( chargingStationType ) ; return getEvseById ( updatedChargingStationType , evse . getId ( ) ) ; }
Update an evse .
2,120
public Evse getEvse ( Long chargingStationTypeId , Long id ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; return getEvseById ( chargingStationType , id ) ; }
Find an evse based on its id .
2,121
public void deleteEvse ( Long chargingStationTypeId , Long id ) { ChargingStationType chargingStationType = chargingStationTypeRepository . findOne ( chargingStationTypeId ) ; chargingStationType . getEvses ( ) . remove ( getEvseById ( chargingStationType , id ) ) ; updateChargingStationType ( chargingStationType . getId ( ) , chargingStationType ) ; }
Delete an evse .
2,122
public Manufacturer updateManufacturer ( Long id , Manufacturer manufacturer ) { manufacturer . setId ( id ) ; return manufacturerRepository . createOrUpdate ( manufacturer ) ; }
Update a manufacturer .
2,123
private Evse getEvseById ( ChargingStationType chargingStationType , Long id ) { for ( Evse evse : chargingStationType . getEvses ( ) ) { if ( id . equals ( evse . getId ( ) ) ) { return evse ; } } throw new EntityNotFoundException ( String . format ( "Unable to find evse with id '%s'" , id ) ) ; }
Gets a Evse by id .
2,124
private Evse getEvseByIdentifier ( ChargingStationType chargingStationType , int identifier ) { for ( Evse evse : chargingStationType . getEvses ( ) ) { if ( identifier == evse . getIdentifier ( ) ) { return evse ; } } return null ; }
Gets a Evse by identifier .
2,125
public Subscription getSubscriptionFromRequest ( HttpServletRequest request ) { String tokenHeader = request . getHeader ( "Authorization" ) ; if ( tokenHeader == null || tokenHeader . indexOf ( "Token " ) != 0 ) { LOG . info ( "Empty authorizationheader, or header does not start with 'Token ': " + tokenHeader ) ; return null ; } String tokenValue = tokenHeader . substring ( tokenHeader . indexOf ( " " ) ) . trim ( ) ; LOG . info ( "Token value: " + tokenValue ) ; if ( tokenValue != null ) { return subscriptionService . findSubscriptionByAuthorizationToken ( tokenValue ) ; } return null ; }
Finds Subscription object based on request .
2,126
public Endpoint getEndpoint ( ModuleIdentifier identifier ) { for ( Endpoint endpoint : getEndpoints ( ) ) { if ( endpoint . getIdentifier ( ) . equals ( identifier ) ) { return endpoint ; } } return null ; }
returns the Endpoint with the identifier passed as argument if not found returns null
2,127
public void startTransaction ( ChargingStationId chargingStationId , EvseId evseId , IdentifyingToken idTag , FutureEventCallback futureEventCallback , AddOnIdentity addOnIdentity ) { ChargingStation chargingStation = this . checkChargingStationExistsAndIsRegisteredAndConfigured ( chargingStationId ) ; if ( evseId . getNumberedId ( ) > chargingStation . getNumberOfEvses ( ) ) { throw new IllegalStateException ( "Cannot start transaction on a unknown evse." ) ; } authorize ( chargingStationId , idTag . getToken ( ) , futureEventCallback , addOnIdentity ) ; }
Generates a transaction identifier and starts a transaction by dispatching a StartTransactionCommand .
2,128
public void changeConfiguration ( ChargingStationId chargingStationId , ConfigurationItem configurationItem , CorrelationToken correlationToken , AddOnIdentity addOnIdentity ) { IdentityContext identityContext = new IdentityContext ( addOnIdentity , new NullUserIdentity ( ) ) ; commandGateway . send ( new ChangeConfigurationItemCommand ( chargingStationId , configurationItem , identityContext ) , correlationToken ) ; }
Change the configuration in the charging station . It has already happened on the physical charging station but the Domain has not been updated yet .
2,129
public Transaction createTransaction ( EvseId evseId ) { Transaction transaction = new Transaction ( ) ; transaction . setEvseId ( evseId ) ; transactionRepository . insert ( transaction ) ; return transaction ; }
Creates a transaction identifier . The EVSE identifier is stored for later usage .
2,130
private ChargingStation checkChargingStationExistsAndIsRegisteredAndConfigured ( ChargingStationId chargingStationId ) { ChargingStation chargingStation = chargingStationRepository . findOne ( chargingStationId . getId ( ) ) ; if ( chargingStation == null ) { throw new IllegalStateException ( "Unknown charging station." ) ; } if ( ! chargingStation . isRegisteredAndConfigured ( ) ) { throw new IllegalStateException ( "Charging station has not been registered/configured." ) ; } return chargingStation ; }
Checks if the charging station exists in the repository and if it has been registered and configured . If not a IllegalStateException will be thrown .
2,131
private Version findHighestMutualVersion ( Versions offeredVersions ) { Version highestSupportedVersion = null ; for ( String supportedVersion : Arrays . asList ( AppConfig . SUPPORTED_VERSIONS ) ) { Version match = offeredVersions . find ( supportedVersion ) ; if ( match != null ) { highestSupportedVersion = match ; } } return highestSupportedVersion ; }
returns the highest mutual version between the offeredVersions of the partner and the supported versions on our side
2,132
private Credentials postCredentials ( Subscription subscription ) { String credentialsUrl = subscription . getEndpoint ( ModuleIdentifier . CREDENTIALS ) . getUrl ( ) ; LOG . info ( "Posting credentials at " + credentialsUrl + " with authorizationToken: " + subscription . getPartnerAuthorizationToken ( ) ) ; Credentials credentials = new Credentials ( ) ; credentials . url = HOST_URL + "/cpo/versions" ; credentials . token = subscription . getAuthorizationToken ( ) ; credentials . party_id = PARTY_ID ; credentials . country_code = COUNTRY_CODE ; BusinessDetails businessDetails = new BusinessDetails ( ) ; businessDetails . name = CLIENT_NAME ; credentials . business_details = businessDetails ; String json = toJson ( credentials ) ; LOG . info ( "Credentials POST: " + json ) ; HttpPost post = new HttpPost ( credentialsUrl ) ; HttpEntity entity = null ; try { entity = new ByteArrayEntity ( json . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( "UnsupportedEncodingException while setting body for posting credentials" , e ) ; } post . setEntity ( entity ) ; CredentialsResponse credentialsResponse = ( CredentialsResponse ) doRequest ( post , subscription . getPartnerAuthorizationToken ( ) , CredentialsResponse . class ) ; LOG . debug ( "credentialsResponse data: " + credentialsResponse ) ; return credentialsResponse . data ; }
Posts the credentials of the user with the EMSP credentials endpoint
2,133
public void register ( Subscription subscription ) { Endpoint versionsEndpoint = subscription . getEndpoint ( ModuleIdentifier . VERSIONS ) ; if ( versionsEndpoint == null ) { return ; } LOG . info ( "Registering, get versions from endpoint " + versionsEndpoint . getUrl ( ) ) ; Version version = findHighestMutualVersion ( getVersions ( versionsEndpoint . getUrl ( ) , subscription . getPartnerAuthorizationToken ( ) ) ) ; LOG . info ( "Registering, get versiondetails at " + version . url ) ; VersionDetails versionDetails = getVersionDetails ( version . url , subscription . getPartnerAuthorizationToken ( ) ) ; subscription . setOcpiVersion ( version . version ) ; for ( io . motown . ocpi . dto . Endpoint endpoint : versionDetails . endpoints ) { subscription . addToEndpoints ( new Endpoint ( endpoint . identifier , endpoint . url . toString ( ) ) ) ; } if ( subscription . getAuthorizationToken ( ) == null ) { subscription . generateNewAuthorizationToken ( ) ; } ocpiRepository . insertOrUpdate ( subscription ) ; Credentials credentials = postCredentials ( subscription ) ; if ( credentials . token != null ) { LOG . debug ( "Updating partnerToken with: " + credentials . token ) ; subscription . setPartnerAuthorizationToken ( credentials . token ) ; LOG . info ( "REMOVING VERIONS-ENDPOINT" ) ; subscription . getEndpoints ( ) . remove ( versionsEndpoint ) ; ocpiRepository . insertOrUpdate ( subscription ) ; } }
registers with the EMSP with passed as argument the endpoints of this EMSP are stored in the database as well as the definitive token
2,134
private String getAuthTokenFromRequest ( HttpServletRequest httpRequest ) { String authToken = httpRequest . getHeader ( AUTH_TOKEN_HEADER_KEY ) ; if ( authToken == null ) { authToken = httpRequest . getParameter ( AUTH_TOKEN_PARAMETER_KEY ) ; } return authToken ; }
Gets the authorization token from the request . First tries the header if that s empty the parameter is checked .
2,135
private static int getPreviousPageOffset ( final int offset , final int limit ) { return hasFullPreviousPage ( offset , limit ) ? getPreviousFullPageOffset ( offset , limit ) : getFirstPageOffset ( ) ; }
Gets the previous page offset .
2,136
private static long getNextPageOffset ( final int offset , final int limit , final long total ) { return hasFullNextPage ( offset , limit , total ) ? getNextFullPageOffset ( offset , limit ) : getLastPageOffset ( total , limit ) ; }
Gets the next page offset .
2,137
public ChargePointService createChargingStationService ( String chargingStationAddress ) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean ( ) ; factory . setServiceClass ( ChargePointService . class ) ; factory . setAddress ( chargingStationAddress ) ; SoapBindingConfiguration conf = new SoapBindingConfiguration ( ) ; conf . setVersion ( Soap12 . getInstance ( ) ) ; factory . setBindingConfig ( conf ) ; factory . getFeatures ( ) . add ( new WSAddressingFeature ( ) ) ; ChargePointService chargePointService = ( ChargePointService ) factory . create ( ) ; ( ( BindingProvider ) chargePointService ) . getRequestContext ( ) . put ( "use.async.http.conduit" , Boolean . TRUE ) ; return chargePointService ; }
Creates a charging station web service proxy .
2,138
public void synchronizeTokens ( Endpoint tokenEndPoint ) { Integer subscriptionId = tokenEndPoint . getSubscriptionId ( ) ; String partnerAuthorizationToken = tokenEndPoint . getSubscription ( ) . getPartnerAuthorizationToken ( ) ; String lastSyncDate = getLastSyncDate ( subscriptionId ) ; int totalCount = 1 ; int numberRetrieved = 0 ; Date startOfSync = new Date ( ) ; while ( totalCount > numberRetrieved ) { String tokenUrl = tokenEndPoint . getUrl ( ) ; tokenUrl += "?offset=" + numberRetrieved + "&limit=" + PAGE_SIZE ; if ( lastSyncDate != null ) { tokenUrl += "&date_from=" + lastSyncDate ; } LOG . info ( "Get tokens at endpoint: " + tokenUrl ) ; TokenResponse tokenResponse = ( TokenResponse ) doRequest ( new HttpGet ( tokenUrl ) , partnerAuthorizationToken , TokenResponse . class ) ; if ( tokenResponse . totalCount == null ) { break ; } totalCount = tokenResponse . totalCount ; numberRetrieved += tokenResponse . data . size ( ) ; LOG . info ( "Inserting " + tokenResponse . data . size ( ) + " tokens" ) ; for ( io . motown . ocpi . dto . Token token : tokenResponse . data ) { insertOrUpdateToken ( token , subscriptionId ) ; } } updateLastSynchronizationDate ( startOfSync , subscriptionId ) ; LOG . info ( "Number of tokens retrieved: " + numberRetrieved ) ; }
Retrieves tokens from the enpoint passed as argument and stores these in the database
2,139
private String getLastSyncDate ( Integer subscriptionId ) { String lastSyncDate = null ; TokenSyncDate tokenSyncDate = ocpiRepository . getTokenSyncDate ( subscriptionId ) ; if ( tokenSyncDate != null ) { lastSyncDate = AppConfig . DATE_FORMAT . format ( tokenSyncDate . getSyncDate ( ) ) ; } return lastSyncDate ; }
Returns the formatted datetime the tokens where last synchronized if it exists otherwise null .
2,140
private void updateLastSynchronizationDate ( Date syncDate , Integer subscriptionId ) { TokenSyncDate tokenSyncDate = ocpiRepository . getTokenSyncDate ( subscriptionId ) ; if ( tokenSyncDate == null ) { tokenSyncDate = new TokenSyncDate ( ) ; tokenSyncDate . setSubscriptionId ( subscriptionId ) ; } tokenSyncDate . setSyncDate ( syncDate ) ; ocpiRepository . insertOrUpdate ( tokenSyncDate ) ; }
Updates the last sync date for the passed subscription .
2,141
private void insertOrUpdateToken ( io . motown . ocpi . dto . Token tokenUpdate , Integer subscriptionId ) { Token token = ocpiRepository . findTokenByUidAndIssuingCompany ( tokenUpdate . uid , tokenUpdate . issuer ) ; if ( token == null ) { token = new Token ( ) ; token . setUid ( tokenUpdate . uid ) ; token . setSubscriptionId ( subscriptionId ) ; token . setDateCreated ( new Date ( ) ) ; } token . setTokenType ( tokenUpdate . type ) ; token . setAuthId ( tokenUpdate . auth_id ) ; token . setVisualNumber ( tokenUpdate . visual_number ) ; token . setIssuingCompany ( tokenUpdate . issuer ) ; token . setValid ( tokenUpdate . valid ) ; token . setWhitelist ( tokenUpdate . whitelist ) ; token . setLanguageCode ( tokenUpdate . languageCode ) ; try { token . setLastUpdated ( AppConfig . DATE_FORMAT . parse ( tokenUpdate . last_updated ) ) ; } catch ( ParseException e ) { throw new RuntimeException ( e ) ; } ocpiRepository . insertOrUpdate ( token ) ; }
Inserts a token or updates it if an existing token is found with the same uid and issuing - company
2,142
public String getChargingStationAddress ( MessageContext messageContext ) { if ( ! ( messageContext instanceof WrappedMessageContext ) ) { LOG . warn ( "Unable to get message context, or message context is not the right type." ) ; return "" ; } Message message = ( ( WrappedMessageContext ) messageContext ) . getWrappedMessage ( ) ; List < Header > headers = CastUtils . cast ( ( List < ? > ) message . get ( Header . HEADER_LIST ) ) ; for ( Header h : headers ) { Element n = ( Element ) h . getObject ( ) ; if ( "From" . equals ( n . getLocalName ( ) ) ) { return n . getTextContent ( ) ; } } LOG . warn ( "No 'From' header found in request. Not able to determine charging station address." ) ; return "" ; }
Gets the charging station address from the SOAP From header .
2,143
@ Path ( "authenticate" ) @ Produces ( MediaType . APPLICATION_JSON ) public TokenDto authenticate ( @ FormParam ( "username" ) String username , @ FormParam ( "password" ) String password ) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken ( username , password ) ; Authentication authentication = this . authManager . authenticate ( authenticationToken ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( authentication ) ; return new TokenDto ( TokenUtils . createToken ( ( UserDetails ) authentication . getPrincipal ( ) ) ) ; }
Authenticates a user and creates an authentication token .
2,144
public static String getUserNameFromToken ( String authToken ) { if ( null == authToken ) { return null ; } return authToken . split ( TOKEN_SEPARATOR ) [ 0 ] ; }
Extracts the user name from token .
2,145
public static boolean validateToken ( String authToken , UserDetails userDetails ) { String [ ] parts = authToken . split ( TOKEN_SEPARATOR ) ; long expires = Long . parseLong ( parts [ 1 ] ) ; String signature = parts [ 2 ] ; return expires >= System . currentTimeMillis ( ) && signature . equals ( TokenUtils . computeSignature ( userDetails , expires ) ) ; }
Validates the token signature against the user details and the current system time .
2,146
public VasSubscriberService createVasSubscriberService ( String deliveryAddress ) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean ( ) ; factory . setServiceClass ( VasSubscriberService . class ) ; factory . setAddress ( deliveryAddress ) ; SoapBindingConfiguration conf = new SoapBindingConfiguration ( ) ; conf . setVersion ( Soap12 . getInstance ( ) ) ; factory . setBindingConfig ( conf ) ; factory . getFeatures ( ) . add ( new WSAddressingFeature ( ) ) ; VasSubscriberService vasSubscriberService = ( VasSubscriberService ) factory . create ( ) ; ( ( BindingProvider ) vasSubscriberService ) . getRequestContext ( ) . put ( "use.async.http.conduit" , Boolean . TRUE ) ; return vasSubscriberService ; }
Creates a vas subscriber web service proxy based on the delivery address .
2,147
public Version find ( String versionToFind ) { for ( Version version : list ) { if ( version . version . equals ( versionToFind ) ) { return version ; } } return null ; }
find returns the version object with the version passed as argument
2,148
public ChargeMode getChargeModeFromEvses ( Set < Evse > evses ) { ChargeMode chargeMode = ChargeMode . UNSPECIFIED ; for ( Evse evse : evses ) { if ( ! evse . getConnectors ( ) . isEmpty ( ) ) { chargeMode = ChargeMode . fromChargingProtocol ( evse . getConnectors ( ) . get ( 0 ) . getChargingProtocol ( ) ) ; break ; } } return chargeMode ; }
Determines the charge mode based on the first connector because VAS does not support multiple protocols for a single charging station . If no charge mode can be determined UNSPECIFIED will be returned .
2,149
public boolean check ( final int nLevel ) { if ( nLevel == FATAL || nLevel == ERROR ) return m_aLogger . isErrorEnabled ( ) ; if ( nLevel == WARN ) return m_aLogger . isWarnEnabled ( ) ; if ( nLevel == INFO ) return m_aLogger . isInfoEnabled ( ) ; if ( nLevel == DEBUG ) return m_aLogger . isDebugEnabled ( ) ; return m_aLogger . isTraceEnabled ( ) ; }
Check if a logger is enabled to log at the specified level
2,150
public Sheet createNewSheet ( final String sName ) { m_aLastSheet = sName == null ? m_aWB . createSheet ( ) : m_aWB . createSheet ( WorkbookUtil . createSafeSheetName ( sName ) ) ; m_nLastSheetRowIndex = 0 ; m_aLastRow = null ; m_nLastRowCellIndex = 0 ; m_aLastCell = null ; m_nMaxCellIndex = 0 ; return m_aLastSheet ; }
Create a new sheet with an optional name
2,151
public void addCellStyle ( final ExcelStyle aExcelStyle ) { ValueEnforcer . notNull ( aExcelStyle , "ExcelStyle" ) ; if ( m_aLastCell == null ) throw new IllegalStateException ( "No cell present for current row!" ) ; CellStyle aCellStyle = m_aStyleCache . getCellStyle ( aExcelStyle ) ; if ( aCellStyle == null ) { aCellStyle = m_aWB . createCellStyle ( ) ; aExcelStyle . fillCellStyle ( m_aWB , aCellStyle , m_aCreationHelper ) ; m_aStyleCache . addCellStyle ( aExcelStyle , aCellStyle ) ; m_nCreatedCellStyles ++ ; } m_aLastCell . setCellStyle ( aCellStyle ) ; }
Set the cell style of the last added cell
2,152
public void autoSizeAllColumns ( ) { for ( short nCol = 0 ; nCol < m_nMaxCellIndex ; ++ nCol ) try { m_aLastSheet . autoSizeColumn ( nCol ) ; } catch ( final IllegalArgumentException ex ) { LOGGER . warn ( "Failed to resize column " + nCol + ": column too wide!" ) ; } }
Auto size all columns to be matching width in the current sheet
2,153
public ESuccess writeTo ( final File aFile ) { return writeTo ( FileHelper . getOutputStream ( aFile ) ) ; }
Write the current workbook to a file
2,154
public ESuccess writeTo ( final IWritableResource aRes ) { return writeTo ( aRes . getOutputStream ( EAppend . TRUNCATE ) ) ; }
Write the current workbook to a writable resource .
2,155
public ESuccess writeTo ( final OutputStream aOS ) { try { ValueEnforcer . notNull ( aOS , "OutputStream" ) ; if ( m_nCreatedCellStyles > 0 && LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Writing Excel workbook with " + m_nCreatedCellStyles + " different cell styles" ) ; m_aWB . write ( aOS ) ; return ESuccess . SUCCESS ; } catch ( final IOException ex ) { if ( ! StreamHelper . isKnownEOFException ( ex ) ) LOGGER . error ( "Failed to write Excel workbook to output stream " + aOS , ex ) ; return ESuccess . FAILURE ; } finally { StreamHelper . close ( aOS ) ; } }
Write the current workbook to an output stream .
2,156
public byte [ ] getAsByteArray ( ) { try ( final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ( ) ) { if ( writeTo ( aBAOS ) . isFailure ( ) ) return null ; return aBAOS . getBufferOrCopy ( ) ; } }
Helper method to get the whole workbook as a single byte array .
2,157
public CloseableHttpClient getHttpClient ( ) { try { URI crxUri = new URI ( props . getPackageManagerUrl ( ) ) ; final AuthScope authScope = new AuthScope ( crxUri . getHost ( ) , crxUri . getPort ( ) ) ; final Credentials credentials = new UsernamePasswordCredentials ( props . getUserId ( ) , props . getPassword ( ) ) ; final CredentialsProvider credsProvider = new BasicCredentialsProvider ( ) ; credsProvider . setCredentials ( authScope , credentials ) ; HttpClientBuilder httpClientBuilder = HttpClients . custom ( ) . setDefaultCredentialsProvider ( credsProvider ) . addInterceptorFirst ( new HttpRequestInterceptor ( ) { public void process ( HttpRequest request , HttpContext context ) throws HttpException , IOException { AuthState authState = ( AuthState ) context . getAttribute ( HttpClientContext . TARGET_AUTH_STATE ) ; authState . update ( new BasicScheme ( ) , credentials ) ; } } ) . setKeepAliveStrategy ( new ConnectionKeepAliveStrategy ( ) { public long getKeepAliveDuration ( HttpResponse response , HttpContext context ) { return 1 ; } } ) ; httpClientBuilder . setDefaultRequestConfig ( HttpClientUtil . buildRequestConfig ( props ) ) ; if ( props . isRelaxedSSLCheck ( ) ) { SSLContext sslContext = new SSLContextBuilder ( ) . loadTrustMaterial ( null , new TrustSelfSignedStrategy ( ) ) . build ( ) ; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory ( sslContext , new NoopHostnameVerifier ( ) ) ; httpClientBuilder . setSSLSocketFactory ( sslsf ) ; } Proxy proxy = getProxyForUrl ( props . getPackageManagerUrl ( ) ) ; if ( proxy != null ) { httpClientBuilder . setProxy ( new HttpHost ( proxy . getHost ( ) , proxy . getPort ( ) , proxy . getProtocol ( ) ) ) ; if ( proxy . useAuthentication ( ) ) { AuthScope proxyAuthScope = new AuthScope ( proxy . getHost ( ) , proxy . getPort ( ) ) ; Credentials proxyCredentials = new UsernamePasswordCredentials ( proxy . getUsername ( ) , proxy . getPassword ( ) ) ; credsProvider . setCredentials ( proxyAuthScope , proxyCredentials ) ; } } return httpClientBuilder . build ( ) ; } catch ( URISyntaxException ex ) { throw new PackageManagerException ( "Invalid url: " + props . getPackageManagerUrl ( ) , ex ) ; } catch ( KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex ) { throw new PackageManagerException ( "Could not set relaxedSSLCheck" , ex ) ; } }
Set up http client with credentials
2,158
private Proxy getProxyForUrl ( String requestUrl ) { List < Proxy > proxies = props . getProxies ( ) ; if ( proxies == null || proxies . isEmpty ( ) ) { return null ; } final URI uri = URI . create ( requestUrl ) ; for ( Proxy proxy : proxies ) { if ( ! proxy . isNonProxyHost ( uri . getHost ( ) ) ) { return proxy ; } } return null ; }
Get proxy for given URL
2,159
private < T > T executeHttpCallWithRetry ( HttpCall < T > call , int runCount ) { try { return call . execute ( ) ; } catch ( PackageManagerHttpActionException ex ) { if ( runCount < props . getRetryCount ( ) ) { log . info ( "ERROR: " + ex . getMessage ( ) ) ; log . debug ( "HTTP call failed." , ex ) ; log . info ( "---------------" ) ; StringBuilder msg = new StringBuilder ( ) ; msg . append ( "HTTP call failed, try again (" + ( runCount + 1 ) + "/" + props . getRetryCount ( ) + ")" ) ; if ( props . getRetryDelaySec ( ) > 0 ) { msg . append ( " after " + props . getRetryDelaySec ( ) + " second(s)" ) ; } msg . append ( "..." ) ; log . info ( msg ) ; if ( props . getRetryDelaySec ( ) > 0 ) { try { Thread . sleep ( props . getRetryDelaySec ( ) * DateUtils . MILLIS_PER_SECOND ) ; } catch ( InterruptedException ex1 ) { } } return executeHttpCallWithRetry ( call , runCount + 1 ) ; } else { throw ex ; } } }
Execute HTTP call with automatic retry as configured for the MOJO .
2,160
public JSONObject executePackageManagerMethodJson ( CloseableHttpClient httpClient , HttpRequestBase method ) { PackageManagerJsonCall call = new PackageManagerJsonCall ( httpClient , method , log ) ; return executeHttpCallWithRetry ( call , 0 ) ; }
Execute CRX HTTP Package manager method and parse JSON response .
2,161
public Document executePackageManagerMethodXml ( CloseableHttpClient httpClient , HttpRequestBase method ) { PackageManagerXmlCall call = new PackageManagerXmlCall ( httpClient , method , log ) ; return executeHttpCallWithRetry ( call , 0 ) ; }
Execute CRX HTTP Package manager method and parse XML response .
2,162
public String executePackageManagerMethodHtml ( CloseableHttpClient httpClient , HttpRequestBase method ) { PackageManagerHtmlCall call = new PackageManagerHtmlCall ( httpClient , method , log ) ; String message = executeHttpCallWithRetry ( call , 0 ) ; return message ; }
Execute CRX HTTP Package manager method and get HTML response .
2,163
public void executePackageManagerMethodHtmlOutputResponse ( CloseableHttpClient httpClient , HttpRequestBase method ) { PackageManagerHtmlMessageCall call = new PackageManagerHtmlMessageCall ( httpClient , method , log ) ; executeHttpCallWithRetry ( call , 0 ) ; }
Execute CRX HTTP Package manager method and output HTML response .
2,164
public void waitForBundlesActivation ( CloseableHttpClient httpClient ) { if ( StringUtils . isBlank ( props . getBundleStatusUrl ( ) ) ) { log . debug ( "Skipping check for bundle activation state because no bundleStatusURL is defined." ) ; return ; } final int WAIT_INTERVAL_SEC = 3 ; final long CHECK_RETRY_COUNT = props . getBundleStatusWaitLimitSec ( ) / WAIT_INTERVAL_SEC ; log . info ( "Check bundle activation status..." ) ; for ( int i = 1 ; i <= CHECK_RETRY_COUNT ; i ++ ) { BundleStatusCall call = new BundleStatusCall ( httpClient , props . getBundleStatusUrl ( ) , log ) ; BundleStatus bundleStatus = executeHttpCallWithRetry ( call , 0 ) ; boolean instanceReady = true ; if ( ! bundleStatus . isAllBundlesRunning ( ) ) { log . info ( "Bundles starting/stopping: " + bundleStatus . getStatusLineCompact ( ) + " - wait " + WAIT_INTERVAL_SEC + " sec " + "(max. " + props . getBundleStatusWaitLimitSec ( ) + " sec) ..." ) ; sleep ( WAIT_INTERVAL_SEC ) ; instanceReady = false ; } if ( instanceReady ) { for ( Pattern blacklistBundleNamePattern : props . getBundleStatusBlacklistBundleNames ( ) ) { String bundleSymbolicName = bundleStatus . getMatchingBundle ( blacklistBundleNamePattern ) ; if ( bundleSymbolicName != null ) { log . info ( "Bundle '" + bundleSymbolicName + "' is still deployed " + " - wait " + WAIT_INTERVAL_SEC + " sec " + "(max. " + props . getBundleStatusWaitLimitSec ( ) + " sec) ..." ) ; sleep ( WAIT_INTERVAL_SEC ) ; instanceReady = false ; break ; } } } if ( instanceReady ) { break ; } } }
Wait for bundles to become active .
2,165
protected int getRowFirstNonWhite ( StyledDocument doc , int offset ) throws BadLocationException { Element lineElement = doc . getParagraphElement ( offset ) ; int start = lineElement . getStartOffset ( ) ; while ( start + 1 < lineElement . getEndOffset ( ) ) { try { if ( doc . getText ( start , 1 ) . charAt ( 0 ) != ' ' ) { break ; } } catch ( BadLocationException ex ) { throw ( BadLocationException ) new BadLocationException ( "calling getText(" + start + ", " + ( start + 1 ) + ") on doc of length: " + doc . getLength ( ) , start ) . initCause ( ex ) ; } start ++ ; } return start ; }
iterates through the text to find first nonwhite
2,166
public void execute ( ) throws MojoExecutionException , MojoFailureException { if ( isSkip ( ) ) { return ; } PackageDownloader downloader = new PackageDownloader ( getPackageManagerProperties ( ) , getLoggerWrapper ( ) ) ; File outputFileObject = downloader . downloadFile ( getPackageFile ( ) , this . outputFile ) ; if ( this . unpack ) { unpackFile ( outputFileObject ) ; } }
Downloads the files
2,167
private void unpackFile ( File file ) throws MojoExecutionException { ContentUnpackerProperties props = new ContentUnpackerProperties ( ) ; props . setExcludeFiles ( this . excludeFiles ) ; props . setExcludeNodes ( this . excludeNodes ) ; props . setExcludeProperties ( this . excludeProperties ) ; props . setExcludeMixins ( this . excludeMixins ) ; ContentUnpacker unpacker = new ContentUnpacker ( props ) ; if ( this . unpackDirectory == null ) { throw new MojoExecutionException ( "No unpack directory specified." ) ; } if ( ! this . unpackDirectory . exists ( ) ) { this . unpackDirectory . mkdirs ( ) ; } if ( this . unpackDeleteDirectories != null ) { for ( String directory : unpackDeleteDirectories ) { File directoryFile = FileUtils . getFile ( this . unpackDirectory , directory ) ; if ( directoryFile . exists ( ) ) { if ( ! deleteDirectoryWithRetries ( directoryFile , 0 ) ) { throw new MojoExecutionException ( "Unable to delete existing content from " + directoryFile . getAbsolutePath ( ) ) ; } } } } unpacker . unpack ( file , this . unpackDirectory ) ; getLog ( ) . info ( "Package unpacked to " + this . unpackDirectory . getAbsolutePath ( ) ) ; }
Unpack content package
2,168
protected void substituteText ( JTextComponent component , String toAdd ) { String text = completionText ; if ( toAdd != null ) { text += toAdd ; } try { StyledDocument doc = ( StyledDocument ) component . getDocument ( ) ; doc . remove ( dotOffset , caretOffset - dotOffset ) ; doc . insertString ( dotOffset , text , null ) ; Completion . get ( ) . hideAll ( ) ; } catch ( BadLocationException ex ) { Exceptions . printStackTrace ( ex ) ; } }
Substitutes the text inside the component .
2,169
public void validate ( ) { if ( StringUtils . isEmpty ( name ) || StringUtils . isEmpty ( group ) ) { throw new IllegalArgumentException ( "Package name or group not set." ) ; } if ( filters . isEmpty ( ) ) { throw new IllegalArgumentException ( "No package filter defined / no package root path set." ) ; } if ( created == null ) { throw new IllegalArgumentException ( "Package creation date not set." ) ; } }
Validates that the mandatory properties are set .
2,170
public void addContent ( String path , ContentElement content ) throws IOException { String fullPath = buildJcrPathForZip ( path ) + "/" + DOT_CONTENT_XML ; Document doc = xmlContentBuilder . buildContent ( content ) ; writeXmlDocument ( fullPath , doc ) ; }
Add some JCR content structure directly to the package .
2,171
private void buildPackageMetadata ( ) throws IOException { metadata . validate ( ) ; buildTemplatedMetadataFile ( META_DIR + "/" + CONFIG_XML ) ; buildPropertiesFile ( META_DIR + "/" + PROPERTIES_XML ) ; buildTemplatedMetadataFile ( META_DIR + "/" + SETTINGS_XML ) ; buildTemplatedMetadataFile ( META_DIR + "/" + PACKAGE_DEFINITION_XML ) ; writeXmlDocument ( META_DIR + "/" + FILTER_XML , xmlContentBuilder . buildFilter ( metadata . getFilters ( ) ) ) ; byte [ ] thumbnailImage = metadata . getThumbnailImage ( ) ; if ( thumbnailImage != null ) { zip . putNextEntry ( new ZipEntry ( META_DIR + "/definition/thumbnail.png" ) ) ; try { zip . write ( thumbnailImage ) ; } finally { zip . closeEntry ( ) ; } } }
Build all package metadata files based on templates .
2,172
private void buildTemplatedMetadataFile ( String path ) throws IOException { try ( InputStream is = getClass ( ) . getResourceAsStream ( "/content-package-template/" + path ) ) { String xmlContent = IOUtils . toString ( is ) ; for ( Map . Entry < String , Object > entry : metadata . getVars ( ) . entrySet ( ) ) { xmlContent = StringUtils . replace ( xmlContent , "{{" + entry . getKey ( ) + "}}" , StringEscapeUtils . escapeXml10 ( entry . getValue ( ) . toString ( ) ) ) ; } zip . putNextEntry ( new ZipEntry ( path ) ) ; try { zip . write ( xmlContent . getBytes ( Charsets . UTF_8 ) ) ; } finally { zip . closeEntry ( ) ; } } }
Read template file from classpath replace variables and store it in the zip stream .
2,173
private void buildPropertiesFile ( String path ) throws IOException { Properties properties = new Properties ( ) ; properties . put ( MetaInf . PACKAGE_FORMAT_VERSION , Integer . toString ( MetaInf . FORMAT_VERSION_2 ) ) ; properties . put ( PackageProperties . NAME_REQUIRES_ROOT , Boolean . toString ( false ) ) ; for ( Map . Entry < String , Object > entry : metadata . getVars ( ) . entrySet ( ) ) { String value = Objects . toString ( entry . getValue ( ) ) ; if ( StringUtils . isNotEmpty ( value ) ) { properties . put ( entry . getKey ( ) , value ) ; } } zip . putNextEntry ( new ZipEntry ( path ) ) ; try { properties . storeToXML ( zip , null ) ; } finally { zip . closeEntry ( ) ; } }
Build java Properties XML file .
2,174
private void writeXmlDocument ( String path , Document doc ) throws IOException { zip . putNextEntry ( new ZipEntry ( path ) ) ; try { DOMSource source = new DOMSource ( doc ) ; StreamResult result = new StreamResult ( zip ) ; transformer . transform ( source , result ) ; } catch ( TransformerException ex ) { throw new IOException ( "Failed to generate XML: " + ex . getMessage ( ) , ex ) ; } finally { zip . closeEntry ( ) ; } }
Writes an XML document as binary file entry to the ZIP output stream .
2,175
private void writeBinaryFile ( String path , InputStream is ) throws IOException { zip . putNextEntry ( new ZipEntry ( path ) ) ; try { IOUtils . copy ( is , zip ) ; } finally { zip . closeEntry ( ) ; } }
Writes an binary file entry to the ZIP output stream .
2,176
private Set < String > resolveClass ( String variableName , String text , Document document ) { Set < String > items = new LinkedHashSet < > ( ) ; FileObject fo = getFileObject ( document ) ; ClassPath sourcePath = ClassPath . getClassPath ( fo , ClassPath . SOURCE ) ; ClassPath compilePath = ClassPath . getClassPath ( fo , ClassPath . COMPILE ) ; ClassPath bootPath = ClassPath . getClassPath ( fo , ClassPath . BOOT ) ; if ( sourcePath == null ) { return items ; } ClassPath cp = ClassPathSupport . createProxyClassPath ( sourcePath , compilePath , bootPath ) ; MemberLookupResolver resolver = new MemberLookupResolver ( text , cp ) ; Set < MemberLookupResult > results = resolver . performMemberLookup ( StringUtils . defaultString ( StringUtils . substringBeforeLast ( variableName , "." ) , variableName ) ) ; for ( MemberLookupResult result : results ) { Matcher m = GETTER_PATTERN . matcher ( result . getMethodName ( ) ) ; if ( m . matches ( ) && m . groupCount ( ) >= 2 ) { items . add ( result . getVariableName ( ) + "." + WordUtils . uncapitalize ( m . group ( 2 ) ) ) ; } else { items . add ( result . getVariableName ( ) + "." + WordUtils . uncapitalize ( result . getMethodName ( ) ) ) ; } } return items ; }
This method tries to find the class which is defined for the given filter and returns a set with all methods and fields of the class
2,177
public Set < MemberLookupResult > performMemberLookup ( String variable ) { if ( variable . contains ( "." ) ) { return performNestedLookup ( variable ) ; } Set < MemberLookupResult > ret = new LinkedHashSet < > ( ) ; ParsedStatement statement = getParsedStatement ( variable ) ; if ( statement == null ) { return ret ; } if ( StringUtils . equals ( statement . getCommand ( ) , DataSlyCommands . DATA_SLY_USE . getCommand ( ) ) ) { ret . addAll ( getResultsForClass ( statement . getValue ( ) , variable ) ) ; } else { Set < MemberLookupResult > subResults = performMemberLookup ( StringUtils . substringBefore ( statement . getValue ( ) , "." ) ) ; for ( MemberLookupResult result : subResults ) { if ( result . matches ( StringUtils . substringAfter ( statement . getValue ( ) , "." ) ) ) { ret . addAll ( getResultsForClass ( result . getReturnType ( ) , variable ) ) ; } } } return ret ; }
The actual lookup
2,178
private Set < MemberLookupResult > performNestedLookup ( String variable ) { Set < MemberLookupResult > ret = new LinkedHashSet < > ( ) ; String [ ] parts = StringUtils . split ( variable , "." ) ; if ( parts . length > 2 ) { Set < MemberLookupResult > subResult = performNestedLookup ( StringUtils . substringBeforeLast ( variable , "." ) ) ; for ( MemberLookupResult result : subResult ) { if ( result . matches ( parts [ parts . length - 1 ] ) ) { ret . addAll ( getResultsForClass ( result . getReturnType ( ) , variable ) ) ; } } } else { Set < MemberLookupResult > subResults = performMemberLookup ( parts [ 0 ] ) ; for ( MemberLookupResult result : subResults ) { if ( result . matches ( parts [ 1 ] ) ) { ret . addAll ( getResultsForClass ( result . getReturnType ( ) , variable ) ) ; } } } return ret ; }
performs a nested lookup . E . g for foo . bar it will resolve the type of bar and then get it s methods
2,179
private Set < MemberLookupResult > getMethodsFromClassLoader ( String clazzname , String variable ) { final Set < MemberLookupResult > ret = new LinkedHashSet < > ( ) ; try { Class clazz = classPath . getClassLoader ( true ) . loadClass ( clazzname ) ; for ( Method method : clazz . getMethods ( ) ) { if ( method . getReturnType ( ) != Void . TYPE && GETTER_PATTERN . matcher ( method . getName ( ) ) . matches ( ) ) { ret . add ( new MemberLookupResult ( variable , method . getName ( ) , method . getReturnType ( ) . getName ( ) ) ) ; } } for ( Field field : clazz . getFields ( ) ) { ret . add ( new MemberLookupResult ( variable , field . getName ( ) , field . getType ( ) . getName ( ) ) ) ; } } catch ( ClassNotFoundException cnfe ) { LOGGER . log ( Level . FINE , "Could not resolve class " + clazzname + "defined for variable " + variable , cnfe ) ; } return ret ; }
Fallback used to load the methods from classloader
2,180
public void installFile ( PackageFile packageFile ) { File file = packageFile . getFile ( ) ; if ( ! file . exists ( ) ) { throw new PackageManagerException ( "File does not exist: " + file . getAbsolutePath ( ) ) ; } try ( CloseableHttpClient httpClient = pkgmgr . getHttpClient ( ) ) { pkgmgr . waitForBundlesActivation ( httpClient ) ; if ( packageFile . isInstall ( ) ) { log . info ( "Upload and install " + ( packageFile . isForce ( ) ? "(force) " : "" ) + file . getName ( ) + " to " + props . getPackageManagerUrl ( ) ) ; } else { log . info ( "Upload " + file . getName ( ) + " to " + props . getPackageManagerUrl ( ) ) ; } VendorPackageInstaller installer = VendorInstallerFactory . getPackageInstaller ( props . getPackageManagerUrl ( ) ) ; if ( installer != null ) { installer . installPackage ( packageFile , pkgmgr , httpClient , props , log ) ; } } catch ( IOException ex ) { throw new PackageManagerException ( "Install operation failed." , ex ) ; } }
Deploy file via package manager .
2,181
void merge ( DefaultWorkspaceFilter workspaceFilter ) { for ( Filter item : filters ) { PathFilterSet filterSet = toFilterSet ( item ) ; boolean exists = false ; for ( PathFilterSet existingFilterSet : workspaceFilter . getFilterSets ( ) ) { if ( filterSet . equals ( existingFilterSet ) ) { exists = true ; } } if ( ! exists ) { workspaceFilter . add ( filterSet ) ; } } }
Merge configured filter paths with existing workspace filter definition .
2,182
public static Service identify ( String url ) { Service answer = Service . UNSUPPORTED ; int index = url . indexOf ( COMPOSUM_URL ) ; if ( index > 0 ) { answer = Service . COMPOSUM ; } else { index = url . indexOf ( CRX_URL ) ; if ( index > 0 ) { answer = Service . CRX ; } } return answer ; }
Identifies the Service Vendor based on the given URL
2,183
public static String getBaseUrl ( String url , Logger logger ) { String answer = url ; switch ( identify ( url ) ) { case COMPOSUM : answer = url . substring ( 0 , url . indexOf ( COMPOSUM_URL ) ) ; break ; case CRX : answer = url . substring ( 0 , url . indexOf ( CRX_URL ) ) ; break ; default : logger . error ( "Given URL is not supported: " + url ) ; } return answer ; }
Returns the Base Url of a given URL with based on its Vendors from the URL
2,184
public static VendorPackageInstaller getPackageInstaller ( String url ) throws PackageManagerException { VendorPackageInstaller answer ; switch ( identify ( url ) ) { case COMPOSUM : answer = new ComposumPackageInstaller ( url ) ; break ; case CRX : answer = new CrxPackageInstaller ( url ) ; break ; default : throw new PackageManagerException ( "Given URL is not supported: " + url ) ; } return answer ; }
Provides the Installer of the Service Vendor
2,185
public String getI18nXmlString ( ) { Format format = Format . getPrettyFormat ( ) ; XMLOutputter outputter = new XMLOutputter ( format ) ; return outputter . outputString ( buildI18nXml ( ) ) ; }
Build i18n resource XML in Sling i18n Message format .
2,186
public String getI18nPropertiesString ( ) throws IOException { Properties i18nProps = new Properties ( ) ; for ( Entry < String , String > entry : properties . entrySet ( ) ) { String key = entry . getKey ( ) ; String escapedKey = validName ( key ) ; i18nProps . put ( escapedKey , entry . getValue ( ) ) ; } try ( ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ) { i18nProps . store ( outStream , null ) ; return outStream . toString ( CharEncoding . ISO_8859_1 ) ; } }
Build i18n resource PROPERTIES .
2,187
public Document buildContent ( Map < String , Object > content ) { Document doc = documentBuilder . newDocument ( ) ; String primaryType = StringUtils . defaultString ( ( String ) content . get ( PN_PRIMARY_TYPE ) , NT_UNSTRUCTURED ) ; Element jcrRoot = createJcrRoot ( doc , primaryType ) ; exportPayload ( doc , jcrRoot , content ) ; return doc ; }
Build XML for any JCR content .
2,188
public Document buildFilter ( List < PackageFilter > filters ) { Document doc = documentBuilder . newDocument ( ) ; Element workspaceFilterElement = doc . createElement ( "workspaceFilter" ) ; workspaceFilterElement . setAttribute ( "version" , "1.0" ) ; doc . appendChild ( workspaceFilterElement ) ; for ( PackageFilter filter : filters ) { Element filterElement = doc . createElement ( "filter" ) ; filterElement . setAttribute ( "root" , filter . getRootPath ( ) ) ; workspaceFilterElement . appendChild ( filterElement ) ; for ( PackageFilterRule rule : filter . getRules ( ) ) { Element ruleElement = doc . createElement ( rule . isInclude ( ) ? "include" : "exclude" ) ; ruleElement . setAttribute ( "pattern" , rule . getPattern ( ) ) ; filterElement . appendChild ( ruleElement ) ; } } return doc ; }
Build filter XML for package metadata files .
2,189
public Rule getRule ( Resource resource ) { for ( Rule rule : rules ) { if ( rule . matches ( resource ) ) { return rule ; } } return null ; }
Get rule matching for the given GraniteUI resource .
2,190
public File downloadFile ( File file , String ouputFilePath ) { try ( CloseableHttpClient httpClient = pkgmgr . getHttpClient ( ) ) { log . info ( "Download " + file . getName ( ) + " from " + props . getPackageManagerUrl ( ) ) ; HttpPost post = new HttpPost ( props . getPackageManagerUrl ( ) + "/.json?cmd=upload" ) ; MultipartEntityBuilder entity = MultipartEntityBuilder . create ( ) . addBinaryBody ( "package" , file ) . addTextBody ( "force" , "true" ) ; post . setEntity ( entity . build ( ) ) ; JSONObject jsonResponse = pkgmgr . executePackageManagerMethodJson ( httpClient , post ) ; boolean success = jsonResponse . optBoolean ( "success" , false ) ; String msg = jsonResponse . optString ( "msg" , null ) ; String path = jsonResponse . optString ( "path" , null ) ; if ( ! success && StringUtils . startsWith ( msg , CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX ) && StringUtils . isEmpty ( path ) ) { path = StringUtils . substringAfter ( msg , CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX ) ; success = true ; } if ( ! success ) { throw new PackageManagerException ( "Package path detection failed: " + msg ) ; } log . info ( "Package path is: " + path + " - now rebuilding package..." ) ; HttpPost buildMethod = new HttpPost ( props . getPackageManagerUrl ( ) + "/console.html" + path + "?cmd=build" ) ; pkgmgr . executePackageManagerMethodHtmlOutputResponse ( httpClient , buildMethod ) ; String baseUrl = VendorInstallerFactory . getBaseUrl ( props . getPackageManagerUrl ( ) , log ) ; HttpGet downloadMethod = new HttpGet ( baseUrl + path ) ; CloseableHttpResponse response = httpClient . execute ( downloadMethod ) ; try { if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { InputStream responseStream = response . getEntity ( ) . getContent ( ) ; File outputFileObject = new File ( ouputFilePath ) ; if ( outputFileObject . exists ( ) ) { outputFileObject . delete ( ) ; } FileOutputStream fos = new FileOutputStream ( outputFileObject ) ; IOUtils . copy ( responseStream , fos ) ; fos . flush ( ) ; responseStream . close ( ) ; fos . close ( ) ; log . info ( "Package downloaded to " + outputFileObject . getAbsolutePath ( ) ) ; return outputFileObject ; } else { throw new PackageManagerException ( "Package download failed:\n" + EntityUtils . toString ( response . getEntity ( ) ) ) ; } } finally { if ( response != null ) { EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; try { response . close ( ) ; } catch ( IOException ex ) { } } } } catch ( FileNotFoundException ex ) { throw new PackageManagerException ( "File not found: " + file . getAbsolutePath ( ) , ex ) ; } catch ( IOException ex ) { throw new PackageManagerException ( "Download operation failed." , ex ) ; } }
Download content package from CRX instance .
2,191
private String sortWeakReferenceValues ( String name , String value ) { Set < String > refs = new TreeSet < > ( ) ; DocViewProperty prop = DocViewProperty . parse ( name , value ) ; for ( int i = 0 ; i < prop . values . length ; i ++ ) { refs . add ( prop . values [ i ] ) ; } List < Value > values = new ArrayList < > ( ) ; for ( String ref : refs ) { values . add ( new MockValue ( ref , PropertyType . WEAKREFERENCE ) ) ; } try { String sortedValues = DocViewProperty . format ( new MockProperty ( name , true , values . toArray ( new Value [ values . size ( ) ] ) ) ) ; return sortedValues ; } catch ( RepositoryException ex ) { throw new RuntimeException ( "Unable to format value for " + name , ex ) ; } }
Sort weak reference values alphabetically to ensure consistent ordering .
2,192
public String getMatchingBundle ( Pattern symbolicNamePattern ) { for ( String bundleSymbolicName : bundleSymbolicNames ) { if ( symbolicNamePattern . matcher ( bundleSymbolicName ) . matches ( ) ) { return bundleSymbolicName ; } } return null ; }
Checks if a bundle with the given pattern exists in the bundle list .
2,193
protected JavaSource getJavaSourceForClass ( String clazzname ) { String resource = clazzname . replaceAll ( "\\." , "/" ) + ".java" ; FileObject fileObject = classPath . findResource ( resource ) ; if ( fileObject == null ) { return null ; } Project project = FileOwnerQuery . getOwner ( fileObject ) ; if ( project == null ) { return null ; } SourceGroup [ ] sourceGroups = ProjectUtils . getSources ( project ) . getSourceGroups ( "java" ) ; for ( SourceGroup sourceGroup : sourceGroups ) { return JavaSource . create ( ClasspathInfo . create ( sourceGroup . getRootFolder ( ) ) ) ; } return null ; }
Resolves the clazzname to a fileobject of the java - file
2,194
protected Set < Element > getMembersFromJavaSource ( final String clazzname , final ElementUtilities . ElementAcceptor acceptor ) { final Set < Element > ret = new LinkedHashSet < > ( ) ; JavaSource javaSource = getJavaSourceForClass ( clazzname ) ; if ( javaSource != null ) { try { javaSource . runUserActionTask ( new Task < CompilationController > ( ) { public void run ( CompilationController controller ) throws IOException { controller . toPhase ( JavaSource . Phase . ELEMENTS_RESOLVED ) ; TypeElement classElem = controller . getElements ( ) . getTypeElement ( clazzname ) ; if ( classElem == null ) { return ; } ElementUtilities eu = controller . getElementUtilities ( ) ; Iterable < ? extends Element > members = eu . getMembers ( classElem . asType ( ) , acceptor ) ; for ( Element e : members ) { ret . add ( e ) ; } } } , false ) ; } catch ( IOException ioe ) { Exceptions . printStackTrace ( ioe ) ; } } return ret ; }
tries to load all members for the given clazzname from javasource files .
2,195
public void run ( ) throws MojoExecutionException { if ( skip ) { return ; } if ( tasks == null || tasks . isEmpty ( ) ) { getLog ( ) . warn ( "No Node.js tasks have been defined. Nothing to do." ) ; } ComparableVersion nodeJsVersionComparable = new ComparableVersion ( nodeJsVersion ) ; if ( nodeJsVersionComparable . compareTo ( NODEJS_MIN_VERSION ) < 0 ) { throw new MojoExecutionException ( "This plugin supports Node.js " + NODEJS_MIN_VERSION + " and up." ) ; } NodeInstallationInformation information = getOrInstallNodeJS ( ) ; if ( tasks != null ) { for ( Task task : tasks ) { task . setLog ( getLog ( ) ) ; task . execute ( information ) ; } } }
Installs node js if necessary and performs defined tasks
2,196
private void updateNPMExecutable ( NodeInstallationInformation information ) throws MojoExecutionException { getLog ( ) . info ( "Installing specified npm version " + npmVersion ) ; NpmInstallTask npmInstallTask = new NpmInstallTask ( ) ; npmInstallTask . setLog ( getLog ( ) ) ; npmInstallTask . setNpmBundledWithNodeJs ( true ) ; npmInstallTask . setArguments ( new String [ ] { "--prefix" , information . getNodeModulesRootPath ( ) , "--global" , "npm@" + npmVersion } ) ; npmInstallTask . execute ( information ) ; }
Makes sure the specified npm version is installed in the base directory regardless in which environment .
2,197
private boolean mapProperty ( JSONObject root , JSONObject node , String key , String ... mapping ) throws JSONException { boolean deleteProperty = false ; for ( String value : mapping ) { Matcher matcher = MAPPED_PATTERN . matcher ( value ) ; if ( matcher . matches ( ) ) { deleteProperty = true ; String path = matcher . group ( 2 ) ; path = StringUtils . removeStart ( StringUtils . stripEnd ( path , "\'" ) , "\'" ) ; if ( root . has ( cleanup ( path ) ) ) { Object originalValue = root . get ( cleanup ( path ) ) ; node . put ( cleanup ( key ) , originalValue ) ; String negate = matcher . group ( 1 ) ; if ( "!" . equals ( negate ) && ( originalValue instanceof Boolean ) ) { node . put ( cleanup ( key ) , ! ( ( Boolean ) originalValue ) ) ; } deleteProperty = false ; break ; } else { String defaultValue = matcher . group ( 4 ) ; if ( defaultValue != null ) { node . put ( cleanup ( key ) , defaultValue ) ; deleteProperty = false ; break ; } } } } if ( deleteProperty ) { node . remove ( key ) ; return false ; } return true ; }
Replaces the value of a mapped property with a value from the original tree .
2,198
private void rewriteProperty ( JSONObject node , String key , JSONArray rewriteProperty ) throws JSONException { if ( node . get ( cleanup ( key ) ) instanceof String ) { if ( rewriteProperty . length ( ) == 2 ) { if ( rewriteProperty . get ( 0 ) instanceof String && rewriteProperty . get ( 1 ) instanceof String ) { String pattern = rewriteProperty . getString ( 0 ) ; String replacement = rewriteProperty . getString ( 1 ) ; Pattern compiledPattern = Pattern . compile ( pattern ) ; Matcher matcher = compiledPattern . matcher ( node . getString ( cleanup ( key ) ) ) ; node . put ( cleanup ( key ) , matcher . replaceAll ( replacement ) ) ; } } } }
Applies a string rewrite to a property .
2,199
private void addCommonAttrMappings ( JSONObject root , JSONObject node ) throws JSONException { for ( String property : GRANITE_COMMON_ATTR_PROPERTIES ) { String [ ] mapping = { "${./" + property + "}" , "${\'./granite:" + property + "\'}" } ; mapProperty ( root , node , "granite:" + property , mapping ) ; } if ( root . has ( NN_GRANITE_DATA ) ) { node . put ( NN_GRANITE_DATA , root . get ( NN_GRANITE_DATA ) ) ; } for ( Map . Entry < String , Object > entry : getProperties ( root ) . entrySet ( ) ) { if ( ! StringUtils . startsWith ( entry . getKey ( ) , DATA_PREFIX ) ) { continue ; } JSONObject dataNode ; if ( ! node . has ( NN_GRANITE_DATA ) ) { dataNode = new JSONObject ( ) ; node . put ( NN_GRANITE_DATA , dataNode ) ; } else { dataNode = node . getJSONObject ( NN_GRANITE_DATA ) ; } String nameWithoutPrefix = entry . getKey ( ) . substring ( DATA_PREFIX . length ( ) ) ; mapProperty ( root , dataNode , nameWithoutPrefix , "${./" + entry . getKey ( ) + "}" ) ; } }
Adds property mappings on a replacement node for Granite common attributes .