id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
6,800
motown-io/motown
ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/wamp/WampMessageParser.java
WampMessageParser.removeQuotes
private String removeQuotes(String toReplace) { String noQuotes = toReplace.replaceAll("\"", ""); noQuotes = noQuotes.replaceAll("'", ""); return noQuotes; }
java
private String removeQuotes(String toReplace) { String noQuotes = toReplace.replaceAll("\"", ""); noQuotes = noQuotes.replaceAll("'", ""); return noQuotes; }
[ "private", "String", "removeQuotes", "(", "String", "toReplace", ")", "{", "String", "noQuotes", "=", "toReplace", ".", "replaceAll", "(", "\"\\\"\"", ",", "\"\"", ")", ";", "noQuotes", "=", "noQuotes", ".", "replaceAll", "(", "\"'\"", ",", "\"\"", ")", ";", "return", "noQuotes", ";", "}" ]
Removes all single and double quotes from the given String. @param toReplace String to replace the quotes from @return String without quotes
[ "Removes", "all", "single", "and", "double", "quotes", "from", "the", "given", "String", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/wamp/WampMessageParser.java#L120-L124
6,801
motown-io/motown
mobi-europe/source/src/main/java/io/motown/mobieurope/source/entities/SourceAuthorizeRequest.java
SourceAuthorizeRequest.getAuthorizeRequest
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; }
java
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; }
[ "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
[ "The", "type", "of", "service", "this", "local", "service", "provides" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/mobi-europe/source/src/main/java/io/motown/mobieurope/source/entities/SourceAuthorizeRequest.java#L38-L46
6,802
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/io/AbstractCsvAnnotationBeanWriter.java
AbstractCsvAnnotationBeanWriter.extractBeanValues
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); // assume they always want a blank column } 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); } } } }
java
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); // assume they always want a blank column } 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); } } } }
[ "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", ")", ";", "// assume they always want a blank column\r", "}", "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. @param source the bean @param nameMapping the name mapping @throws NullPointerException if source or nameMapping are null @throws SuperCsvReflectionException if there was a reflection exception extracting the bean value
[ "Extracts", "the", "bean", "values", "using", "the", "supplied", "name", "mapping", "array", "." ]
9910320cb6dc143be972c7d10d9ab5ffb09c3b84
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/io/AbstractCsvAnnotationBeanWriter.java#L183-L209
6,803
motown-io/motown
operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/repositories/ReservationRepository.java
ReservationRepository.findByChargingStationIdEvseIdUserId
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(); } }
java
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(); } }
[ "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 @param chargingStationId @param evseid @param UserId @return @throws NoResultException
[ "find", "reservations", "by", "chargingstationid", "evseid", "and", "userId" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/repositories/ReservationRepository.java#L86-L97
6,804
motown-io/motown
domain/core-api/src/main/java/io/motown/domain/api/chargingstation/NumberedTransactionId.java
NumberedTransactionId.numberFromTransactionIdString
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)); } }
java
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)); } }
[ "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. @param chargingStationId the charging station's identifier. @param protocol the protocol identifier. @param transactionId the transaction id containing the number. @return the transaction number @throws NumberFormatException if the number cannot be extracted from {@code transactionId}.
[ "Retrieves", "the", "number", "from", "a", "transaction", "id", "string", ".", "ChargingStationId", "and", "protocol", "are", "passed", "to", "make", "a", "better", "guess", "at", "the", "number", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/domain/core-api/src/main/java/io/motown/domain/api/chargingstation/NumberedTransactionId.java#L110-L117
6,805
motown-io/motown
mobi-europe/source/src/main/java/io/motown/mobieurope/source/api/rest/SourceResource.java
SourceResource.getSession
@POST @Path("/session") public Response getSession(String authorizationIdentifier) { return Response.ok().entity(sourceSessionRepository.findSessionInfoByAuthorizationId(authorizationIdentifier)).build(); }
java
@POST @Path("/session") public Response getSession(String authorizationIdentifier) { return Response.ok().entity(sourceSessionRepository.findSessionInfoByAuthorizationId(authorizationIdentifier)).build(); }
[ "@", "POST", "@", "Path", "(", "\"/session\"", ")", "public", "Response", "getSession", "(", "String", "authorizationIdentifier", ")", "{", "return", "Response", ".", "ok", "(", ")", ".", "entity", "(", "sourceSessionRepository", ".", "findSessionInfoByAuthorizationId", "(", "authorizationIdentifier", ")", ")", ".", "build", "(", ")", ";", "}" ]
Polling of the sessionInfo @param authorizationIdentifier The session authorizationIdentifier @return The session for the given authorizationIdentifier
[ "Polling", "of", "the", "sessionInfo" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/mobi-europe/source/src/main/java/io/motown/mobieurope/source/api/rest/SourceResource.java#L133-L137
6,806
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.createEvse
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()); }
java
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()); }
[ "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. @param chargingStationTypeId charging station type identifier. @param evse evse object @return created Evse
[ "Creates", "a", "Evse", "in", "a", "charging", "station", "type", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L73-L84
6,807
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvses
public Set<Evse> getEvses(Long chargingStationTypeId) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); return chargingStationType.getEvses(); }
java
public Set<Evse> getEvses(Long chargingStationTypeId) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); return chargingStationType.getEvses(); }
[ "public", "Set", "<", "Evse", ">", "getEvses", "(", "Long", "chargingStationTypeId", ")", "{", "ChargingStationType", "chargingStationType", "=", "chargingStationTypeRepository", ".", "findOne", "(", "chargingStationTypeId", ")", ";", "return", "chargingStationType", ".", "getEvses", "(", ")", ";", "}" ]
Gets the Evses of a charging station type. @param chargingStationTypeId charging station type identifier. @return set of Evses
[ "Gets", "the", "Evses", "of", "a", "charging", "station", "type", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L92-L96
6,808
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.updateChargingStationType
public ChargingStationType updateChargingStationType(Long id, ChargingStationType chargingStationType) { chargingStationType.setId(id); return chargingStationTypeRepository.createOrUpdate(chargingStationType); }
java
public ChargingStationType updateChargingStationType(Long id, ChargingStationType chargingStationType) { chargingStationType.setId(id); return chargingStationTypeRepository.createOrUpdate(chargingStationType); }
[ "public", "ChargingStationType", "updateChargingStationType", "(", "Long", "id", ",", "ChargingStationType", "chargingStationType", ")", "{", "chargingStationType", ".", "setId", "(", "id", ")", ";", "return", "chargingStationTypeRepository", ".", "createOrUpdate", "(", "chargingStationType", ")", ";", "}" ]
Update a charging station type. @param id the id of the entity to find. @param chargingStationType the payload from the request.
[ "Update", "a", "charging", "station", "type", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L131-L134
6,809
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getConnectors
public Set<Connector> getConnectors(Long chargingStationTypeId, Long evseId) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); return evse.getConnectors(); }
java
public Set<Connector> getConnectors(Long chargingStationTypeId, Long evseId) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); return evse.getConnectors(); }
[ "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. @param chargingStationTypeId charging station identifier. @param evseId evse id. @return set of connectors.
[ "Gets", "the", "connectors", "for", "a", "charging", "station", "type", "evse", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L180-L185
6,810
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.createConnector
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; } }
java
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; } }
[ "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. @param chargingStationTypeId charging station identifier. @param evseId evse id. @param connector connector to be created. @return created connector.
[ "Creates", "a", "connector", "in", "a", "charging", "station", "type", "evse", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L195-L212
6,811
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.updateConnector
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()); }
java
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()); }
[ "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. @param chargingStationTypeId charging station type identifier. @param evseId the id of the evse that contains the connector. @param connector the payload from the request. @return updated connector.
[ "Update", "a", "connector", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L222-L236
6,812
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getConnector
public Connector getConnector(Long chargingStationTypeId, Long evseId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); return getConnectorById(evse, id); }
java
public Connector getConnector(Long chargingStationTypeId, Long evseId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); return getConnectorById(evse, id); }
[ "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. @param id the id of the entity to find. @return the connector.
[ "Find", "a", "connector", "based", "on", "its", "id", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L244-L249
6,813
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.deleteConnector
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); }
java
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); }
[ "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. @param id the id of the entity to delete.
[ "Delete", "a", "connector", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L256-L264
6,814
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.updateEvse
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()); }
java
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()); }
[ "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. @param evse evse object to update. @return updated evse.
[ "Update", "an", "evse", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L272-L283
6,815
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvse
public Evse getEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); return getEvseById(chargingStationType, id); }
java
public Evse getEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); return getEvseById(chargingStationType, id); }
[ "public", "Evse", "getEvse", "(", "Long", "chargingStationTypeId", ",", "Long", "id", ")", "{", "ChargingStationType", "chargingStationType", "=", "chargingStationTypeRepository", ".", "findOne", "(", "chargingStationTypeId", ")", ";", "return", "getEvseById", "(", "chargingStationType", ",", "id", ")", ";", "}" ]
Find an evse based on its id. @param chargingStationTypeId charging station identifier. @param id the id of the evse to find. @return the evse.
[ "Find", "an", "evse", "based", "on", "its", "id", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L292-L296
6,816
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.deleteEvse
public void deleteEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); chargingStationType.getEvses().remove(getEvseById(chargingStationType, id)); updateChargingStationType(chargingStationType.getId(), chargingStationType); }
java
public void deleteEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); chargingStationType.getEvses().remove(getEvseById(chargingStationType, id)); updateChargingStationType(chargingStationType.getId(), chargingStationType); }
[ "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. @param chargingStationTypeId charging station identifier. @param id the id of the evse to delete.
[ "Delete", "an", "evse", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L304-L310
6,817
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.updateManufacturer
public Manufacturer updateManufacturer(Long id, Manufacturer manufacturer) { manufacturer.setId(id); return manufacturerRepository.createOrUpdate(manufacturer); }
java
public Manufacturer updateManufacturer(Long id, Manufacturer manufacturer) { manufacturer.setId(id); return manufacturerRepository.createOrUpdate(manufacturer); }
[ "public", "Manufacturer", "updateManufacturer", "(", "Long", "id", ",", "Manufacturer", "manufacturer", ")", "{", "manufacturer", ".", "setId", "(", "id", ")", ";", "return", "manufacturerRepository", ".", "createOrUpdate", "(", "manufacturer", ")", ";", "}" ]
Update a manufacturer. @param id the id of the entity to find. @param manufacturer the payload from the request.
[ "Update", "a", "manufacturer", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L327-L330
6,818
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvseById
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)); }
java
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)); }
[ "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. @param chargingStationType charging station type. @param id evse id. @return evse @throws EntityNotFoundException if the Evse cannot be found.
[ "Gets", "a", "Evse", "by", "id", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L395-L402
6,819
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvseByIdentifier
private Evse getEvseByIdentifier(ChargingStationType chargingStationType, int identifier) { for (Evse evse:chargingStationType.getEvses()) { if(identifier == evse.getIdentifier()) { return evse; } } return null; }
java
private Evse getEvseByIdentifier(ChargingStationType chargingStationType, int identifier) { for (Evse evse:chargingStationType.getEvses()) { if(identifier == evse.getIdentifier()) { return evse; } } return null; }
[ "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. @param chargingStationType charging station type. @param identifier evse identifier. @return evse or null if not found.
[ "Gets", "a", "Evse", "by", "identifier", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L445-L452
6,820
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/rest/CpoService.java
CpoService.getSubscriptionFromRequest
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; }
java
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; }
[ "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. @param request request that should contain the authorization value @return subscription object if it can be found for the token value extracted from the request.
[ "Finds", "Subscription", "object", "based", "on", "request", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/rest/CpoService.java#L82-L97
6,821
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/persistence/entities/Subscription.java
Subscription.getEndpoint
public Endpoint getEndpoint(ModuleIdentifier identifier) { for (Endpoint endpoint : getEndpoints()) { if (endpoint.getIdentifier().equals(identifier)) { return endpoint; } } return null; }
java
public Endpoint getEndpoint(ModuleIdentifier identifier) { for (Endpoint endpoint : getEndpoints()) { if (endpoint.getIdentifier().equals(identifier)) { return endpoint; } } return null; }
[ "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 @param identifier @return Endpoint
[ "returns", "the", "Endpoint", "with", "the", "identifier", "passed", "as", "argument", "if", "not", "found", "returns", "null" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/persistence/entities/Subscription.java#L100-L107
6,822
motown-io/motown
ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java
DomainService.startTransaction
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 the token, the future contains the call to start the transaction authorize(chargingStationId, idTag.getToken(), futureEventCallback, addOnIdentity); }
java
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 the token, the future contains the call to start the transaction authorize(chargingStationId, idTag.getToken(), futureEventCallback, addOnIdentity); }
[ "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 the token, the future contains the call to start the transaction", "authorize", "(", "chargingStationId", ",", "idTag", ".", "getToken", "(", ")", ",", "futureEventCallback", ",", "addOnIdentity", ")", ";", "}" ]
Generates a transaction identifier and starts a transaction by dispatching a StartTransactionCommand. @param chargingStationId identifier of the charging station. @param evseId evse identifier on which the transaction is started. @param idTag the identification which started the transaction. @param futureEventCallback will be called once the authorize result event occurs. @param addOnIdentity identity of the add on that calls this method.
[ "Generates", "a", "transaction", "identifier", "and", "starts", "a", "transaction", "by", "dispatching", "a", "StartTransactionCommand", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java#L216-L226
6,823
motown-io/motown
ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java
DomainService.changeConfiguration
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); }
java
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); }
[ "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. @param chargingStationId the charging station id. @param configurationItem the configuration item which has changed. @param correlationToken the token to correlate commands and events that belong together. @param addOnIdentity the identity of the add-on.
[ "Change", "the", "configuration", "in", "the", "charging", "station", ".", "It", "has", "already", "happened", "on", "the", "physical", "charging", "station", "but", "the", "Domain", "has", "not", "been", "updated", "yet", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java#L353-L357
6,824
motown-io/motown
ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java
DomainService.createTransaction
public Transaction createTransaction(EvseId evseId) { Transaction transaction = new Transaction(); transaction.setEvseId(evseId); transactionRepository.insert(transaction); return transaction; }
java
public Transaction createTransaction(EvseId evseId) { Transaction transaction = new Transaction(); transaction.setEvseId(evseId); transactionRepository.insert(transaction); return transaction; }
[ "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. @param evseId evse identifier that's stored in the transaction @return transaction
[ "Creates", "a", "transaction", "identifier", ".", "The", "EVSE", "identifier", "is", "stored", "for", "later", "usage", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java#L443-L450
6,825
motown-io/motown
ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java
DomainService.checkChargingStationExistsAndIsRegisteredAndConfigured
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; }
java
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; }
[ "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. @param chargingStationId charging station identifier. @return ChargingStation if the charging station exists and is registered and configured. @throws IllegalStateException if the charging station does not exist in the repository, or it has not been registered and configured.
[ "Checks", "if", "the", "charging", "station", "exists", "in", "the", "repository", "and", "if", "it", "has", "been", "registered", "and", "configured", ".", "If", "not", "a", "IllegalStateException", "will", "be", "thrown", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java#L461-L473
6,826
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java
SubscriptionService.findHighestMutualVersion
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; }
java
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; }
[ "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 @param offeredVersions @return
[ "returns", "the", "highest", "mutual", "version", "between", "the", "offeredVersions", "of", "the", "partner", "and", "the", "supported", "versions", "on", "our", "side" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java#L82-L93
6,827
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java
SubscriptionService.postCredentials
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; }
java
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; }
[ "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 @param subscription @return the definitive partnerAuthorizationToken in the post response
[ "Posts", "the", "credentials", "of", "the", "user", "with", "the", "EMSP", "credentials", "endpoint" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java#L133-L167
6,828
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java
SubscriptionService.register
@Transactional 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()); // store version and endpoints for this subscription subscription.setOcpiVersion(version.version); for (io.motown.ocpi.dto.Endpoint endpoint : versionDetails.endpoints) { subscription.addToEndpoints(new Endpoint(endpoint.identifier, endpoint.url.toString())); // because the endpoints in 'versionInformationResponse' are not // DTO's (yet) we must instantiate ModuleIdentifier from value } // if not present generate a new token if (subscription.getAuthorizationToken() == null) { subscription.generateNewAuthorizationToken(); } ocpiRepository.insertOrUpdate(subscription); Credentials credentials = postCredentials(subscription); if (credentials.token != null) { // if no token update do not overwrite // existing partner token! LOG.debug("Updating partnerToken with: " + credentials.token); subscription.setPartnerAuthorizationToken(credentials.token); // at this point we can safely remove the versionsEndpoint LOG.info("REMOVING VERIONS-ENDPOINT"); subscription.getEndpoints().remove(versionsEndpoint); ocpiRepository.insertOrUpdate(subscription); } }
java
@Transactional 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()); // store version and endpoints for this subscription subscription.setOcpiVersion(version.version); for (io.motown.ocpi.dto.Endpoint endpoint : versionDetails.endpoints) { subscription.addToEndpoints(new Endpoint(endpoint.identifier, endpoint.url.toString())); // because the endpoints in 'versionInformationResponse' are not // DTO's (yet) we must instantiate ModuleIdentifier from value } // if not present generate a new token if (subscription.getAuthorizationToken() == null) { subscription.generateNewAuthorizationToken(); } ocpiRepository.insertOrUpdate(subscription); Credentials credentials = postCredentials(subscription); if (credentials.token != null) { // if no token update do not overwrite // existing partner token! LOG.debug("Updating partnerToken with: " + credentials.token); subscription.setPartnerAuthorizationToken(credentials.token); // at this point we can safely remove the versionsEndpoint LOG.info("REMOVING VERIONS-ENDPOINT"); subscription.getEndpoints().remove(versionsEndpoint); ocpiRepository.insertOrUpdate(subscription); } }
[ "@", "Transactional", "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", "(", ")", ")", ";", "// store version and endpoints for this subscription", "subscription", ".", "setOcpiVersion", "(", "version", ".", "version", ")", ";", "for", "(", "io", ".", "motown", ".", "ocpi", ".", "dto", ".", "Endpoint", "endpoint", ":", "versionDetails", ".", "endpoints", ")", "{", "subscription", ".", "addToEndpoints", "(", "new", "Endpoint", "(", "endpoint", ".", "identifier", ",", "endpoint", ".", "url", ".", "toString", "(", ")", ")", ")", ";", "// because the endpoints in 'versionInformationResponse' are not", "// DTO's (yet) we must instantiate ModuleIdentifier from value", "}", "// if not present generate a new token", "if", "(", "subscription", ".", "getAuthorizationToken", "(", ")", "==", "null", ")", "{", "subscription", ".", "generateNewAuthorizationToken", "(", ")", ";", "}", "ocpiRepository", ".", "insertOrUpdate", "(", "subscription", ")", ";", "Credentials", "credentials", "=", "postCredentials", "(", "subscription", ")", ";", "if", "(", "credentials", ".", "token", "!=", "null", ")", "{", "// if no token update do not overwrite", "// existing partner token!", "LOG", ".", "debug", "(", "\"Updating partnerToken with: \"", "+", "credentials", ".", "token", ")", ";", "subscription", ".", "setPartnerAuthorizationToken", "(", "credentials", ".", "token", ")", ";", "// at this point we can safely remove the versionsEndpoint", "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 @param tokenProvider
[ "registers", "with", "the", "EMSP", "with", "passed", "as", "argument", "the", "endpoints", "of", "this", "EMSP", "are", "stored", "in", "the", "database", "as", "well", "as", "the", "definitive", "token" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/SubscriptionService.java#L175-L215
6,829
motown-io/motown
samples/authentication/src/main/java/io/motown/sample/authentication/rest/AuthenticationTokenProcessingFilter.java
AuthenticationTokenProcessingFilter.getAuthTokenFromRequest
private String getAuthTokenFromRequest(HttpServletRequest httpRequest) { String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER_KEY); if (authToken == null) { // token can also exist as request parameter authToken = httpRequest.getParameter(AUTH_TOKEN_PARAMETER_KEY); } return authToken; }
java
private String getAuthTokenFromRequest(HttpServletRequest httpRequest) { String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER_KEY); if (authToken == null) { // token can also exist as request parameter authToken = httpRequest.getParameter(AUTH_TOKEN_PARAMETER_KEY); } return authToken; }
[ "private", "String", "getAuthTokenFromRequest", "(", "HttpServletRequest", "httpRequest", ")", "{", "String", "authToken", "=", "httpRequest", ".", "getHeader", "(", "AUTH_TOKEN_HEADER_KEY", ")", ";", "if", "(", "authToken", "==", "null", ")", "{", "// token can also exist as request parameter", "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. @param httpRequest request. @return authorization token if it exists in the request.
[ "Gets", "the", "authorization", "token", "from", "the", "request", ".", "First", "tries", "the", "header", "if", "that", "s", "empty", "the", "parameter", "is", "checked", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/samples/authentication/src/main/java/io/motown/sample/authentication/rest/AuthenticationTokenProcessingFilter.java#L77-L86
6,830
motown-io/motown
utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java
ResponseBuilder.getPreviousPageOffset
private static int getPreviousPageOffset(final int offset, final int limit) { return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
java
private static int getPreviousPageOffset(final int offset, final int limit) { return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
[ "private", "static", "int", "getPreviousPageOffset", "(", "final", "int", "offset", ",", "final", "int", "limit", ")", "{", "return", "hasFullPreviousPage", "(", "offset", ",", "limit", ")", "?", "getPreviousFullPageOffset", "(", "offset", ",", "limit", ")", ":", "getFirstPageOffset", "(", ")", ";", "}" ]
Gets the previous page offset. @param offset the current offset. @param limit the limit. @return the previous page offset.
[ "Gets", "the", "previous", "page", "offset", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java#L92-L94
6,831
motown-io/motown
utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java
ResponseBuilder.getNextPageOffset
private static long getNextPageOffset(final int offset, final int limit, final long total) { return hasFullNextPage(offset, limit, total) ? getNextFullPageOffset(offset, limit) : getLastPageOffset(total, limit); }
java
private static long getNextPageOffset(final int offset, final int limit, final long total) { return hasFullNextPage(offset, limit, total) ? getNextFullPageOffset(offset, limit) : getLastPageOffset(total, limit); }
[ "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. @param offset the current offset. @param limit the limit. @param total the total. @return the next page offset.
[ "Gets", "the", "next", "page", "offset", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java#L104-L106
6,832
motown-io/motown
ocpp/v15-soap/src/main/java/io/motown/ocpp/v15/soap/chargepoint/ChargingStationProxyFactory.java
ChargingStationProxyFactory.createChargingStationService
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(); //Force the use of the Async transport, even for synchronous calls ((BindingProvider) chargePointService).getRequestContext().put("use.async.http.conduit", Boolean.TRUE); return chargePointService; }
java
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(); //Force the use of the Async transport, even for synchronous calls ((BindingProvider) chargePointService).getRequestContext().put("use.async.http.conduit", Boolean.TRUE); return chargePointService; }
[ "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", "(", ")", ";", "//Force the use of the Async transport, even for synchronous calls", "(", "(", "BindingProvider", ")", "chargePointService", ")", ".", "getRequestContext", "(", ")", ".", "put", "(", "\"use.async.http.conduit\"", ",", "Boolean", ".", "TRUE", ")", ";", "return", "chargePointService", ";", "}" ]
Creates a charging station web service proxy. @param chargingStationAddress address of the charging station. @return charging station web service proxy
[ "Creates", "a", "charging", "station", "web", "service", "proxy", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/v15-soap/src/main/java/io/motown/ocpp/v15/soap/chargepoint/ChargingStationProxyFactory.java#L34-L50
6,833
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java
AuthorizationService.synchronizeTokens
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); }
java
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); }
[ "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 @param tokenEndPoint endpoint to use for retrieving tokens
[ "Retrieves", "tokens", "from", "the", "enpoint", "passed", "as", "argument", "and", "stores", "these", "in", "the", "database" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java#L49-L85
6,834
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java
AuthorizationService.getLastSyncDate
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; }
java
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; }
[ "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. @return last sync date if it exists, null otherwise
[ "Returns", "the", "formatted", "datetime", "the", "tokens", "where", "last", "synchronized", "if", "it", "exists", "otherwise", "null", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java#L92-L101
6,835
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java
AuthorizationService.updateLastSynchronizationDate
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); }
java
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); }
[ "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. @param syncDate date of the last sync @param subscriptionId the subscription that should be updated
[ "Updates", "the", "last", "sync", "date", "for", "the", "passed", "subscription", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java#L109-L119
6,836
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java
AuthorizationService.insertOrUpdateToken
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); }
java
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); }
[ "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 @param tokenUpdate
[ "Inserts", "a", "token", "or", "updates", "it", "if", "an", "existing", "token", "is", "found", "with", "the", "same", "uid", "and", "issuing", "-", "company" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/service/AuthorizationService.java#L127-L149
6,837
motown-io/motown
utils/soap/src/main/java/io/motown/utils/soap/header/CXFSoapHeaderReader.java
CXFSoapHeaderReader.getChargingStationAddress
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 ""; }
java
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 ""; }
[ "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. @param messageContext message context @return charging station address, or empty string if From header is empty or doesn't exist.
[ "Gets", "the", "charging", "station", "address", "from", "the", "SOAP", "From", "header", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/utils/soap/src/main/java/io/motown/utils/soap/header/CXFSoapHeaderReader.java#L39-L58
6,838
motown-io/motown
samples/authentication/src/main/java/io/motown/sample/authentication/resources/UserResource.java
UserResource.authenticate
@Path("authenticate") @POST @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())); }
java
@Path("authenticate") @POST @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())); }
[ "@", "Path", "(", "\"authenticate\"", ")", "@", "POST", "@", "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. @param username name of the user. @param password password of the user. @return authentication token.
[ "Authenticates", "a", "user", "and", "creates", "an", "authentication", "token", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/samples/authentication/src/main/java/io/motown/sample/authentication/resources/UserResource.java#L46-L55
6,839
motown-io/motown
samples/authentication/src/main/java/io/motown/sample/authentication/rest/TokenUtils.java
TokenUtils.getUserNameFromToken
public static String getUserNameFromToken(String authToken) { if (null == authToken) { return null; } return authToken.split(TOKEN_SEPARATOR)[0]; }
java
public static String getUserNameFromToken(String authToken) { if (null == authToken) { return null; } return authToken.split(TOKEN_SEPARATOR)[0]; }
[ "public", "static", "String", "getUserNameFromToken", "(", "String", "authToken", ")", "{", "if", "(", "null", "==", "authToken", ")", "{", "return", "null", ";", "}", "return", "authToken", ".", "split", "(", "TOKEN_SEPARATOR", ")", "[", "0", "]", ";", "}" ]
Extracts the user name from token. @param authToken token containing username. @return username or null if token is null.
[ "Extracts", "the", "user", "name", "from", "token", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/samples/authentication/src/main/java/io/motown/sample/authentication/rest/TokenUtils.java#L86-L92
6,840
motown-io/motown
samples/authentication/src/main/java/io/motown/sample/authentication/rest/TokenUtils.java
TokenUtils.validateToken
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)); }
java
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)); }
[ "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. @param authToken authorization token. @param userDetails user details. @return true if token is not expired and is equal to computed signature on base of user details.
[ "Validates", "the", "token", "signature", "against", "the", "user", "details", "and", "the", "current", "system", "time", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/samples/authentication/src/main/java/io/motown/sample/authentication/rest/TokenUtils.java#L101-L107
6,841
motown-io/motown
vas/v10-soap/src/main/java/io/motown/vas/v10/soap/subscriber/VasSubscriberServiceProxyFactory.java
VasSubscriberServiceProxyFactory.createVasSubscriberService
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(); //Force the use of the Async transport, even for synchronous calls ((BindingProvider) vasSubscriberService).getRequestContext().put("use.async.http.conduit", Boolean.TRUE); return vasSubscriberService; }
java
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(); //Force the use of the Async transport, even for synchronous calls ((BindingProvider) vasSubscriberService).getRequestContext().put("use.async.http.conduit", Boolean.TRUE); return vasSubscriberService; }
[ "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", "(", ")", ";", "//Force the use of the Async transport, even for synchronous calls", "(", "(", "BindingProvider", ")", "vasSubscriberService", ")", ".", "getRequestContext", "(", ")", ".", "put", "(", "\"use.async.http.conduit\"", ",", "Boolean", ".", "TRUE", ")", ";", "return", "vasSubscriberService", ";", "}" ]
Creates a vas subscriber web service proxy based on the delivery address. @param deliveryAddress delivery address @return subscriber web service proxy
[ "Creates", "a", "vas", "subscriber", "web", "service", "proxy", "based", "on", "the", "delivery", "address", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/vas/v10-soap/src/main/java/io/motown/vas/v10/soap/subscriber/VasSubscriberServiceProxyFactory.java#L34-L50
6,842
motown-io/motown
ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/dto/Versions.java
Versions.find
public Version find(String versionToFind) { for (Version version : list) { if (version.version.equals(versionToFind)) { return version; } } return null; }
java
public Version find(String versionToFind) { for (Version version : list) { if (version.version.equals(versionToFind)) { return version; } } return null; }
[ "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 @param versionToFind @return
[ "find", "returns", "the", "version", "object", "with", "the", "version", "passed", "as", "argument" ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpi/ocpi-identification-authorization-plugin/src/main/java/io/motown/ocpi/dto/Versions.java#L40-L47
6,843
motown-io/motown
vas/view-model/src/main/java/io/motown/vas/viewmodel/ConfigurationConversionService.java
ConfigurationConversionService.getChargeModeFromEvses
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; }
java
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; }
[ "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. @param evses list of EVSEs. @return charge mode or UNSPECIFIED if no specific charge mode can be determined.
[ "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", "." ]
783ccda7c28b273a529ddd47defe8673b1ea365b
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/vas/view-model/src/main/java/io/motown/vas/viewmodel/ConfigurationConversionService.java#L50-L59
6,844
phax/ph-poi
src/main/java/com/helger/poi/POISLF4JLogger.java
POISLF4JLogger.check
@Override 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 (); }
java
@Override 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 (); }
[ "@", "Override", "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 @param nLevel One of DEBUG, INFO, WARN, ERROR, FATAL @return <code>true</code> if the logger can handle the specified error level
[ "Check", "if", "a", "logger", "is", "enabled", "to", "log", "at", "the", "specified", "level" ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/POISLF4JLogger.java#L131-L143
6,845
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.createNewSheet
@Nonnull public Sheet createNewSheet (@Nullable 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; }
java
@Nonnull public Sheet createNewSheet (@Nullable 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; }
[ "@", "Nonnull", "public", "Sheet", "createNewSheet", "(", "@", "Nullable", "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 @param sName The name to be used. May be <code>null</code>. @return The created workbook sheet
[ "Create", "a", "new", "sheet", "with", "an", "optional", "name" ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L137-L147
6,846
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.addCellStyle
public void addCellStyle (@Nonnull 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); }
java
public void addCellStyle (@Nonnull 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); }
[ "public", "void", "addCellStyle", "(", "@", "Nonnull", "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 @param aExcelStyle The style to be set.
[ "Set", "the", "cell", "style", "of", "the", "last", "added", "cell" ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L475-L490
6,847
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.autoSizeAllColumns
public void autoSizeAllColumns () { // auto-adjust all columns (except description and image description) for (short nCol = 0; nCol < m_nMaxCellIndex; ++nCol) try { m_aLastSheet.autoSizeColumn (nCol); } catch (final IllegalArgumentException ex) { // Happens if a column is too large LOGGER.warn ("Failed to resize column " + nCol + ": column too wide!"); } }
java
public void autoSizeAllColumns () { // auto-adjust all columns (except description and image description) for (short nCol = 0; nCol < m_nMaxCellIndex; ++nCol) try { m_aLastSheet.autoSizeColumn (nCol); } catch (final IllegalArgumentException ex) { // Happens if a column is too large LOGGER.warn ("Failed to resize column " + nCol + ": column too wide!"); } }
[ "public", "void", "autoSizeAllColumns", "(", ")", "{", "// auto-adjust all columns (except description and image description)", "for", "(", "short", "nCol", "=", "0", ";", "nCol", "<", "m_nMaxCellIndex", ";", "++", "nCol", ")", "try", "{", "m_aLastSheet", ".", "autoSizeColumn", "(", "nCol", ")", ";", "}", "catch", "(", "final", "IllegalArgumentException", "ex", ")", "{", "// Happens if a column is too large", "LOGGER", ".", "warn", "(", "\"Failed to resize column \"", "+", "nCol", "+", "\": column too wide!\"", ")", ";", "}", "}" ]
Auto size all columns to be matching width in the current sheet
[ "Auto", "size", "all", "columns", "to", "be", "matching", "width", "in", "the", "current", "sheet" ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L525-L538
6,848
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.writeTo
@Nonnull public ESuccess writeTo (@Nonnull final File aFile) { return writeTo (FileHelper.getOutputStream (aFile)); }
java
@Nonnull public ESuccess writeTo (@Nonnull final File aFile) { return writeTo (FileHelper.getOutputStream (aFile)); }
[ "@", "Nonnull", "public", "ESuccess", "writeTo", "(", "@", "Nonnull", "final", "File", "aFile", ")", "{", "return", "writeTo", "(", "FileHelper", ".", "getOutputStream", "(", "aFile", ")", ")", ";", "}" ]
Write the current workbook to a file @param aFile The file to write to. May not be <code>null</code>. @return {@link ESuccess}
[ "Write", "the", "current", "workbook", "to", "a", "file" ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L568-L572
6,849
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.writeTo
@Nonnull public ESuccess writeTo (@Nonnull final IWritableResource aRes) { return writeTo (aRes.getOutputStream (EAppend.TRUNCATE)); }
java
@Nonnull public ESuccess writeTo (@Nonnull final IWritableResource aRes) { return writeTo (aRes.getOutputStream (EAppend.TRUNCATE)); }
[ "@", "Nonnull", "public", "ESuccess", "writeTo", "(", "@", "Nonnull", "final", "IWritableResource", "aRes", ")", "{", "return", "writeTo", "(", "aRes", ".", "getOutputStream", "(", "EAppend", ".", "TRUNCATE", ")", ")", ";", "}" ]
Write the current workbook to a writable resource. @param aRes The resource to write to. May not be <code>null</code>. @return {@link ESuccess}
[ "Write", "the", "current", "workbook", "to", "a", "writable", "resource", "." ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L581-L585
6,850
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.writeTo
@Nonnull public ESuccess writeTo (@Nonnull @WillClose 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); } }
java
@Nonnull public ESuccess writeTo (@Nonnull @WillClose 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); } }
[ "@", "Nonnull", "public", "ESuccess", "writeTo", "(", "@", "Nonnull", "@", "WillClose", "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. @param aOS The output stream to write to. May not be <code>null</code>. Is automatically closed independent of the success state. @return {@link ESuccess}
[ "Write", "the", "current", "workbook", "to", "an", "output", "stream", "." ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L595-L618
6,851
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.getAsByteArray
@Nullable public byte [] getAsByteArray () { try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ()) { if (writeTo (aBAOS).isFailure ()) return null; return aBAOS.getBufferOrCopy (); } }
java
@Nullable public byte [] getAsByteArray () { try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ()) { if (writeTo (aBAOS).isFailure ()) return null; return aBAOS.getBufferOrCopy (); } }
[ "@", "Nullable", "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. @return <code>null</code> if writing failed. See log files for details.
[ "Helper", "method", "to", "get", "the", "whole", "workbook", "as", "a", "single", "byte", "array", "." ]
908c5dd434739e6989cf88e55bea48f2f18c6996
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L625-L634
6,852
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.getHttpClient
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() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // enable preemptive authentication AuthState authState = (AuthState)context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); authState.update(new BasicScheme(), credentials); } }) .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // keep reusing connections to a minimum - may conflict when instance is restarting and responds in unexpected manner return 1; } }); // timeout settings httpClientBuilder.setDefaultRequestConfig(HttpClientUtil.buildRequestConfig(props)); // relaxed SSL check if (props.isRelaxedSSLCheck()) { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(sslsf); } // proxy support 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); } }
java
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() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // enable preemptive authentication AuthState authState = (AuthState)context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); authState.update(new BasicScheme(), credentials); } }) .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // keep reusing connections to a minimum - may conflict when instance is restarting and responds in unexpected manner return 1; } }); // timeout settings httpClientBuilder.setDefaultRequestConfig(HttpClientUtil.buildRequestConfig(props)); // relaxed SSL check if (props.isRelaxedSSLCheck()) { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(sslsf); } // proxy support 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); } }
[ "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", "(", ")", "{", "@", "Override", "public", "void", "process", "(", "HttpRequest", "request", ",", "HttpContext", "context", ")", "throws", "HttpException", ",", "IOException", "{", "// enable preemptive authentication", "AuthState", "authState", "=", "(", "AuthState", ")", "context", ".", "getAttribute", "(", "HttpClientContext", ".", "TARGET_AUTH_STATE", ")", ";", "authState", ".", "update", "(", "new", "BasicScheme", "(", ")", ",", "credentials", ")", ";", "}", "}", ")", ".", "setKeepAliveStrategy", "(", "new", "ConnectionKeepAliveStrategy", "(", ")", "{", "@", "Override", "public", "long", "getKeepAliveDuration", "(", "HttpResponse", "response", ",", "HttpContext", "context", ")", "{", "// keep reusing connections to a minimum - may conflict when instance is restarting and responds in unexpected manner", "return", "1", ";", "}", "}", ")", ";", "// timeout settings", "httpClientBuilder", ".", "setDefaultRequestConfig", "(", "HttpClientUtil", ".", "buildRequestConfig", "(", "props", ")", ")", ";", "// relaxed SSL check", "if", "(", "props", ".", "isRelaxedSSLCheck", "(", ")", ")", "{", "SSLContext", "sslContext", "=", "new", "SSLContextBuilder", "(", ")", ".", "loadTrustMaterial", "(", "null", ",", "new", "TrustSelfSignedStrategy", "(", ")", ")", ".", "build", "(", ")", ";", "SSLConnectionSocketFactory", "sslsf", "=", "new", "SSLConnectionSocketFactory", "(", "sslContext", ",", "new", "NoopHostnameVerifier", "(", ")", ")", ";", "httpClientBuilder", ".", "setSSLSocketFactory", "(", "sslsf", ")", ";", "}", "// proxy support", "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 @return Http client
[ "Set", "up", "http", "client", "with", "credentials" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L97-L153
6,853
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.getProxyForUrl
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; }
java
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; }
[ "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 @param requestUrl Request URL @return Proxy or null if none matching found
[ "Get", "proxy", "for", "given", "URL" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L160-L172
6,854
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.executeHttpCallWithRetry
private <T> T executeHttpCallWithRetry(HttpCall<T> call, int runCount) { try { return call.execute(); } catch (PackageManagerHttpActionException ex) { // retry again if configured so... 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) { // ignore } } return executeHttpCallWithRetry(call, runCount + 1); } else { throw ex; } } }
java
private <T> T executeHttpCallWithRetry(HttpCall<T> call, int runCount) { try { return call.execute(); } catch (PackageManagerHttpActionException ex) { // retry again if configured so... 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) { // ignore } } return executeHttpCallWithRetry(call, runCount + 1); } else { throw ex; } } }
[ "private", "<", "T", ">", "T", "executeHttpCallWithRetry", "(", "HttpCall", "<", "T", ">", "call", ",", "int", "runCount", ")", "{", "try", "{", "return", "call", ".", "execute", "(", ")", ";", "}", "catch", "(", "PackageManagerHttpActionException", "ex", ")", "{", "// retry again if configured so...", "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", ")", "{", "// ignore", "}", "}", "return", "executeHttpCallWithRetry", "(", "call", ",", "runCount", "+", "1", ")", ";", "}", "else", "{", "throw", "ex", ";", "}", "}", "}" ]
Execute HTTP call with automatic retry as configured for the MOJO. @param call HTTP call @param runCount Number of runs this call was already executed
[ "Execute", "HTTP", "call", "with", "automatic", "retry", "as", "configured", "for", "the", "MOJO", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L180-L212
6,855
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.executePackageManagerMethodJson
public JSONObject executePackageManagerMethodJson(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerJsonCall call = new PackageManagerJsonCall(httpClient, method, log); return executeHttpCallWithRetry(call, 0); }
java
public JSONObject executePackageManagerMethodJson(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerJsonCall call = new PackageManagerJsonCall(httpClient, method, log); return executeHttpCallWithRetry(call, 0); }
[ "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. @param httpClient Http client @param method Get or Post method @return JSON object
[ "Execute", "CRX", "HTTP", "Package", "manager", "method", "and", "parse", "JSON", "response", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L220-L223
6,856
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.executePackageManagerMethodXml
public Document executePackageManagerMethodXml(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerXmlCall call = new PackageManagerXmlCall(httpClient, method, log); return executeHttpCallWithRetry(call, 0); }
java
public Document executePackageManagerMethodXml(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerXmlCall call = new PackageManagerXmlCall(httpClient, method, log); return executeHttpCallWithRetry(call, 0); }
[ "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. @param httpClient Http client @param method Get or Post method @return XML document
[ "Execute", "CRX", "HTTP", "Package", "manager", "method", "and", "parse", "XML", "response", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L231-L234
6,857
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.executePackageManagerMethodHtml
public String executePackageManagerMethodHtml(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerHtmlCall call = new PackageManagerHtmlCall(httpClient, method, log); String message = executeHttpCallWithRetry(call, 0); return message; }
java
public String executePackageManagerMethodHtml(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerHtmlCall call = new PackageManagerHtmlCall(httpClient, method, log); String message = executeHttpCallWithRetry(call, 0); return message; }
[ "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. @param httpClient Http client @param method Get or Post method @return Response from HTML server
[ "Execute", "CRX", "HTTP", "Package", "manager", "method", "and", "get", "HTML", "response", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L242-L246
6,858
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.executePackageManagerMethodHtmlOutputResponse
public void executePackageManagerMethodHtmlOutputResponse(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerHtmlMessageCall call = new PackageManagerHtmlMessageCall(httpClient, method, log); executeHttpCallWithRetry(call, 0); }
java
public void executePackageManagerMethodHtmlOutputResponse(CloseableHttpClient httpClient, HttpRequestBase method) { PackageManagerHtmlMessageCall call = new PackageManagerHtmlMessageCall(httpClient, method, log); executeHttpCallWithRetry(call, 0); }
[ "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. @param httpClient Http client @param method Get or Post method
[ "Execute", "CRX", "HTTP", "Package", "manager", "method", "and", "output", "HTML", "response", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L253-L256
6,859
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java
PackageManagerHelper.waitForBundlesActivation
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; // check if bundles are still stopping/staring 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; } // check if any of the blacklisted bundles is still present 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; } } } // instance is ready if (instanceReady) { break; } } }
java
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; // check if bundles are still stopping/staring 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; } // check if any of the blacklisted bundles is still present 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; } } } // instance is ready if (instanceReady) { break; } } }
[ "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", ";", "// check if bundles are still stopping/staring", "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", ";", "}", "// check if any of the blacklisted bundles is still present", "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", ";", "}", "}", "}", "// instance is ready", "if", "(", "instanceReady", ")", "{", "break", ";", "}", "}", "}" ]
Wait for bundles to become active. @param httpClient Http client
[ "Wait", "for", "bundles", "to", "become", "active", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHelper.java#L273-L318
6,860
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/AbstractCompleter.java
AbstractCompleter.getRowFirstNonWhite
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; }
java
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; }
[ "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 @param doc @param offset @return the offset of the first non-white @throws BadLocationException
[ "iterates", "through", "the", "text", "to", "find", "first", "nonwhite" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/AbstractCompleter.java#L103-L119
6,861
wcm-io/wcm-io-tooling
maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/DownloadMojo.java
DownloadMojo.execute
@Override 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); } }
java
@Override 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); } }
[ "@", "Override", "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
[ "Downloads", "the", "files" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/DownloadMojo.java#L101-L113
6,862
wcm-io/wcm-io-tooling
maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/DownloadMojo.java
DownloadMojo.unpackFile
private void unpackFile(File file) throws MojoExecutionException { // initialize unpacker to validate patterns 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); // validate output directory if (this.unpackDirectory == null) { throw new MojoExecutionException("No unpack directory specified."); } if (!this.unpackDirectory.exists()) { this.unpackDirectory.mkdirs(); } // remove existing content 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()); } } } } // unpack file unpacker.unpack(file, this.unpackDirectory); getLog().info("Package unpacked to " + this.unpackDirectory.getAbsolutePath()); }
java
private void unpackFile(File file) throws MojoExecutionException { // initialize unpacker to validate patterns 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); // validate output directory if (this.unpackDirectory == null) { throw new MojoExecutionException("No unpack directory specified."); } if (!this.unpackDirectory.exists()) { this.unpackDirectory.mkdirs(); } // remove existing content 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()); } } } } // unpack file unpacker.unpack(file, this.unpackDirectory); getLog().info("Package unpacked to " + this.unpackDirectory.getAbsolutePath()); }
[ "private", "void", "unpackFile", "(", "File", "file", ")", "throws", "MojoExecutionException", "{", "// initialize unpacker to validate patterns", "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", ")", ";", "// validate output directory", "if", "(", "this", ".", "unpackDirectory", "==", "null", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"No unpack directory specified.\"", ")", ";", "}", "if", "(", "!", "this", ".", "unpackDirectory", ".", "exists", "(", ")", ")", "{", "this", ".", "unpackDirectory", ".", "mkdirs", "(", ")", ";", "}", "// remove existing content", "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", "(", ")", ")", ";", "}", "}", "}", "}", "// unpack file", "unpacker", ".", "unpack", "(", "file", ",", "this", ".", "unpackDirectory", ")", ";", "getLog", "(", ")", ".", "info", "(", "\"Package unpacked to \"", "+", "this", ".", "unpackDirectory", ".", "getAbsolutePath", "(", ")", ")", ";", "}" ]
Unpack content package
[ "Unpack", "content", "package" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/DownloadMojo.java#L118-L153
6,863
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/BasicCompletionItem.java
BasicCompletionItem.substituteText
protected void substituteText(JTextComponent component, String toAdd) { String text = completionText; if (toAdd != null) { text += toAdd; } try { StyledDocument doc = (StyledDocument)component.getDocument(); //Here we remove the characters starting at the start offset //and ending at the point where the caret is currently found: doc.remove(dotOffset, caretOffset - dotOffset); doc.insertString(dotOffset, text, null); Completion.get().hideAll(); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
java
protected void substituteText(JTextComponent component, String toAdd) { String text = completionText; if (toAdd != null) { text += toAdd; } try { StyledDocument doc = (StyledDocument)component.getDocument(); //Here we remove the characters starting at the start offset //and ending at the point where the caret is currently found: doc.remove(dotOffset, caretOffset - dotOffset); doc.insertString(dotOffset, text, null); Completion.get().hideAll(); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
[ "protected", "void", "substituteText", "(", "JTextComponent", "component", ",", "String", "toAdd", ")", "{", "String", "text", "=", "completionText", ";", "if", "(", "toAdd", "!=", "null", ")", "{", "text", "+=", "toAdd", ";", "}", "try", "{", "StyledDocument", "doc", "=", "(", "StyledDocument", ")", "component", ".", "getDocument", "(", ")", ";", "//Here we remove the characters starting at the start offset", "//and ending at the point where the caret is currently found:", "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. @param component @param toAdd optional text which is appended to the completion text
[ "Substitutes", "the", "text", "inside", "the", "component", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/BasicCompletionItem.java#L88-L104
6,864
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/PackageMetadata.java
PackageMetadata.validate
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."); } }
java
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."); } }
[ "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.
[ "Validates", "that", "the", "mandatory", "properties", "are", "set", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/PackageMetadata.java#L136-L146
6,865
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.addContent
public void addContent(String path, ContentElement content) throws IOException { String fullPath = buildJcrPathForZip(path) + "/" + DOT_CONTENT_XML; Document doc = xmlContentBuilder.buildContent(content); writeXmlDocument(fullPath, doc); }
java
public void addContent(String path, ContentElement content) throws IOException { String fullPath = buildJcrPathForZip(path) + "/" + DOT_CONTENT_XML; Document doc = xmlContentBuilder.buildContent(content); writeXmlDocument(fullPath, doc); }
[ "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. @param path Full content path of content root node. @param content Hierarchy of content elements. @throws IOException I/O exception
[ "Add", "some", "JCR", "content", "structure", "directly", "to", "the", "package", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L151-L155
6,866
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.buildPackageMetadata
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())); // package thumbnail byte[] thumbnailImage = metadata.getThumbnailImage(); if (thumbnailImage != null) { zip.putNextEntry(new ZipEntry(META_DIR + "/definition/thumbnail.png")); try { zip.write(thumbnailImage); } finally { zip.closeEntry(); } } }
java
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())); // package thumbnail byte[] thumbnailImage = metadata.getThumbnailImage(); if (thumbnailImage != null) { zip.putNextEntry(new ZipEntry(META_DIR + "/definition/thumbnail.png")); try { zip.write(thumbnailImage); } finally { zip.closeEntry(); } } }
[ "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", "(", ")", ")", ")", ";", "// package thumbnail", "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. @throws IOException I/O exception
[ "Build", "all", "package", "metadata", "files", "based", "on", "templates", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L276-L295
6,867
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.buildTemplatedMetadataFile
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(); } } }
java
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(); } } }
[ "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. @param path Path @throws IOException I/O exception
[ "Read", "template", "file", "from", "classpath", "replace", "variables", "and", "store", "it", "in", "the", "zip", "stream", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L302-L317
6,868
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.buildPropertiesFile
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(); } }
java
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(); } }
[ "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. @param path Path @throws IOException I/O exception
[ "Build", "java", "Properties", "XML", "file", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L324-L343
6,869
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.writeXmlDocument
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(); } }
java
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(); } }
[ "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. @param path Content path @param doc XML content @throws IOException I/O exception
[ "Writes", "an", "XML", "document", "as", "binary", "file", "entry", "to", "the", "ZIP", "output", "stream", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L351-L364
6,870
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.writeBinaryFile
private void writeBinaryFile(String path, InputStream is) throws IOException { zip.putNextEntry(new ZipEntry(path)); try { IOUtils.copy(is, zip); } finally { zip.closeEntry(); } }
java
private void writeBinaryFile(String path, InputStream is) throws IOException { zip.putNextEntry(new ZipEntry(path)); try { IOUtils.copy(is, zip); } finally { zip.closeEntry(); } }
[ "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. @param path Content path @param is Input stream with binary data @throws IOException I/O exception
[ "Writes", "an", "binary", "file", "entry", "to", "the", "ZIP", "output", "stream", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L372-L380
6,871
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupCompleter.java
MemberLookupCompleter.resolveClass
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; }
java
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; }
[ "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 @param variableName @param text @param document @return Set of methods and fields, never null
[ "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" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupCompleter.java#L117-L139
6,872
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java
MemberLookupResolver.performMemberLookup
public Set<MemberLookupResult> performMemberLookup(String variable) { // if there is more than one "." we need to do some magic and resolve the definition fragmented if (variable.contains(".")) { return performNestedLookup(variable); } Set<MemberLookupResult> ret = new LinkedHashSet<>(); // check, if the current variable resolves to a data-sly-use command ParsedStatement statement = getParsedStatement(variable); if (statement == null) { return ret; } if (StringUtils.equals(statement.getCommand(), DataSlyCommands.DATA_SLY_USE.getCommand())) { // this ends the search and we can perform the actual lookup 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; }
java
public Set<MemberLookupResult> performMemberLookup(String variable) { // if there is more than one "." we need to do some magic and resolve the definition fragmented if (variable.contains(".")) { return performNestedLookup(variable); } Set<MemberLookupResult> ret = new LinkedHashSet<>(); // check, if the current variable resolves to a data-sly-use command ParsedStatement statement = getParsedStatement(variable); if (statement == null) { return ret; } if (StringUtils.equals(statement.getCommand(), DataSlyCommands.DATA_SLY_USE.getCommand())) { // this ends the search and we can perform the actual lookup 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; }
[ "public", "Set", "<", "MemberLookupResult", ">", "performMemberLookup", "(", "String", "variable", ")", "{", "// if there is more than one \".\" we need to do some magic and resolve the definition fragmented", "if", "(", "variable", ".", "contains", "(", "\".\"", ")", ")", "{", "return", "performNestedLookup", "(", "variable", ")", ";", "}", "Set", "<", "MemberLookupResult", ">", "ret", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "// check, if the current variable resolves to a data-sly-use command", "ParsedStatement", "statement", "=", "getParsedStatement", "(", "variable", ")", ";", "if", "(", "statement", "==", "null", ")", "{", "return", "ret", ";", "}", "if", "(", "StringUtils", ".", "equals", "(", "statement", ".", "getCommand", "(", ")", ",", "DataSlyCommands", ".", "DATA_SLY_USE", ".", "getCommand", "(", ")", ")", ")", "{", "// this ends the search and we can perform the actual lookup", "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 @return set of all elements which match the lookup
[ "The", "actual", "lookup" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java#L76-L101
6,873
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java
MemberLookupResolver.performNestedLookup
private Set<MemberLookupResult> performNestedLookup(String variable) { Set<MemberLookupResult> ret = new LinkedHashSet<>(); // start with the first part 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])) { // we found a method which has the correct name, now we can resolv this ret.addAll(getResultsForClass(result.getReturnType(), variable)); } } } return ret; }
java
private Set<MemberLookupResult> performNestedLookup(String variable) { Set<MemberLookupResult> ret = new LinkedHashSet<>(); // start with the first part 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])) { // we found a method which has the correct name, now we can resolv this ret.addAll(getResultsForClass(result.getReturnType(), variable)); } } } return ret; }
[ "private", "Set", "<", "MemberLookupResult", ">", "performNestedLookup", "(", "String", "variable", ")", "{", "Set", "<", "MemberLookupResult", ">", "ret", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "// start with the first part", "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", "]", ")", ")", "{", "// we found a method which has the correct name, now we can resolv this", "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 @param variable e.g. foo.bar @return set with matching results
[ "performs", "a", "nested", "lookup", ".", "E", ".", "g", "for", "foo", ".", "bar", "it", "will", "resolve", "the", "type", "of", "bar", "and", "then", "get", "it", "s", "methods" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java#L109-L131
6,874
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java
MemberLookupResolver.getMethodsFromClassLoader
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; }
java
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; }
[ "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 @param clazzname @param variable @return set with all methods, can be empty
[ "Fallback", "used", "to", "load", "the", "methods", "from", "classloader" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/MemberLookupResolver.java#L188-L205
6,875
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/PackageInstaller.java
PackageInstaller.installFile
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()) { // before install: if bundles are still stopping/starting, wait for completion 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); } }
java
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()) { // before install: if bundles are still stopping/starting, wait for completion 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); } }
[ "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", "(", ")", ")", "{", "// before install: if bundles are still stopping/starting, wait for completion", "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. @param packageFile AEM content package
[ "Deploy", "file", "via", "package", "manager", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/PackageInstaller.java#L66-L92
6,876
wcm-io/wcm-io-tooling
maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/pack/Filters.java
Filters.merge
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); } } }
java
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); } } }
[ "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. @param workspaceFilter Filter
[ "Merge", "configured", "filter", "paths", "with", "existing", "workspace", "filter", "definition", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/wcmio-content-package-maven-plugin/src/main/java/io/wcm/maven/plugins/contentpackage/pack/Filters.java#L47-L60
6,877
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java
VendorInstallerFactory.identify
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; }
java
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; }
[ "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 @param url Base URL to check @return Service Enum found or unsupported
[ "Identifies", "the", "Service", "Vendor", "based", "on", "the", "given", "URL" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java#L73-L86
6,878
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java
VendorInstallerFactory.getBaseUrl
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; }
java
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; }
[ "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 @param url Service URL @param logger Logger @return Base URL if service vendor was found otherwise the given URL
[ "Returns", "the", "Base", "Url", "of", "a", "given", "URL", "with", "based", "on", "its", "Vendors", "from", "the", "URL" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java#L95-L108
6,879
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java
VendorInstallerFactory.getPackageInstaller
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; }
java
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; }
[ "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 @param url Base URL of the service @return Installer if URL is supported otherwise null
[ "Provides", "the", "Installer", "of", "the", "Service", "Vendor" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/VendorInstallerFactory.java#L115-L128
6,880
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/SlingI18nMap.java
SlingI18nMap.getI18nXmlString
public String getI18nXmlString() { Format format = Format.getPrettyFormat(); XMLOutputter outputter = new XMLOutputter(format); return outputter.outputString(buildI18nXml()); }
java
public String getI18nXmlString() { Format format = Format.getPrettyFormat(); XMLOutputter outputter = new XMLOutputter(format); return outputter.outputString(buildI18nXml()); }
[ "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. @return XML
[ "Build", "i18n", "resource", "XML", "in", "Sling", "i18n", "Message", "format", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/SlingI18nMap.java#L136-L140
6,881
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/SlingI18nMap.java
SlingI18nMap.getI18nPropertiesString
public String getI18nPropertiesString() throws IOException { // Load all properties Properties i18nProps = new Properties(); // add entries 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); // Property files are always ISO 8859 encoded return outStream.toString(CharEncoding.ISO_8859_1); } }
java
public String getI18nPropertiesString() throws IOException { // Load all properties Properties i18nProps = new Properties(); // add entries 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); // Property files are always ISO 8859 encoded return outStream.toString(CharEncoding.ISO_8859_1); } }
[ "public", "String", "getI18nPropertiesString", "(", ")", "throws", "IOException", "{", "// Load all properties", "Properties", "i18nProps", "=", "new", "Properties", "(", ")", ";", "// add entries", "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", ")", ";", "// Property files are always ISO 8859 encoded", "return", "outStream", ".", "toString", "(", "CharEncoding", ".", "ISO_8859_1", ")", ";", "}", "}" ]
Build i18n resource PROPERTIES. @return JSON @throws IOException
[ "Build", "i18n", "resource", "PROPERTIES", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/SlingI18nMap.java#L229-L245
6,882
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java
XmlContentBuilder.buildContent
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; }
java
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; }
[ "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. @param content Content with properties and nested nodes @return JCR XML
[ "Build", "XML", "for", "any", "JCR", "content", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java#L119-L128
6,883
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java
XmlContentBuilder.buildFilter
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; }
java
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; }
[ "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. @param filters Filters @return Filter XML
[ "Build", "filter", "XML", "for", "package", "metadata", "files", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java#L156-L176
6,884
wcm-io/wcm-io-tooling
maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/Rules.java
Rules.getRule
public Rule getRule(Resource resource) { for (Rule rule : rules) { if (rule.matches(resource)) { return rule; } } return null; }
java
public Rule getRule(Resource resource) { for (Rule rule : rules) { if (rule.matches(resource)) { return rule; } } return null; }
[ "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. @param resource GraniteUIR resource @return matching rule or null
[ "Get", "rule", "matching", "for", "the", "given", "GraniteUI", "resource", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/Rules.java#L47-L54
6,885
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/download/PackageDownloader.java
PackageDownloader.downloadFile
public File downloadFile(File file, String ouputFilePath) { try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) { log.info("Download " + file.getName() + " from " + props.getPackageManagerUrl()); // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!) 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); // package already exists - get path from error message and continue 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..."); // 2nd: build package HttpPost buildMethod = new HttpPost(props.getPackageManagerUrl() + "/console.html" + path + "?cmd=build"); pkgmgr.executePackageManagerMethodHtmlOutputResponse(httpClient, buildMethod); // 3rd: download package String baseUrl = VendorInstallerFactory.getBaseUrl(props.getPackageManagerUrl(), log); HttpGet downloadMethod = new HttpGet(baseUrl + path); // execute download CloseableHttpResponse response = httpClient.execute(downloadMethod); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // get response stream InputStream responseStream = response.getEntity().getContent(); // delete existing file File outputFileObject = new File(ouputFilePath); if (outputFileObject.exists()) { outputFileObject.delete(); } // write response file 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) { // ignore } } } } catch (FileNotFoundException ex) { throw new PackageManagerException("File not found: " + file.getAbsolutePath(), ex); } catch (IOException ex) { throw new PackageManagerException("Download operation failed.", ex); } }
java
public File downloadFile(File file, String ouputFilePath) { try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) { log.info("Download " + file.getName() + " from " + props.getPackageManagerUrl()); // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!) 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); // package already exists - get path from error message and continue 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..."); // 2nd: build package HttpPost buildMethod = new HttpPost(props.getPackageManagerUrl() + "/console.html" + path + "?cmd=build"); pkgmgr.executePackageManagerMethodHtmlOutputResponse(httpClient, buildMethod); // 3rd: download package String baseUrl = VendorInstallerFactory.getBaseUrl(props.getPackageManagerUrl(), log); HttpGet downloadMethod = new HttpGet(baseUrl + path); // execute download CloseableHttpResponse response = httpClient.execute(downloadMethod); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // get response stream InputStream responseStream = response.getEntity().getContent(); // delete existing file File outputFileObject = new File(ouputFilePath); if (outputFileObject.exists()) { outputFileObject.delete(); } // write response file 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) { // ignore } } } } catch (FileNotFoundException ex) { throw new PackageManagerException("File not found: " + file.getAbsolutePath(), ex); } catch (IOException ex) { throw new PackageManagerException("Download operation failed.", ex); } }
[ "public", "File", "downloadFile", "(", "File", "file", ",", "String", "ouputFilePath", ")", "{", "try", "(", "CloseableHttpClient", "httpClient", "=", "pkgmgr", ".", "getHttpClient", "(", ")", ")", "{", "log", ".", "info", "(", "\"Download \"", "+", "file", ".", "getName", "(", ")", "+", "\" from \"", "+", "props", ".", "getPackageManagerUrl", "(", ")", ")", ";", "// 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)", "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", ")", ";", "// package already exists - get path from error message and continue", "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...\"", ")", ";", "// 2nd: build package", "HttpPost", "buildMethod", "=", "new", "HttpPost", "(", "props", ".", "getPackageManagerUrl", "(", ")", "+", "\"/console.html\"", "+", "path", "+", "\"?cmd=build\"", ")", ";", "pkgmgr", ".", "executePackageManagerMethodHtmlOutputResponse", "(", "httpClient", ",", "buildMethod", ")", ";", "// 3rd: download package", "String", "baseUrl", "=", "VendorInstallerFactory", ".", "getBaseUrl", "(", "props", ".", "getPackageManagerUrl", "(", ")", ",", "log", ")", ";", "HttpGet", "downloadMethod", "=", "new", "HttpGet", "(", "baseUrl", "+", "path", ")", ";", "// execute download", "CloseableHttpResponse", "response", "=", "httpClient", ".", "execute", "(", "downloadMethod", ")", ";", "try", "{", "if", "(", "response", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", "==", "HttpStatus", ".", "SC_OK", ")", "{", "// get response stream", "InputStream", "responseStream", "=", "response", ".", "getEntity", "(", ")", ".", "getContent", "(", ")", ";", "// delete existing file", "File", "outputFileObject", "=", "new", "File", "(", "ouputFilePath", ")", ";", "if", "(", "outputFileObject", ".", "exists", "(", ")", ")", "{", "outputFileObject", ".", "delete", "(", ")", ";", "}", "// write response file", "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", ")", "{", "// ignore", "}", "}", "}", "}", "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. @param file Local version of package that should be downloaded. @param ouputFilePath Path to download package from AEM instance to. @return Downloaded file
[ "Download", "content", "package", "from", "CRX", "instance", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/download/PackageDownloader.java#L72-L154
6,886
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/unpack/ContentUnpacker.java
ContentUnpacker.sortWeakReferenceValues
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); } }
java
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); } }
[ "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. @param name Property name @param value Property value @return Property value with sorted references
[ "Sort", "weak", "reference", "values", "alphabetically", "to", "ensure", "consistent", "ordering", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/unpack/ContentUnpacker.java#L369-L386
6,887
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/httpaction/BundleStatus.java
BundleStatus.getMatchingBundle
public String getMatchingBundle(Pattern symbolicNamePattern) { for (String bundleSymbolicName : bundleSymbolicNames) { if (symbolicNamePattern.matcher(bundleSymbolicName).matches()) { return bundleSymbolicName; } } return null; }
java
public String getMatchingBundle(Pattern symbolicNamePattern) { for (String bundleSymbolicName : bundleSymbolicNames) { if (symbolicNamePattern.matcher(bundleSymbolicName).matches()) { return bundleSymbolicName; } } return null; }
[ "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. @param symbolicNamePattern Bundle symbolic name pattern @return Bundle name if a bundle was found, null otherwise
[ "Checks", "if", "a", "bundle", "with", "the", "given", "pattern", "exists", "in", "the", "bundle", "list", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/httpaction/BundleStatus.java#L114-L121
6,888
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/AbstractSourceResolver.java
AbstractSourceResolver.getJavaSourceForClass
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; }
java
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; }
[ "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 @param clazzname @return null or the fileobject
[ "Resolves", "the", "clazzname", "to", "a", "fileobject", "of", "the", "java", "-", "file" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/AbstractSourceResolver.java#L57-L72
6,889
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/AbstractSourceResolver.java
AbstractSourceResolver.getMembersFromJavaSource
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>() { @Override 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; }
java
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>() { @Override 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; }
[ "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", ">", "(", ")", "{", "@", "Override", "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. @param clazzname @param acceptor @return set with methods or empty set if class could not be loaded
[ "tries", "to", "load", "all", "members", "for", "the", "given", "clazzname", "from", "javasource", "files", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/AbstractSourceResolver.java#L81-L108
6,890
wcm-io/wcm-io-tooling
maven/plugins/nodejs-maven-plugin/src/main/java/io/wcm/maven/plugins/nodejs/mojo/AbstractNodeJsMojo.java
AbstractNodeJsMojo.run
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."); } // validate nodejs version 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); } } }
java
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."); } // validate nodejs version 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); } } }
[ "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.\"", ")", ";", "}", "// validate nodejs version", "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 @throws MojoExecutionException Mojo execution exception
[ "Installs", "node", "js", "if", "necessary", "and", "performs", "defined", "tasks" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/nodejs-maven-plugin/src/main/java/io/wcm/maven/plugins/nodejs/mojo/AbstractNodeJsMojo.java#L145-L168
6,891
wcm-io/wcm-io-tooling
maven/plugins/nodejs-maven-plugin/src/main/java/io/wcm/maven/plugins/nodejs/mojo/AbstractNodeJsMojo.java
AbstractNodeJsMojo.updateNPMExecutable
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); }
java
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); }
[ "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. @param information @throws MojoExecutionException
[ "Makes", "sure", "the", "specified", "npm", "version", "is", "installed", "in", "the", "base", "directory", "regardless", "in", "which", "environment", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/nodejs-maven-plugin/src/main/java/io/wcm/maven/plugins/nodejs/mojo/AbstractNodeJsMojo.java#L231-L240
6,892
wcm-io/wcm-io-tooling
maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java
DialogConverter.mapProperty
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()) { // this is a mapped property, we will delete it if the mapped destination // property doesn't exist deleteProperty = true; String path = matcher.group(2); // unwrap quoted property paths path = StringUtils.removeStart(StringUtils.stripEnd(path, "\'"), "\'"); if (root.has(cleanup(path))) { // replace property by mapped value in the original tree Object originalValue = root.get(cleanup(path)); node.put(cleanup(key), originalValue); // negate boolean properties if negation character has been set String negate = matcher.group(1); if ("!".equals(negate) && (originalValue instanceof Boolean)) { node.put(cleanup(key), !((Boolean)originalValue)); } // the mapping was successful deleteProperty = false; break; } else { String defaultValue = matcher.group(4); if (defaultValue != null) { node.put(cleanup(key), defaultValue); deleteProperty = false; break; } } } } if (deleteProperty) { // mapped destination does not exist, we don't include the property in replacement tree node.remove(key); return false; } return true; }
java
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()) { // this is a mapped property, we will delete it if the mapped destination // property doesn't exist deleteProperty = true; String path = matcher.group(2); // unwrap quoted property paths path = StringUtils.removeStart(StringUtils.stripEnd(path, "\'"), "\'"); if (root.has(cleanup(path))) { // replace property by mapped value in the original tree Object originalValue = root.get(cleanup(path)); node.put(cleanup(key), originalValue); // negate boolean properties if negation character has been set String negate = matcher.group(1); if ("!".equals(negate) && (originalValue instanceof Boolean)) { node.put(cleanup(key), !((Boolean)originalValue)); } // the mapping was successful deleteProperty = false; break; } else { String defaultValue = matcher.group(4); if (defaultValue != null) { node.put(cleanup(key), defaultValue); deleteProperty = false; break; } } } } if (deleteProperty) { // mapped destination does not exist, we don't include the property in replacement tree node.remove(key); return false; } return true; }
[ "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", "(", ")", ")", "{", "// this is a mapped property, we will delete it if the mapped destination", "// property doesn't exist", "deleteProperty", "=", "true", ";", "String", "path", "=", "matcher", ".", "group", "(", "2", ")", ";", "// unwrap quoted property paths", "path", "=", "StringUtils", ".", "removeStart", "(", "StringUtils", ".", "stripEnd", "(", "path", ",", "\"\\'\"", ")", ",", "\"\\'\"", ")", ";", "if", "(", "root", ".", "has", "(", "cleanup", "(", "path", ")", ")", ")", "{", "// replace property by mapped value in the original tree", "Object", "originalValue", "=", "root", ".", "get", "(", "cleanup", "(", "path", ")", ")", ";", "node", ".", "put", "(", "cleanup", "(", "key", ")", ",", "originalValue", ")", ";", "// negate boolean properties if negation character has been set", "String", "negate", "=", "matcher", ".", "group", "(", "1", ")", ";", "if", "(", "\"!\"", ".", "equals", "(", "negate", ")", "&&", "(", "originalValue", "instanceof", "Boolean", ")", ")", "{", "node", ".", "put", "(", "cleanup", "(", "key", ")", ",", "!", "(", "(", "Boolean", ")", "originalValue", ")", ")", ";", "}", "// the mapping was successful", "deleteProperty", "=", "false", ";", "break", ";", "}", "else", "{", "String", "defaultValue", "=", "matcher", ".", "group", "(", "4", ")", ";", "if", "(", "defaultValue", "!=", "null", ")", "{", "node", ".", "put", "(", "cleanup", "(", "key", ")", ",", "defaultValue", ")", ";", "deleteProperty", "=", "false", ";", "break", ";", "}", "}", "}", "}", "if", "(", "deleteProperty", ")", "{", "// mapped destination does not exist, we don't include the property in replacement tree", "node", ".", "remove", "(", "key", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Replaces the value of a mapped property with a value from the original tree. @param root the root node of the original tree @param node the replacement tree object @param key property name of the (potentially) mapped property in the replacement copy tree @return true if there was a successful mapping, false otherwise @throws JSONException
[ "Replaces", "the", "value", "of", "a", "mapped", "property", "with", "a", "value", "from", "the", "original", "tree", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java#L297-L340
6,893
wcm-io/wcm-io-tooling
maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java
DialogConverter.rewriteProperty
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)); } } } }
java
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)); } } } }
[ "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. @param node Node @param key the property name to rewrite @param rewriteProperty the property that defines the string rewrite @throws JSONException
[ "Applies", "a", "string", "rewrite", "to", "a", "property", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java#L349-L362
6,894
wcm-io/wcm-io-tooling
maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java
DialogConverter.addCommonAttrMappings
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)) { // the root has granite:data defined, copy it before applying data-* properties node.put(NN_GRANITE_DATA, root.get(NN_GRANITE_DATA)); } // map data-* prefixed properties to granite:data child for (Map.Entry<String, Object> entry : getProperties(root).entrySet()) { if (!StringUtils.startsWith(entry.getKey(), DATA_PREFIX)) { continue; } // add the granite:data child if necessary JSONObject dataNode; if (!node.has(NN_GRANITE_DATA)) { dataNode = new JSONObject(); node.put(NN_GRANITE_DATA, dataNode); } else { dataNode = node.getJSONObject(NN_GRANITE_DATA); } // set up the property mapping String nameWithoutPrefix = entry.getKey().substring(DATA_PREFIX.length()); mapProperty(root, dataNode, nameWithoutPrefix, "${./" + entry.getKey() + "}"); } }
java
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)) { // the root has granite:data defined, copy it before applying data-* properties node.put(NN_GRANITE_DATA, root.get(NN_GRANITE_DATA)); } // map data-* prefixed properties to granite:data child for (Map.Entry<String, Object> entry : getProperties(root).entrySet()) { if (!StringUtils.startsWith(entry.getKey(), DATA_PREFIX)) { continue; } // add the granite:data child if necessary JSONObject dataNode; if (!node.has(NN_GRANITE_DATA)) { dataNode = new JSONObject(); node.put(NN_GRANITE_DATA, dataNode); } else { dataNode = node.getJSONObject(NN_GRANITE_DATA); } // set up the property mapping String nameWithoutPrefix = entry.getKey().substring(DATA_PREFIX.length()); mapProperty(root, dataNode, nameWithoutPrefix, "${./" + entry.getKey() + "}"); } }
[ "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", ")", ")", "{", "// the root has granite:data defined, copy it before applying data-* properties", "node", ".", "put", "(", "NN_GRANITE_DATA", ",", "root", ".", "get", "(", "NN_GRANITE_DATA", ")", ")", ";", "}", "// map data-* prefixed properties to granite:data child", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "getProperties", "(", "root", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "!", "StringUtils", ".", "startsWith", "(", "entry", ".", "getKey", "(", ")", ",", "DATA_PREFIX", ")", ")", "{", "continue", ";", "}", "// add the granite:data child if necessary", "JSONObject", "dataNode", ";", "if", "(", "!", "node", ".", "has", "(", "NN_GRANITE_DATA", ")", ")", "{", "dataNode", "=", "new", "JSONObject", "(", ")", ";", "node", ".", "put", "(", "NN_GRANITE_DATA", ",", "dataNode", ")", ";", "}", "else", "{", "dataNode", "=", "node", ".", "getJSONObject", "(", "NN_GRANITE_DATA", ")", ";", "}", "// set up the property mapping", "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. @param root the root node @param node the replacement node @throws JSONException
[ "Adds", "property", "mappings", "on", "a", "replacement", "node", "for", "Granite", "common", "attributes", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/json-dialog-conversion-plugin/src/main/java/io/wcm/maven/plugins/jsondlgcnv/DialogConverter.java#L370-L401
6,895
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/ContentPackageProperties.java
ContentPackageProperties.get
public static Map<String, Object> get(File packageFile) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(packageFile); ZipArchiveEntry entry = zipFile.getEntry(ZIP_ENTRY_PROPERTIES); if (entry != null && !entry.isDirectory()) { Map<String, Object> props = getPackageProperties(zipFile, entry); return new TreeMap<>(transformPropertyTypes(props)); } return Collections.emptyMap(); } finally { IOUtils.closeQuietly(zipFile); } }
java
public static Map<String, Object> get(File packageFile) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(packageFile); ZipArchiveEntry entry = zipFile.getEntry(ZIP_ENTRY_PROPERTIES); if (entry != null && !entry.isDirectory()) { Map<String, Object> props = getPackageProperties(zipFile, entry); return new TreeMap<>(transformPropertyTypes(props)); } return Collections.emptyMap(); } finally { IOUtils.closeQuietly(zipFile); } }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "get", "(", "File", "packageFile", ")", "throws", "IOException", "{", "ZipFile", "zipFile", "=", "null", ";", "try", "{", "zipFile", "=", "new", "ZipFile", "(", "packageFile", ")", ";", "ZipArchiveEntry", "entry", "=", "zipFile", ".", "getEntry", "(", "ZIP_ENTRY_PROPERTIES", ")", ";", "if", "(", "entry", "!=", "null", "&&", "!", "entry", ".", "isDirectory", "(", ")", ")", "{", "Map", "<", "String", ",", "Object", ">", "props", "=", "getPackageProperties", "(", "zipFile", ",", "entry", ")", ";", "return", "new", "TreeMap", "<>", "(", "transformPropertyTypes", "(", "props", ")", ")", ";", "}", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "zipFile", ")", ";", "}", "}" ]
Get properties of AEM package. @param packageFile AEM package file. @return Map with properties or empty map if none found. @throws IOException I/O exception
[ "Get", "properties", "of", "AEM", "package", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/ContentPackageProperties.java#L55-L69
6,896
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/ContentPackageProperties.java
ContentPackageProperties.transformType
private static Object transformType(Object value) { if (value == null) { return null; } String valueString = value.toString(); // check for boolean boolean boolValue = BooleanUtils.toBoolean(valueString); if (StringUtils.equals(valueString, Boolean.toString(boolValue))) { return boolValue; } // check for integer int intValue = NumberUtils.toInt(valueString); if (StringUtils.equals(valueString, Integer.toString(intValue))) { return intValue; } return value; }
java
private static Object transformType(Object value) { if (value == null) { return null; } String valueString = value.toString(); // check for boolean boolean boolValue = BooleanUtils.toBoolean(valueString); if (StringUtils.equals(valueString, Boolean.toString(boolValue))) { return boolValue; } // check for integer int intValue = NumberUtils.toInt(valueString); if (StringUtils.equals(valueString, Integer.toString(intValue))) { return intValue; } return value; }
[ "private", "static", "Object", "transformType", "(", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "String", "valueString", "=", "value", ".", "toString", "(", ")", ";", "// check for boolean", "boolean", "boolValue", "=", "BooleanUtils", ".", "toBoolean", "(", "valueString", ")", ";", "if", "(", "StringUtils", ".", "equals", "(", "valueString", ",", "Boolean", ".", "toString", "(", "boolValue", ")", ")", ")", "{", "return", "boolValue", ";", "}", "// check for integer", "int", "intValue", "=", "NumberUtils", ".", "toInt", "(", "valueString", ")", ";", "if", "(", "StringUtils", ".", "equals", "(", "valueString", ",", "Integer", ".", "toString", "(", "intValue", ")", ")", ")", "{", "return", "intValue", ";", "}", "return", "value", ";", "}" ]
Detects if string values are boolean or integer and transforms them to correct types. @param value Value @return Transformed value
[ "Detects", "if", "string", "values", "are", "boolean", "or", "integer", "and", "transforms", "them", "to", "correct", "types", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/ContentPackageProperties.java#L98-L117
6,897
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/HttpClientUtil.java
HttpClientUtil.buildRequestConfig
public static RequestConfig buildRequestConfig(PackageManagerProperties props) { return RequestConfig.custom() .setConnectTimeout(props.getHttpConnectTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .setSocketTimeout(props.getHttpSocketTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .build(); }
java
public static RequestConfig buildRequestConfig(PackageManagerProperties props) { return RequestConfig.custom() .setConnectTimeout(props.getHttpConnectTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .setSocketTimeout(props.getHttpSocketTimeoutSec() * (int)DateUtils.MILLIS_PER_SECOND) .build(); }
[ "public", "static", "RequestConfig", "buildRequestConfig", "(", "PackageManagerProperties", "props", ")", "{", "return", "RequestConfig", ".", "custom", "(", ")", ".", "setConnectTimeout", "(", "props", ".", "getHttpConnectTimeoutSec", "(", ")", "*", "(", "int", ")", "DateUtils", ".", "MILLIS_PER_SECOND", ")", ".", "setSocketTimeout", "(", "props", ".", "getHttpSocketTimeoutSec", "(", ")", "*", "(", "int", ")", "DateUtils", ".", "MILLIS_PER_SECOND", ")", ".", "build", "(", ")", ";", "}" ]
Built custom request configuration from package manager properties. @param props Package manager properties @return Request config
[ "Built", "custom", "request", "configuration", "from", "package", "manager", "properties", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/HttpClientUtil.java#L43-L48
6,898
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/HttpClientUtil.java
HttpClientUtil.applyRequestConfig
public static void applyRequestConfig(HttpRequestBase httpRequest, PackageFile packageFile, PackageManagerProperties props) { Integer httpSocketTimeoutSec = packageFile.getHttpSocketTimeoutSec(); if (httpSocketTimeoutSec == null) { return; } // apply specific timeout settings configured for this package file RequestConfig defaultConfig = buildRequestConfig(props); httpRequest.setConfig(RequestConfig.copy(defaultConfig) .setSocketTimeout(httpSocketTimeoutSec * (int)DateUtils.MILLIS_PER_SECOND) .build()); }
java
public static void applyRequestConfig(HttpRequestBase httpRequest, PackageFile packageFile, PackageManagerProperties props) { Integer httpSocketTimeoutSec = packageFile.getHttpSocketTimeoutSec(); if (httpSocketTimeoutSec == null) { return; } // apply specific timeout settings configured for this package file RequestConfig defaultConfig = buildRequestConfig(props); httpRequest.setConfig(RequestConfig.copy(defaultConfig) .setSocketTimeout(httpSocketTimeoutSec * (int)DateUtils.MILLIS_PER_SECOND) .build()); }
[ "public", "static", "void", "applyRequestConfig", "(", "HttpRequestBase", "httpRequest", ",", "PackageFile", "packageFile", ",", "PackageManagerProperties", "props", ")", "{", "Integer", "httpSocketTimeoutSec", "=", "packageFile", ".", "getHttpSocketTimeoutSec", "(", ")", ";", "if", "(", "httpSocketTimeoutSec", "==", "null", ")", "{", "return", ";", "}", "// apply specific timeout settings configured for this package file", "RequestConfig", "defaultConfig", "=", "buildRequestConfig", "(", "props", ")", ";", "httpRequest", ".", "setConfig", "(", "RequestConfig", ".", "copy", "(", "defaultConfig", ")", ".", "setSocketTimeout", "(", "httpSocketTimeoutSec", "*", "(", "int", ")", "DateUtils", ".", "MILLIS_PER_SECOND", ")", ".", "build", "(", ")", ")", ";", "}" ]
Apply timeout configurations that are defined specific for this package file. @param httpRequest Http request @param packageFile Package file @param props Package manager properties
[ "Apply", "timeout", "configurations", "that", "are", "defined", "specific", "for", "this", "package", "file", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/util/HttpClientUtil.java#L56-L67
6,899
wcm-io/wcm-io-tooling
maven/skins/reflow-velocity-tools/src/main/java/io/wcm/maven/skins/reflow/velocity/HtmlTool.java
HtmlTool.headingIndex
private static int headingIndex(Element element) { String tagName = element.tagName(); if (tagName.startsWith("h")) { try { return Integer.parseInt(tagName.substring(1)); } catch (Throwable ex) { throw new IllegalArgumentException("Must be a header tag: " + tagName, ex); } } else { throw new IllegalArgumentException("Must be a header tag: " + tagName); } }
java
private static int headingIndex(Element element) { String tagName = element.tagName(); if (tagName.startsWith("h")) { try { return Integer.parseInt(tagName.substring(1)); } catch (Throwable ex) { throw new IllegalArgumentException("Must be a header tag: " + tagName, ex); } } else { throw new IllegalArgumentException("Must be a header tag: " + tagName); } }
[ "private", "static", "int", "headingIndex", "(", "Element", "element", ")", "{", "String", "tagName", "=", "element", ".", "tagName", "(", ")", ";", "if", "(", "tagName", ".", "startsWith", "(", "\"h\"", ")", ")", "{", "try", "{", "return", "Integer", ".", "parseInt", "(", "tagName", ".", "substring", "(", "1", ")", ")", ";", "}", "catch", "(", "Throwable", "ex", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Must be a header tag: \"", "+", "tagName", ",", "ex", ")", ";", "}", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Must be a header tag: \"", "+", "tagName", ")", ";", "}", "}" ]
Retrieves numeric index of a heading. @param element @return Index
[ "Retrieves", "numeric", "index", "of", "a", "heading", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/skins/reflow-velocity-tools/src/main/java/io/wcm/maven/skins/reflow/velocity/HtmlTool.java#L1225-L1238