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
partition
stringclasses
1 value
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/token/TokenLoaderUtils.java
TokenLoaderUtils.isEmptyCriteria
public static boolean isEmptyCriteria(final Criteria criteria) { return isEmpty(criteria.getAliases()) && isEmpty(criteria.getDeviceTypes()) && isEmpty(criteria.getCategories()); }
java
public static boolean isEmptyCriteria(final Criteria criteria) { return isEmpty(criteria.getAliases()) && isEmpty(criteria.getDeviceTypes()) && isEmpty(criteria.getCategories()); }
[ "public", "static", "boolean", "isEmptyCriteria", "(", "final", "Criteria", "criteria", ")", "{", "return", "isEmpty", "(", "criteria", ".", "getAliases", "(", ")", ")", "&&", "isEmpty", "(", "criteria", ".", "getDeviceTypes", "(", ")", ")", "&&", "isEmpty",...
Helper method to check if all criteria are empty. Useful in FCM land, where we use topics.
[ "Helper", "method", "to", "check", "if", "all", "criteria", "are", "empty", ".", "Useful", "in", "FCM", "land", "where", "we", "use", "topics", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/token/TokenLoaderUtils.java#L71-L76
train
aerogear/aerogear-unifiedpush-server
service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/PushSearchServiceImpl.java
PushSearchServiceImpl.loadDashboardData
@Override public DashboardData loadDashboardData() { long totalApps = totalApplicationNumber(); long totalDevices = totalDeviceNumber(); long totalMessages = totalMessages(); final DashboardData data = new DashboardData(); data.setApplications(totalApps); data.setDevices(totalDevices); data.setMessages(totalMessages); return data; }
java
@Override public DashboardData loadDashboardData() { long totalApps = totalApplicationNumber(); long totalDevices = totalDeviceNumber(); long totalMessages = totalMessages(); final DashboardData data = new DashboardData(); data.setApplications(totalApps); data.setDevices(totalDevices); data.setMessages(totalMessages); return data; }
[ "@", "Override", "public", "DashboardData", "loadDashboardData", "(", ")", "{", "long", "totalApps", "=", "totalApplicationNumber", "(", ")", ";", "long", "totalDevices", "=", "totalDeviceNumber", "(", ")", ";", "long", "totalMessages", "=", "totalMessages", "(", ...
Receives the dashboard data for the given user
[ "Receives", "the", "dashboard", "data", "for", "the", "given", "user" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/PushSearchServiceImpl.java#L80-L94
train
aerogear/aerogear-unifiedpush-server
service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/PushSearchServiceImpl.java
PushSearchServiceImpl.getVariantsWithWarnings
@Override public List<ApplicationVariant> getVariantsWithWarnings() { final List<String> warningIDs = flatPushMessageInformationDao.findVariantIDsWithWarnings(); if (warningIDs.isEmpty()) { return Collections.emptyList(); } return wrapApplicationVariant(pushApplicationDao.findByVariantIds(warningIDs)); }
java
@Override public List<ApplicationVariant> getVariantsWithWarnings() { final List<String> warningIDs = flatPushMessageInformationDao.findVariantIDsWithWarnings(); if (warningIDs.isEmpty()) { return Collections.emptyList(); } return wrapApplicationVariant(pushApplicationDao.findByVariantIds(warningIDs)); }
[ "@", "Override", "public", "List", "<", "ApplicationVariant", ">", "getVariantsWithWarnings", "(", ")", "{", "final", "List", "<", "String", ">", "warningIDs", "=", "flatPushMessageInformationDao", ".", "findVariantIDsWithWarnings", "(", ")", ";", "if", "(", "warn...
Loads all the Variant objects where we did notice some failures on sending for the given user
[ "Loads", "all", "the", "Variant", "objects", "where", "we", "did", "notice", "some", "failures", "on", "sending", "for", "the", "given", "user" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/PushSearchServiceImpl.java#L100-L108
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/metrics/PushMetricsEndpoint.java
PushMetricsEndpoint.pushMessageInformationPerApplication
@GET @Path("/application/{id}") @Produces(MediaType.APPLICATION_JSON) public Response pushMessageInformationPerApplication( @PathParam("id") String id, @QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("sort") String sorting, @QueryParam("search") String search) { pageSize = parsePageSize(pageSize); if (page == null) { page = 0; } if (id == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested information").build(); } PageResult<FlatPushMessageInformation, MessageMetrics> pageResult = metricsService.findAllFlatsForPushApplication(id, search, isAscendingOrder(sorting), page, pageSize); return Response.ok(pageResult.getResultList()) .header("total", pageResult.getAggregate().getCount()) .header("receivers", "0") .header("appOpenedCounter", pageResult.getAggregate().getAppOpenedCounter()) .build(); }
java
@GET @Path("/application/{id}") @Produces(MediaType.APPLICATION_JSON) public Response pushMessageInformationPerApplication( @PathParam("id") String id, @QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("sort") String sorting, @QueryParam("search") String search) { pageSize = parsePageSize(pageSize); if (page == null) { page = 0; } if (id == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested information").build(); } PageResult<FlatPushMessageInformation, MessageMetrics> pageResult = metricsService.findAllFlatsForPushApplication(id, search, isAscendingOrder(sorting), page, pageSize); return Response.ok(pageResult.getResultList()) .header("total", pageResult.getAggregate().getCount()) .header("receivers", "0") .header("appOpenedCounter", pageResult.getAggregate().getAppOpenedCounter()) .build(); }
[ "@", "GET", "@", "Path", "(", "\"/application/{id}\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "pushMessageInformationPerApplication", "(", "@", "PathParam", "(", "\"id\"", ")", "String", "id", ",", "@", "Query...
GET info about submitted push messages for the given Push Application @param id id of {@link org.jboss.aerogear.unifiedpush.api.PushApplication} @param page page number @param pageSize number of items per page @param sorting sorting order: {@code asc} (default) or {@code desc} @param search search query @return list of {@link FlatPushMessageInformation}s @responseheader total Total count of items @responseheader receivers Receivers @responseheader appOpenedCounter App Opened Counter @statuscode 404 The requested PushApplication resource does not exist
[ "GET", "info", "about", "submitted", "push", "messages", "for", "the", "given", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/metrics/PushMetricsEndpoint.java#L59-L87
train
aerogear/aerogear-unifiedpush-server
common/src/main/java/org/jboss/aerogear/unifiedpush/system/ConfigurationUtils.java
ConfigurationUtils.tryGetGlobalProperty
public static String tryGetGlobalProperty(String key, String defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { value = tryGetProperty(key, defaultValue); } return value; } catch (SecurityException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } }
java
public static String tryGetGlobalProperty(String key, String defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { value = tryGetProperty(key, defaultValue); } return value; } catch (SecurityException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } }
[ "public", "static", "String", "tryGetGlobalProperty", "(", "String", "key", ",", "String", "defaultValue", ")", "{", "try", "{", "String", "value", "=", "System", ".", "getenv", "(", "formatEnvironmentVariable", "(", "key", ")", ")", ";", "if", "(", "value",...
Get a global string property. This method will first try to get the value from an environment variable and if that does not exist it will look up a system property. @param key Name of the variable @param defaultValue Returned if neither env var nor system property are defined @return String the value of the Environment or System Property if defined, the given default value otherwise
[ "Get", "a", "global", "string", "property", ".", "This", "method", "will", "first", "try", "to", "get", "the", "value", "from", "an", "environment", "variable", "and", "if", "that", "does", "not", "exist", "it", "will", "look", "up", "a", "system", "prop...
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/common/src/main/java/org/jboss/aerogear/unifiedpush/system/ConfigurationUtils.java#L81-L92
train
aerogear/aerogear-unifiedpush-server
common/src/main/java/org/jboss/aerogear/unifiedpush/system/ConfigurationUtils.java
ConfigurationUtils.tryGetGlobalIntegerProperty
public static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { return tryGetIntegerProperty(key, defaultValue); } else { return Integer.parseInt(value); } } catch (SecurityException | NumberFormatException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } }
java
public static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { return tryGetIntegerProperty(key, defaultValue); } else { return Integer.parseInt(value); } } catch (SecurityException | NumberFormatException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } }
[ "public", "static", "Integer", "tryGetGlobalIntegerProperty", "(", "String", "key", ",", "Integer", "defaultValue", ")", "{", "try", "{", "String", "value", "=", "System", ".", "getenv", "(", "formatEnvironmentVariable", "(", "key", ")", ")", ";", "if", "(", ...
Get a global integer property. This method will first try to get the value from an environment variable and if that does not exist it will look up a system property. @param key Name of the variable @param defaultValue Returned if neither env var nor system property are defined @return String the value of the Environment or System Property if defined, the given default value otherwise
[ "Get", "a", "global", "integer", "property", ".", "This", "method", "will", "first", "try", "to", "get", "the", "value", "from", "an", "environment", "variable", "and", "if", "that", "does", "not", "exist", "it", "will", "look", "up", "a", "system", "pro...
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/common/src/main/java/org/jboss/aerogear/unifiedpush/system/ConfigurationUtils.java#L111-L123
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/WindowsVariantEndpoint.java
WindowsVariantEndpoint.listAllWindowsVariationsForPushApp
@GET @Produces(MediaType.APPLICATION_JSON) public Response listAllWindowsVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID) { final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); return Response.ok(getVariants(application)).build(); }
java
@GET @Produces(MediaType.APPLICATION_JSON) public Response listAllWindowsVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID) { final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); return Response.ok(getVariants(application)).build(); }
[ "@", "GET", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "listAllWindowsVariationsForPushApp", "(", "@", "PathParam", "(", "\"pushAppID\"", ")", "String", "pushApplicationID", ")", "{", "final", "PushApplication", "application...
List Windows Variants for Push Application @param pushApplicationID id of {@link PushApplication} @return list of {@link WindowsVariant}s
[ "List", "Windows", "Variants", "for", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/WindowsVariantEndpoint.java#L99-L104
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/WindowsVariantEndpoint.java
WindowsVariantEndpoint.updateWindowsVariant
@PUT @Path("/{windowsID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateWindowsVariant( @PathParam("windowsID") String windowsID, WindowsVariant updatedWindowsVariant) { WindowsVariant windowsVariant = (WindowsVariant) variantService.findByVariantID(windowsID); if (windowsVariant != null) { // some validation try { validateModelClass(updatedWindowsVariant); } catch (ConstraintViolationException cve) { logger.info("Unable to update Windows Variant '{}'", windowsVariant.getVariantID()); logger.debug("Details: {}", cve); // Build and return the 400 (Bad Request) response Response.ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } // apply updated data: if (windowsVariant instanceof WindowsWNSVariant) { WindowsWNSVariant windowsWNSVariant = (WindowsWNSVariant) windowsVariant; windowsWNSVariant.setClientSecret(((WindowsWNSVariant)updatedWindowsVariant).getClientSecret()); windowsWNSVariant.setSid(((WindowsWNSVariant)updatedWindowsVariant).getSid()); } windowsVariant.setName(updatedWindowsVariant.getName()); windowsVariant.setDescription(updatedWindowsVariant.getDescription()); logger.trace("Updating Windows Variant '{}'", windowsVariant.getVariantID()); variantService.updateVariant(windowsVariant); return Response.ok(windowsVariant).build(); } return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build(); }
java
@PUT @Path("/{windowsID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateWindowsVariant( @PathParam("windowsID") String windowsID, WindowsVariant updatedWindowsVariant) { WindowsVariant windowsVariant = (WindowsVariant) variantService.findByVariantID(windowsID); if (windowsVariant != null) { // some validation try { validateModelClass(updatedWindowsVariant); } catch (ConstraintViolationException cve) { logger.info("Unable to update Windows Variant '{}'", windowsVariant.getVariantID()); logger.debug("Details: {}", cve); // Build and return the 400 (Bad Request) response Response.ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } // apply updated data: if (windowsVariant instanceof WindowsWNSVariant) { WindowsWNSVariant windowsWNSVariant = (WindowsWNSVariant) windowsVariant; windowsWNSVariant.setClientSecret(((WindowsWNSVariant)updatedWindowsVariant).getClientSecret()); windowsWNSVariant.setSid(((WindowsWNSVariant)updatedWindowsVariant).getSid()); } windowsVariant.setName(updatedWindowsVariant.getName()); windowsVariant.setDescription(updatedWindowsVariant.getDescription()); logger.trace("Updating Windows Variant '{}'", windowsVariant.getVariantID()); variantService.updateVariant(windowsVariant); return Response.ok(windowsVariant).build(); } return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build(); }
[ "@", "PUT", "@", "Path", "(", "\"/{windowsID}\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "updateWindowsVariant", "(", "@", "PathParam", "(", "...
Update Windows Variant @param windowsID id of {@link WindowsVariant} @param updatedWindowsVariant new info of {@link WindowsVariant} @return updated {@link WindowsVariant} @statuscode 200 The Windows Variant updated successfully @statuscode 400 The format of the client request was incorrect @statuscode 404 The requested Windows Variant resource does not exist
[ "Update", "Windows", "Variant" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/WindowsVariantEndpoint.java#L118-L158
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java
AbstractJMSMessageProducer.sendNonTransacted
protected void sendNonTransacted(Destination destination, Serializable message) { send(destination, message, null, null, false); }
java
protected void sendNonTransacted(Destination destination, Serializable message) { send(destination, message, null, null, false); }
[ "protected", "void", "sendNonTransacted", "(", "Destination", "destination", ",", "Serializable", "message", ")", "{", "send", "(", "destination", ",", "message", ",", "null", ",", "null", ",", "false", ")", ";", "}" ]
Sends message to the destination in non-transactional manner. @param destination where to send @param message what to send Since non-transacted session is used, the message is send immediately without requiring to commit enclosing transaction.
[ "Sends", "message", "to", "the", "destination", "in", "non", "-", "transactional", "manner", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java#L54-L56
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java
AbstractJMSMessageProducer.sendTransacted
protected void sendTransacted(Destination destination, Serializable message) { send(destination, message, null, null, true); }
java
protected void sendTransacted(Destination destination, Serializable message) { send(destination, message, null, null, true); }
[ "protected", "void", "sendTransacted", "(", "Destination", "destination", ",", "Serializable", "message", ")", "{", "send", "(", "destination", ",", "message", ",", "null", ",", "null", ",", "true", ")", ";", "}" ]
Sends message to the destination in transactional manner. @param destination where to send @param message what to send Since transacted session is used, the message won't be committed until whole enclosing transaction ends
[ "Sends", "message", "to", "the", "destination", "in", "transactional", "manner", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java#L66-L68
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java
AbstractJMSMessageProducer.sendNonTransacted
protected void sendNonTransacted(Destination destination, Serializable message, String propertyName, String propertValue) { send(destination, message, propertyName, propertValue, false); }
java
protected void sendNonTransacted(Destination destination, Serializable message, String propertyName, String propertValue) { send(destination, message, propertyName, propertValue, false); }
[ "protected", "void", "sendNonTransacted", "(", "Destination", "destination", ",", "Serializable", "message", ",", "String", "propertyName", ",", "String", "propertValue", ")", "{", "send", "(", "destination", ",", "message", ",", "propertyName", ",", "propertValue",...
Sends message to destination with given JMS message property name and value in non-transactional manner. @param destination where to send @param message what to send @param propertyName property of obj @param propertValue value of obj Since non-transacted session is used, the message is send immediately without requiring to commit enclosing transaction.
[ "Sends", "message", "to", "destination", "with", "given", "JMS", "message", "property", "name", "and", "value", "in", "non", "-", "transactional", "manner", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java#L80-L82
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java
AbstractJMSMessageProducer.sendTransacted
protected void sendTransacted(Destination destination, Serializable message, String propertyName, String propertValue) { send(destination, message, propertyName, propertValue, true); }
java
protected void sendTransacted(Destination destination, Serializable message, String propertyName, String propertValue) { send(destination, message, propertyName, propertValue, true); }
[ "protected", "void", "sendTransacted", "(", "Destination", "destination", ",", "Serializable", "message", ",", "String", "propertyName", ",", "String", "propertValue", ")", "{", "send", "(", "destination", ",", "message", ",", "propertyName", ",", "propertValue", ...
Sends message to destination with given JMS message property name and value in transactional manner. @param destination where to send @param message what to send @param propertyName property of obj @param propertValue value of obj Since transacted session is used, the message won't be committed until whole enclosing transaction ends.
[ "Sends", "message", "to", "destination", "with", "given", "JMS", "message", "property", "name", "and", "value", "in", "transactional", "manner", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/jms/AbstractJMSMessageProducer.java#L94-L96
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/cache/SimpleApnsClientCache.java
SimpleApnsClientCache.disconnectOnChange
public void disconnectOnChange(@Observes final iOSVariantUpdateEvent iOSVariantUpdateEvent) { final iOSVariant variant = iOSVariantUpdateEvent.getiOSVariant(); final String connectionKey = extractConnectionKey(variant); final ApnsClient client = apnsClientExpiringMap.remove(connectionKey); logger.debug("Removed client from cache for {}", variant.getVariantID()); if (client != null) { tearDownApnsHttp2Connection(client); } }
java
public void disconnectOnChange(@Observes final iOSVariantUpdateEvent iOSVariantUpdateEvent) { final iOSVariant variant = iOSVariantUpdateEvent.getiOSVariant(); final String connectionKey = extractConnectionKey(variant); final ApnsClient client = apnsClientExpiringMap.remove(connectionKey); logger.debug("Removed client from cache for {}", variant.getVariantID()); if (client != null) { tearDownApnsHttp2Connection(client); } }
[ "public", "void", "disconnectOnChange", "(", "@", "Observes", "final", "iOSVariantUpdateEvent", "iOSVariantUpdateEvent", ")", "{", "final", "iOSVariant", "variant", "=", "iOSVariantUpdateEvent", ".", "getiOSVariant", "(", ")", ";", "final", "String", "connectionKey", ...
Receives iOS variant change event to remove client from the cache and also tear down the connection. @param iOSVariantUpdateEvent event fired when updating the variant
[ "Receives", "iOS", "variant", "change", "event", "to", "remove", "client", "from", "the", "cache", "and", "also", "tear", "down", "the", "connection", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/cache/SimpleApnsClientCache.java#L94-L102
train
aerogear/aerogear-unifiedpush-server
service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/ClientInstallationServiceImpl.java
ClientInstallationServiceImpl.findAllDeviceTokenForVariantIDByCriteria
@Override public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID, List<String> categories, List<String> aliases, List<String> deviceTypes, int maxResults, String lastTokenFromPreviousBatch) { return installationDao.findAllDeviceTokenForVariantIDByCriteria(variantID, categories, aliases, deviceTypes, maxResults, lastTokenFromPreviousBatch, false); }
java
@Override public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID, List<String> categories, List<String> aliases, List<String> deviceTypes, int maxResults, String lastTokenFromPreviousBatch) { return installationDao.findAllDeviceTokenForVariantIDByCriteria(variantID, categories, aliases, deviceTypes, maxResults, lastTokenFromPreviousBatch, false); }
[ "@", "Override", "public", "ResultsStream", ".", "QueryBuilder", "<", "String", ">", "findAllDeviceTokenForVariantIDByCriteria", "(", "String", "variantID", ",", "List", "<", "String", ">", "categories", ",", "List", "<", "String", ">", "aliases", ",", "List", "...
Finder for 'send', used for Android and iOS clients
[ "Finder", "for", "send", "used", "for", "Android", "and", "iOS", "clients" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/service/src/main/java/org/jboss/aerogear/unifiedpush/service/impl/ClientInstallationServiceImpl.java#L223-L226
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/InstallationManagementEndpoint.java
InstallationManagementEndpoint.findInstallation
@GET @Path("/{installationID}") @Produces(MediaType.APPLICATION_JSON) public Response findInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId) { Installation installation = clientInstallationService.findById(installationId); if (installation == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build(); } return Response.ok(installation).build(); }
java
@GET @Path("/{installationID}") @Produces(MediaType.APPLICATION_JSON) public Response findInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId) { Installation installation = clientInstallationService.findById(installationId); if (installation == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build(); } return Response.ok(installation).build(); }
[ "@", "GET", "@", "Path", "(", "\"/{installationID}\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "findInstallation", "(", "@", "PathParam", "(", "\"variantID\"", ")", "String", "variantId", ",", "@", "PathParam",...
Get Installation of specified Variant @param variantId id of {@link org.jboss.aerogear.unifiedpush.api.Variant} @param installationId id of {@link Installation} @return requested {@link Installation} @statuscode 404 The requested Installation resource does not exist
[ "Get", "Installation", "of", "specified", "Variant" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/InstallationManagementEndpoint.java#L130-L142
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/InstallationManagementEndpoint.java
InstallationManagementEndpoint.updateInstallation
@PUT @Path("/{installationID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateInstallation(Installation entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId) { Installation installation = clientInstallationService.findById(installationId); if (installation == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build(); } clientInstallationService.updateInstallation(installation, entity); return Response.noContent().build(); }
java
@PUT @Path("/{installationID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateInstallation(Installation entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId) { Installation installation = clientInstallationService.findById(installationId); if (installation == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build(); } clientInstallationService.updateInstallation(installation, entity); return Response.noContent().build(); }
[ "@", "PUT", "@", "Path", "(", "\"/{installationID}\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "updateInstallation", "(", "Installation", "entity",...
Update Installation of specified Variant @param entity new info of {@link Installation} @param variantId id of {@link org.jboss.aerogear.unifiedpush.api.Variant} @param installationId id of {@link Installation} @return updated {@link Installation} @statuscode 204 The Installation updated successfully @statuscode 404 The requested Installation resource does not exist
[ "Update", "Installation", "of", "specified", "Variant" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/InstallationManagementEndpoint.java#L155-L171
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/installations/ExportEndpoint.java
ExportEndpoint.exportInstallations
@GET @Path("/{variantId}/installations/") @Produces(MediaType.APPLICATION_JSON) @GZIP public Response exportInstallations(@PathParam("variantId") String variantId) { return Response.ok(getSearch().findAllInstallationsByVariantForDeveloper(variantId, 0, Integer.MAX_VALUE, null).getResultList()).build(); }
java
@GET @Path("/{variantId}/installations/") @Produces(MediaType.APPLICATION_JSON) @GZIP public Response exportInstallations(@PathParam("variantId") String variantId) { return Response.ok(getSearch().findAllInstallationsByVariantForDeveloper(variantId, 0, Integer.MAX_VALUE, null).getResultList()).build(); }
[ "@", "GET", "@", "Path", "(", "\"/{variantId}/installations/\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "GZIP", "public", "Response", "exportInstallations", "(", "@", "PathParam", "(", "\"variantId\"", ")", "String", "variantId"...
Endpoint for exporting as JSON file device installations for a given variant. Only Keycloak authenticated can access it @param variantId the variant ID @return list of {@link org.jboss.aerogear.unifiedpush.api.Installation}s
[ "Endpoint", "for", "exporting", "as", "JSON", "file", "device", "installations", "for", "a", "given", "variant", ".", "Only", "Keycloak", "authenticated", "can", "access", "it" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/installations/ExportEndpoint.java#L50-L56
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/sender/FCMPushNotificationSender.java
FCMPushNotificationSender.processFCM
private void processFCM(AndroidVariant androidVariant, List<String> pushTargets, Message fcmMessage, ConfigurableFCMSender sender) throws IOException { // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed. if (pushTargets.get(0).startsWith(Constants.TOPIC_PREFIX)) { // perform the topic delivery for (String topic : pushTargets) { logger.info(String.format("Sent push notification to FCM topic: %s", topic)); Result result = sender.sendNoRetry(fcmMessage, topic); logger.trace("Response from FCM topic request: {}", result); } } else { logger.info(String.format("Sent push notification to FCM Server for %d registrationIDs", pushTargets.size())); MulticastResult multicastResult = sender.sendNoRetry(fcmMessage, pushTargets); logger.trace("Response from FCM request: {}", multicastResult); // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion: cleanupInvalidRegistrationIDsForVariant(androidVariant.getVariantID(), multicastResult, pushTargets); } }
java
private void processFCM(AndroidVariant androidVariant, List<String> pushTargets, Message fcmMessage, ConfigurableFCMSender sender) throws IOException { // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed. if (pushTargets.get(0).startsWith(Constants.TOPIC_PREFIX)) { // perform the topic delivery for (String topic : pushTargets) { logger.info(String.format("Sent push notification to FCM topic: %s", topic)); Result result = sender.sendNoRetry(fcmMessage, topic); logger.trace("Response from FCM topic request: {}", result); } } else { logger.info(String.format("Sent push notification to FCM Server for %d registrationIDs", pushTargets.size())); MulticastResult multicastResult = sender.sendNoRetry(fcmMessage, pushTargets); logger.trace("Response from FCM request: {}", multicastResult); // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion: cleanupInvalidRegistrationIDsForVariant(androidVariant.getVariantID(), multicastResult, pushTargets); } }
[ "private", "void", "processFCM", "(", "AndroidVariant", "androidVariant", ",", "List", "<", "String", ">", "pushTargets", ",", "Message", "fcmMessage", ",", "ConfigurableFCMSender", "sender", ")", "throws", "IOException", "{", "// push targets can be registration IDs OR t...
Process the HTTP POST to the FCM infrastructure for the given list of registrationIDs.
[ "Process", "the", "HTTP", "POST", "to", "the", "FCM", "infrastructure", "for", "the", "given", "list", "of", "registrationIDs", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/sender/FCMPushNotificationSender.java#L142-L165
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.registerPushApplication
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response registerPushApplication(PushApplication pushApp) { try { validateModelClass(pushApp); } catch (ConstraintViolationException cve) { logger.trace("Unable to create Push Application"); return createBadRequestResponse(cve.getConstraintViolations()).build(); } try { logger.trace("Invoke service to create a push application"); pushAppService.addPushApplication(pushApp); } catch (IllegalArgumentException e) { return Response.status(Status.CONFLICT).entity(e.getMessage()).build(); } final URI uri = UriBuilder.fromResource(PushApplicationEndpoint.class) .path(pushApp.getPushApplicationID()) .build(); return Response .created(uri) .entity(pushApp) .build(); }
java
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response registerPushApplication(PushApplication pushApp) { try { validateModelClass(pushApp); } catch (ConstraintViolationException cve) { logger.trace("Unable to create Push Application"); return createBadRequestResponse(cve.getConstraintViolations()).build(); } try { logger.trace("Invoke service to create a push application"); pushAppService.addPushApplication(pushApp); } catch (IllegalArgumentException e) { return Response.status(Status.CONFLICT).entity(e.getMessage()).build(); } final URI uri = UriBuilder.fromResource(PushApplicationEndpoint.class) .path(pushApp.getPushApplicationID()) .build(); return Response .created(uri) .entity(pushApp) .build(); }
[ "@", "POST", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "registerPushApplication", "(", "PushApplication", "pushApp", ")", "{", "try", "{", "validateModelC...
Create Push Application @param pushApp new {@link PushApplication} @return created {@link PushApplication} @statuscode 201 The PushApplication Variant created successfully @statuscode 400 The format of the client request was incorrect @statuscode 409 The PushApplication already exists
[ "Create", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L75-L102
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.listAllPushApplications
@GET @Produces(MediaType.APPLICATION_JSON) public Response listAllPushApplications(@QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount, @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) { if (pageSize != null) { pageSize = Math.min(MAX_PAGE_SIZE, pageSize); } else { pageSize = DEFAULT_PAGE_SIZE; } if (page == null) { page = 0; } logger.trace("Query paged push applications with {} items for page {}", pageSize, page); final PageResult<PushApplication, Count> pageResult = getSearch().findAllPushApplicationsForDeveloper(page, pageSize); ResponseBuilder response = Response.ok(pageResult.getResultList()); response.header("total", pageResult.getAggregate().getCount()); for (PushApplication app : pageResult.getResultList()) { if (includeActivity) { logger.trace("Include activity header"); putActivityIntoResponseHeaders(app, response); } if (includeDeviceCount) { logger.trace("Include device count header"); putDeviceCountIntoResponseHeaders(app, response); } } return response.build(); }
java
@GET @Produces(MediaType.APPLICATION_JSON) public Response listAllPushApplications(@QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount, @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) { if (pageSize != null) { pageSize = Math.min(MAX_PAGE_SIZE, pageSize); } else { pageSize = DEFAULT_PAGE_SIZE; } if (page == null) { page = 0; } logger.trace("Query paged push applications with {} items for page {}", pageSize, page); final PageResult<PushApplication, Count> pageResult = getSearch().findAllPushApplicationsForDeveloper(page, pageSize); ResponseBuilder response = Response.ok(pageResult.getResultList()); response.header("total", pageResult.getAggregate().getCount()); for (PushApplication app : pageResult.getResultList()) { if (includeActivity) { logger.trace("Include activity header"); putActivityIntoResponseHeaders(app, response); } if (includeDeviceCount) { logger.trace("Include device count header"); putDeviceCountIntoResponseHeaders(app, response); } } return response.build(); }
[ "@", "GET", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "listAllPushApplications", "(", "@", "QueryParam", "(", "\"page\"", ")", "Integer", "page", ",", "@", "QueryParam", "(", "\"per_page\"", ")", "Integer", "pageSize"...
List Push Applications @param page page number @param pageSize number of items per page @param includeDeviceCount put device count into response headers, default {@code false} @param includeActivity put activity into response headers, default {@code false} @return list of {@link PushApplication}s @responseheader total Total count of items @responseheader activity_app_{pushApplicationID} Count number of messages for Push Application @responseheader activity_variant_{variantID} Count number of messages for Variant @responseheader deviceCount_app_{pushApplicationID} Count number of devices for Push Application @responseheader deviceCount_variant_{variantID} Count number of devices for Variant
[ "List", "Push", "Applications" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L119-L150
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.findById
@GET @Path("/{pushAppID}") @Produces(MediaType.APPLICATION_JSON) public Response findById( @PathParam("pushAppID") String pushApplicationID, @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount, @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { logger.trace("Query details for push application {}", pushApp.getName()); ResponseBuilder response = Response.ok(pushApp); if (includeActivity) { logger.trace("Include activity header"); putActivityIntoResponseHeaders(pushApp, response); } if (includeDeviceCount) { logger.trace("Include device count header"); putDeviceCountIntoResponseHeaders(pushApp, response); } return response.build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
java
@GET @Path("/{pushAppID}") @Produces(MediaType.APPLICATION_JSON) public Response findById( @PathParam("pushAppID") String pushApplicationID, @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount, @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { logger.trace("Query details for push application {}", pushApp.getName()); ResponseBuilder response = Response.ok(pushApp); if (includeActivity) { logger.trace("Include activity header"); putActivityIntoResponseHeaders(pushApp, response); } if (includeDeviceCount) { logger.trace("Include device count header"); putDeviceCountIntoResponseHeaders(pushApp, response); } return response.build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
[ "@", "GET", "@", "Path", "(", "\"/{pushAppID}\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "findById", "(", "@", "PathParam", "(", "\"pushAppID\"", ")", "String", "pushApplicationID", ",", "@", "QueryParam", "...
Get Push Application. @param pushApplicationID id of {@link PushApplication} @param includeDeviceCount boolean param to put device count into response headers, default {@code false} @param includeActivity boolean param to put activity into response headers, default {@code false} @return requested {@link PushApplication} @responseheader activity_app_{pushApplicationID} Count number of messages for Push Application @responseheader activity_variant_{variantID} Count number of messages for Variant @responseheader deviceCount_app_{pushApplicationID} Count number of devices for Push Application @responseheader deviceCount_variant_{variantID} Count number of devices for Variant @statuscode 404 The requested PushApplication resource does not exist
[ "Get", "Push", "Application", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L167-L192
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.updatePushApplication
@PUT @Path("/{pushAppID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updatePushApplication(@PathParam("pushAppID") String pushApplicationID, PushApplication updatedPushApp) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { // some validation try { validateModelClass(updatedPushApp); } catch (ConstraintViolationException cve) { logger.info("Unable to update Push Application '{}'", pushApplicationID); logger.debug("Details: {}", cve); // Build and return the 400 (Bad Request) response ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } // update name/desc: pushApp.setDescription(updatedPushApp.getDescription()); pushApp.setName(updatedPushApp.getName()); logger.trace("Invoke service to update a push application"); pushAppService.updatePushApplication(pushApp); return Response.noContent().build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
java
@PUT @Path("/{pushAppID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updatePushApplication(@PathParam("pushAppID") String pushApplicationID, PushApplication updatedPushApp) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { // some validation try { validateModelClass(updatedPushApp); } catch (ConstraintViolationException cve) { logger.info("Unable to update Push Application '{}'", pushApplicationID); logger.debug("Details: {}", cve); // Build and return the 400 (Bad Request) response ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } // update name/desc: pushApp.setDescription(updatedPushApp.getDescription()); pushApp.setName(updatedPushApp.getName()); logger.trace("Invoke service to update a push application"); pushAppService.updatePushApplication(pushApp); return Response.noContent().build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
[ "@", "PUT", "@", "Path", "(", "\"/{pushAppID}\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "updatePushApplication", "(", "@", "PathParam", "(", ...
Update Push Application @param pushApplicationID id of {@link PushApplication} @param updatedPushApp new info of {@link PushApplication} @return updated {@link PushApplication} @statuscode 204 The PushApplication updated successfully @statuscode 400 The format of the client request was incorrect @statuscode 404 The requested PushApplication resource does not exist
[ "Update", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L219-L251
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.resetMasterSecret
@PUT @Path("/{pushAppID}/reset") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response resetMasterSecret(@PathParam("pushAppID") String pushApplicationID) { //PushApplication pushApp = pushAppService.findByPushApplicationIDForDeveloper(pushApplicationID, extractUsername(request)); PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { // generate the new 'masterSecret' and apply it: String newMasterSecret = UUID.randomUUID().toString(); pushApp.setMasterSecret(newMasterSecret); logger.info("Invoke service to change master secret of a push application '{}'", pushApp.getPushApplicationID()); pushAppService.updatePushApplication(pushApp); return Response.ok(pushApp).build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
java
@PUT @Path("/{pushAppID}/reset") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response resetMasterSecret(@PathParam("pushAppID") String pushApplicationID) { //PushApplication pushApp = pushAppService.findByPushApplicationIDForDeveloper(pushApplicationID, extractUsername(request)); PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { // generate the new 'masterSecret' and apply it: String newMasterSecret = UUID.randomUUID().toString(); pushApp.setMasterSecret(newMasterSecret); logger.info("Invoke service to change master secret of a push application '{}'", pushApp.getPushApplicationID()); pushAppService.updatePushApplication(pushApp); return Response.ok(pushApp).build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
[ "@", "PUT", "@", "Path", "(", "\"/{pushAppID}/reset\"", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "resetMasterSecret", "(", "@", "PathParam", "(", ...
Reset MasterSecret for Push Application @param pushApplicationID id of {@link PushApplication} @return updated {@link PushApplication} @statuscode 200 The MasterSecret for Push Application reset successfully @statuscode 404 The requested PushApplication resource does not exist
[ "Reset", "MasterSecret", "for", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L262-L282
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.deletePushApplication
@DELETE @Path("/{pushAppID}") @Produces(MediaType.APPLICATION_JSON) public Response deletePushApplication(@PathParam("pushAppID") String pushApplicationID) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { logger.trace("Invoke service to delete a push application"); pushAppService.removePushApplication(pushApp); return Response.noContent().build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
java
@DELETE @Path("/{pushAppID}") @Produces(MediaType.APPLICATION_JSON) public Response deletePushApplication(@PathParam("pushAppID") String pushApplicationID) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp != null) { logger.trace("Invoke service to delete a push application"); pushAppService.removePushApplication(pushApp); return Response.noContent().build(); } return Response.status(Status.NOT_FOUND).entity("Could not find requested PushApplicationEntity").build(); }
[ "@", "DELETE", "@", "Path", "(", "\"/{pushAppID}\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "deletePushApplication", "(", "@", "PathParam", "(", "\"pushAppID\"", ")", "String", "pushApplicationID", ")", "{", "...
Delete Push Application @param pushApplicationID id of {@link PushApplication} @return no content @statuscode 204 The PushApplication successfully deleted @statuscode 404 The requested PushApplication resource does not exist
[ "Delete", "Push", "Application" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L293-L306
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java
PushApplicationEndpoint.countInstallations
@GET @Path("/{pushAppID}/count") @Produces(MediaType.APPLICATION_JSON) public Response countInstallations(@PathParam("pushAppID") String pushApplicationID) { logger.trace("counting devices by type for push application '{}'", pushApplicationID); Map<String, Long> result = pushAppService.countInstallationsByType(pushApplicationID); return Response.ok(result).build(); }
java
@GET @Path("/{pushAppID}/count") @Produces(MediaType.APPLICATION_JSON) public Response countInstallations(@PathParam("pushAppID") String pushApplicationID) { logger.trace("counting devices by type for push application '{}'", pushApplicationID); Map<String, Long> result = pushAppService.countInstallationsByType(pushApplicationID); return Response.ok(result).build(); }
[ "@", "GET", "@", "Path", "(", "\"/{pushAppID}/count\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "public", "Response", "countInstallations", "(", "@", "PathParam", "(", "\"pushAppID\"", ")", "String", "pushApplicationID", ")", "{", "...
Count Push Applications @param pushApplicationID id of {@link PushApplication} @return count number for each {@link org.jboss.aerogear.unifiedpush.api.VariantType}
[ "Count", "Push", "Applications" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/PushApplicationEndpoint.java#L314-L322
train
aerogear/aerogear-unifiedpush-server
push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/configuration/SenderConfigurationProvider.java
SenderConfigurationProvider.validateAndSanitizeConfiguration
private SenderConfiguration validateAndSanitizeConfiguration(VariantType type, SenderConfiguration configuration) { switch (type) { case ANDROID: if (configuration.batchSize() > 1000) { logger.warn(String .format("Sender configuration -D%s=%s is invalid: at most 1000 tokens can be submitted to GCM in one batch", getSystemPropertyName(type, ConfigurationProperty.batchSize), configuration.batchSize())); configuration.setBatchSize(1000); } break; default: break; } return configuration; }
java
private SenderConfiguration validateAndSanitizeConfiguration(VariantType type, SenderConfiguration configuration) { switch (type) { case ANDROID: if (configuration.batchSize() > 1000) { logger.warn(String .format("Sender configuration -D%s=%s is invalid: at most 1000 tokens can be submitted to GCM in one batch", getSystemPropertyName(type, ConfigurationProperty.batchSize), configuration.batchSize())); configuration.setBatchSize(1000); } break; default: break; } return configuration; }
[ "private", "SenderConfiguration", "validateAndSanitizeConfiguration", "(", "VariantType", "type", ",", "SenderConfiguration", "configuration", ")", "{", "switch", "(", "type", ")", "{", "case", "ANDROID", ":", "if", "(", "configuration", ".", "batchSize", "(", ")", ...
Validates that configuration is correct with regards to push networks limitations or implementation, etc.
[ "Validates", "that", "configuration", "is", "correct", "with", "regards", "to", "push", "networks", "limitations", "or", "implementation", "etc", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/push-sender/src/main/java/org/jboss/aerogear/unifiedpush/message/configuration/SenderConfigurationProvider.java#L73-L87
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/util/CommonUtils.java
CommonUtils.isAscendingOrder
public static Boolean isAscendingOrder(String sorting) { return "desc".equalsIgnoreCase(sorting) ? Boolean.FALSE : Boolean.TRUE; }
java
public static Boolean isAscendingOrder(String sorting) { return "desc".equalsIgnoreCase(sorting) ? Boolean.FALSE : Boolean.TRUE; }
[ "public", "static", "Boolean", "isAscendingOrder", "(", "String", "sorting", ")", "{", "return", "\"desc\"", ".", "equalsIgnoreCase", "(", "sorting", ")", "?", "Boolean", ".", "FALSE", ":", "Boolean", ".", "TRUE", ";", "}" ]
Verify if the string sorting matches with asc or desc Returns FALSE when sorting query value matches desc, otherwise it returns TRUE. @param sorting the sorting value from the http header @return false for desc or true for as
[ "Verify", "if", "the", "string", "sorting", "matches", "with", "asc", "or", "desc", "Returns", "FALSE", "when", "sorting", "query", "value", "matches", "desc", "otherwise", "it", "returns", "TRUE", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/util/CommonUtils.java#L35-L37
train
aerogear/aerogear-unifiedpush-server
model/push/src/main/java/org/jboss/aerogear/unifiedpush/message/UnifiedPushMessage.java
UnifiedPushMessage.toStrippedJsonString
public String toStrippedJsonString() { try { final Map<String, Object> json = new LinkedHashMap<>(); json.put("alert", this.message.getAlert()); json.put("priority", this.message.getPriority().toString()); if (this.getMessage().getBadge()>0) { json.put("badge", Integer.toString(this.getMessage().getBadge())); } json.put("criteria", this.criteria); json.put("config", this.config); return OBJECT_MAPPER.writeValueAsString(json); } catch (JsonProcessingException e) { return "[\"invalid json\"]"; } catch (IOException e) { return "[\"invalid json\"]"; } }
java
public String toStrippedJsonString() { try { final Map<String, Object> json = new LinkedHashMap<>(); json.put("alert", this.message.getAlert()); json.put("priority", this.message.getPriority().toString()); if (this.getMessage().getBadge()>0) { json.put("badge", Integer.toString(this.getMessage().getBadge())); } json.put("criteria", this.criteria); json.put("config", this.config); return OBJECT_MAPPER.writeValueAsString(json); } catch (JsonProcessingException e) { return "[\"invalid json\"]"; } catch (IOException e) { return "[\"invalid json\"]"; } }
[ "public", "String", "toStrippedJsonString", "(", ")", "{", "try", "{", "final", "Map", "<", "String", ",", "Object", ">", "json", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "json", ".", "put", "(", "\"alert\"", ",", "this", ".", "message", ".", ...
Returns a JSON representation of the payload. This does not include any pushed data, just the alert of the message. This also contains the entire criteria object. @see #toMinimizedJsonString() @return JSON payload
[ "Returns", "a", "JSON", "representation", "of", "the", "payload", ".", "This", "does", "not", "include", "any", "pushed", "data", "just", "the", "alert", "of", "the", "message", ".", "This", "also", "contains", "the", "entire", "criteria", "object", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/model/push/src/main/java/org/jboss/aerogear/unifiedpush/message/UnifiedPushMessage.java#L79-L95
train
aerogear/aerogear-unifiedpush-server
model/push/src/main/java/org/jboss/aerogear/unifiedpush/message/UnifiedPushMessage.java
UnifiedPushMessage.toMinimizedJsonString
public String toMinimizedJsonString() { try { final Map<String, Object> json = new LinkedHashMap<>(); json.put("alert", this.message.getAlert()); if (this.getMessage().getBadge()>0) { json.put("badge", Integer.toString(this.getMessage().getBadge())); } json.put("config", this.config); // we strip down the criteria too, as alias/category can be quite long, based on use-case final Map<String, Object> shrinkedCriteriaJSON = new LinkedHashMap<>(); shrinkedCriteriaJSON.put("variants", this.criteria.getVariants()); shrinkedCriteriaJSON.put("deviceType", this.criteria.getDeviceTypes()); json.put("criteria", shrinkedCriteriaJSON); return OBJECT_MAPPER.writeValueAsString(json); } catch (JsonProcessingException e) { return "[\"invalid json\"]"; } catch (IOException e) { return "[\"invalid json\"]"; } }
java
public String toMinimizedJsonString() { try { final Map<String, Object> json = new LinkedHashMap<>(); json.put("alert", this.message.getAlert()); if (this.getMessage().getBadge()>0) { json.put("badge", Integer.toString(this.getMessage().getBadge())); } json.put("config", this.config); // we strip down the criteria too, as alias/category can be quite long, based on use-case final Map<String, Object> shrinkedCriteriaJSON = new LinkedHashMap<>(); shrinkedCriteriaJSON.put("variants", this.criteria.getVariants()); shrinkedCriteriaJSON.put("deviceType", this.criteria.getDeviceTypes()); json.put("criteria", shrinkedCriteriaJSON); return OBJECT_MAPPER.writeValueAsString(json); } catch (JsonProcessingException e) { return "[\"invalid json\"]"; } catch (IOException e) { return "[\"invalid json\"]"; } }
[ "public", "String", "toMinimizedJsonString", "(", ")", "{", "try", "{", "final", "Map", "<", "String", ",", "Object", ">", "json", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "json", ".", "put", "(", "\"alert\"", ",", "this", ".", "message", ".",...
Returns a minimized JSON representation of the payload. This does not include potentially large objects, like alias or category from the given criteria. @see #toStrippedJsonString() @return minizmized JSON payload
[ "Returns", "a", "minimized", "JSON", "representation", "of", "the", "payload", ".", "This", "does", "not", "include", "potentially", "large", "objects", "like", "alias", "or", "category", "from", "the", "given", "criteria", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/model/push/src/main/java/org/jboss/aerogear/unifiedpush/message/UnifiedPushMessage.java#L105-L126
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/AbstractBaseEndpoint.java
AbstractBaseEndpoint.validateModelClass
protected void validateModelClass(Object model) { final Set<ConstraintViolation<Object>> violations = validator.validate(model); // in case of an invalid model, we throw a ConstraintViolationException, containing the violations: if (!violations.isEmpty()) { throw new ConstraintViolationException( new HashSet<>(violations)); } }
java
protected void validateModelClass(Object model) { final Set<ConstraintViolation<Object>> violations = validator.validate(model); // in case of an invalid model, we throw a ConstraintViolationException, containing the violations: if (!violations.isEmpty()) { throw new ConstraintViolationException( new HashSet<>(violations)); } }
[ "protected", "void", "validateModelClass", "(", "Object", "model", ")", "{", "final", "Set", "<", "ConstraintViolation", "<", "Object", ">", ">", "violations", "=", "validator", ".", "validate", "(", "model", ")", ";", "// in case of an invalid model, we throw a Con...
Generic validator used to identify constraint violations of the given model class. @param model object to validate @throws ConstraintViolationException if constraint violations on the given model have been identified.
[ "Generic", "validator", "used", "to", "identify", "constraint", "violations", "of", "the", "given", "model", "class", "." ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/AbstractBaseEndpoint.java#L70-L78
train
aerogear/aerogear-unifiedpush-server
jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/AbstractBaseEndpoint.java
AbstractBaseEndpoint.createBadRequestResponse
protected ResponseBuilder createBadRequestResponse(Set<ConstraintViolation<?>> violations) { final Map<String, String> responseObj = violations.stream() .collect(Collectors.toMap(v -> v.getPropertyPath().toString(), ConstraintViolation::getMessage)); return Response.status(Response.Status.BAD_REQUEST) .entity(responseObj); }
java
protected ResponseBuilder createBadRequestResponse(Set<ConstraintViolation<?>> violations) { final Map<String, String> responseObj = violations.stream() .collect(Collectors.toMap(v -> v.getPropertyPath().toString(), ConstraintViolation::getMessage)); return Response.status(Response.Status.BAD_REQUEST) .entity(responseObj); }
[ "protected", "ResponseBuilder", "createBadRequestResponse", "(", "Set", "<", "ConstraintViolation", "<", "?", ">", ">", "violations", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "responseObj", "=", "violations", ".", "stream", "(", ")", ".", ...
Helper function to create a 400 Bad Request response, containing a JSON map giving details about the violations @param violations set of occurred constraint violations @return 400 Bad Request response, containing details on the constraint violations
[ "Helper", "function", "to", "create", "a", "400", "Bad", "Request", "response", "containing", "a", "JSON", "map", "giving", "details", "about", "the", "violations" ]
c7b798f085449117d84345d8c378b27165cad32b
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/AbstractBaseEndpoint.java#L86-L92
train
google/closure-templates
java/src/com/google/template/soy/parsepasses/contextautoesc/InferenceEngine.java
InferenceEngine.checkBlockEndContext
private static void checkBlockEndContext(RenderUnitNode node, Context endContext) { if (!endContext.isValidEndContextForContentKind( MoreObjects.firstNonNull(node.getContentKind(), SanitizedContentKind.HTML))) { String msg = String.format( "A block of kind=\"%s\" cannot end in context %s. Likely cause is %s.", node.getContentKind().asAttributeValue(), endContext, endContext.getLikelyEndContextMismatchCause(node.getContentKind())); throw SoyAutoescapeException.createWithNode(msg, node); } }
java
private static void checkBlockEndContext(RenderUnitNode node, Context endContext) { if (!endContext.isValidEndContextForContentKind( MoreObjects.firstNonNull(node.getContentKind(), SanitizedContentKind.HTML))) { String msg = String.format( "A block of kind=\"%s\" cannot end in context %s. Likely cause is %s.", node.getContentKind().asAttributeValue(), endContext, endContext.getLikelyEndContextMismatchCause(node.getContentKind())); throw SoyAutoescapeException.createWithNode(msg, node); } }
[ "private", "static", "void", "checkBlockEndContext", "(", "RenderUnitNode", "node", ",", "Context", "endContext", ")", "{", "if", "(", "!", "endContext", ".", "isValidEndContextForContentKind", "(", "MoreObjects", ".", "firstNonNull", "(", "node", ".", "getContentKi...
Checks that the end context of a block is compatible with its start context. @throws SoyAutoescapeException if they mismatch.
[ "Checks", "that", "the", "end", "context", "of", "a", "block", "is", "compatible", "with", "its", "start", "context", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/InferenceEngine.java#L113-L124
train
google/closure-templates
java/src/com/google/template/soy/parsepasses/contextautoesc/InferenceEngine.java
InferenceEngine.inferStrictRenderUnitNode
static void inferStrictRenderUnitNode( RenderUnitNode node, Inferences inferences, ErrorReporter errorReporter) { InferenceEngine inferenceEngine = new InferenceEngine(inferences, errorReporter); // Context started off as startContext and we have propagated context through all of // node's children, so now context is the node's end context. Context endContext = inferenceEngine.inferChildren( node, Context.getStartContextForContentKind(node.getContentKind())); // Checking that start and end context is same. checkBlockEndContext(node, endContext); }
java
static void inferStrictRenderUnitNode( RenderUnitNode node, Inferences inferences, ErrorReporter errorReporter) { InferenceEngine inferenceEngine = new InferenceEngine(inferences, errorReporter); // Context started off as startContext and we have propagated context through all of // node's children, so now context is the node's end context. Context endContext = inferenceEngine.inferChildren( node, Context.getStartContextForContentKind(node.getContentKind())); // Checking that start and end context is same. checkBlockEndContext(node, endContext); }
[ "static", "void", "inferStrictRenderUnitNode", "(", "RenderUnitNode", "node", ",", "Inferences", "inferences", ",", "ErrorReporter", "errorReporter", ")", "{", "InferenceEngine", "inferenceEngine", "=", "new", "InferenceEngine", "(", "inferences", ",", "errorReporter", ...
Applies strict contextual autoescaping to the given node's children. <p>The start context is the given node's declared {@link ContentKind}, and it is enforced that the block's inferred end context matches the start context. <p>This method is used to visit the content of {let} and {param} nodes with a {@code kind} attribute.
[ "Applies", "strict", "contextual", "autoescaping", "to", "the", "given", "node", "s", "children", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/parsepasses/contextautoesc/InferenceEngine.java#L135-L145
train
google/closure-templates
java/src/com/google/template/soy/i18ndirectives/FormatNumDirective.java
FormatNumDirective.parseFormat
private static String parseFormat(List<? extends TargetExpr> args) { String numberFormatType = !args.isEmpty() ? args.get(0).getText() : "'" + DEFAULT_FORMAT + "'"; if (!JS_ARGS_TO_ENUM.containsKey(numberFormatType)) { String validKeys = Joiner.on("', '").join(JS_ARGS_TO_ENUM.keySet()); throw new IllegalArgumentException( "First argument to formatNum must be constant, and one of: '" + validKeys + "'."); } return numberFormatType; }
java
private static String parseFormat(List<? extends TargetExpr> args) { String numberFormatType = !args.isEmpty() ? args.get(0).getText() : "'" + DEFAULT_FORMAT + "'"; if (!JS_ARGS_TO_ENUM.containsKey(numberFormatType)) { String validKeys = Joiner.on("', '").join(JS_ARGS_TO_ENUM.keySet()); throw new IllegalArgumentException( "First argument to formatNum must be constant, and one of: '" + validKeys + "'."); } return numberFormatType; }
[ "private", "static", "String", "parseFormat", "(", "List", "<", "?", "extends", "TargetExpr", ">", "args", ")", "{", "String", "numberFormatType", "=", "!", "args", ".", "isEmpty", "(", ")", "?", "args", ".", "get", "(", "0", ")", ".", "getText", "(", ...
Validates that the provided format matches a supported format, and returns the value, if not, this throws an exception. @param args The list of provided arguments. @return String The number format type.
[ "Validates", "that", "the", "provided", "format", "matches", "a", "supported", "format", "and", "returns", "the", "value", "if", "not", "this", "throws", "an", "exception", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/i18ndirectives/FormatNumDirective.java#L245-L255
train
google/closure-templates
java/src/com/google/template/soy/data/SoyProtoValue.java
SoyProtoValue.clazz
private ProtoClass clazz() { ProtoClass localClazz = clazz; if (localClazz == null) { localClazz = classCache.getUnchecked(proto.getDescriptorForType()); clazz = localClazz; } return localClazz; }
java
private ProtoClass clazz() { ProtoClass localClazz = clazz; if (localClazz == null) { localClazz = classCache.getUnchecked(proto.getDescriptorForType()); clazz = localClazz; } return localClazz; }
[ "private", "ProtoClass", "clazz", "(", ")", "{", "ProtoClass", "localClazz", "=", "clazz", ";", "if", "(", "localClazz", "==", "null", ")", "{", "localClazz", "=", "classCache", ".", "getUnchecked", "(", "proto", ".", "getDescriptorForType", "(", ")", ")", ...
it if we can
[ "it", "if", "we", "can" ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyProtoValue.java#L205-L212
train
google/closure-templates
java/src/com/google/template/soy/data/SoyProtoValue.java
SoyProtoValue.getProtoField
public SoyValue getProtoField(String name) { FieldWithInterpreter field = clazz().fields.get(name); if (field == null) { throw new IllegalArgumentException( "Proto " + proto.getClass().getName() + " does not have a field of name " + name); } if (field.shouldCheckFieldPresenceToEmulateJspbNullability() && !proto.hasField(field.getDescriptor())) { return NullData.INSTANCE; } return field.interpretField(proto); }
java
public SoyValue getProtoField(String name) { FieldWithInterpreter field = clazz().fields.get(name); if (field == null) { throw new IllegalArgumentException( "Proto " + proto.getClass().getName() + " does not have a field of name " + name); } if (field.shouldCheckFieldPresenceToEmulateJspbNullability() && !proto.hasField(field.getDescriptor())) { return NullData.INSTANCE; } return field.interpretField(proto); }
[ "public", "SoyValue", "getProtoField", "(", "String", "name", ")", "{", "FieldWithInterpreter", "field", "=", "clazz", "(", ")", ".", "fields", ".", "get", "(", "name", ")", ";", "if", "(", "field", "==", "null", ")", "{", "throw", "new", "IllegalArgumen...
Gets a value for the field for the underlying proto object. Not intended for general use. @param name The proto field name. @return The value of the given field for the underlying proto object, or NullData if either the field does not exist or the value is not set in the underlying proto (according to the jspb semantics)
[ "Gets", "a", "value", "for", "the", "field", "for", "the", "underlying", "proto", "object", ".", "Not", "intended", "for", "general", "use", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyProtoValue.java#L227-L238
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/Field.java
Field.getFieldsForType
public static <T extends Field> ImmutableMap<String, T> getFieldsForType( Descriptor descriptor, Set<FieldDescriptor> extensions, Factory<T> factory) { ImmutableMap.Builder<String, T> fields = ImmutableMap.builder(); for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { if (ProtoUtils.shouldJsIgnoreField(fieldDescriptor)) { continue; } T field = factory.create(fieldDescriptor); fields.put(field.getName(), field); } SetMultimap<String, T> extensionsBySoyName = MultimapBuilder.hashKeys().hashSetValues().build(); for (FieldDescriptor extension : extensions) { T field = factory.create(extension); extensionsBySoyName.put(field.getName(), field); } for (Map.Entry<String, Set<T>> group : Multimaps.asMap(extensionsBySoyName).entrySet()) { Set<T> ambiguousFields = group.getValue(); String fieldName = group.getKey(); if (ambiguousFields.size() == 1) { fields.put(fieldName, Iterables.getOnlyElement(ambiguousFields)); } else { T value = factory.createAmbiguousFieldSet(ambiguousFields); logger.severe( "Proto " + descriptor.getFullName() + " has multiple extensions with the name \"" + fieldName + "\": " + fullFieldNames(ambiguousFields) + "\nThis field will not be accessible from soy"); fields.put(fieldName, value); } } return fields.build(); }
java
public static <T extends Field> ImmutableMap<String, T> getFieldsForType( Descriptor descriptor, Set<FieldDescriptor> extensions, Factory<T> factory) { ImmutableMap.Builder<String, T> fields = ImmutableMap.builder(); for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { if (ProtoUtils.shouldJsIgnoreField(fieldDescriptor)) { continue; } T field = factory.create(fieldDescriptor); fields.put(field.getName(), field); } SetMultimap<String, T> extensionsBySoyName = MultimapBuilder.hashKeys().hashSetValues().build(); for (FieldDescriptor extension : extensions) { T field = factory.create(extension); extensionsBySoyName.put(field.getName(), field); } for (Map.Entry<String, Set<T>> group : Multimaps.asMap(extensionsBySoyName).entrySet()) { Set<T> ambiguousFields = group.getValue(); String fieldName = group.getKey(); if (ambiguousFields.size() == 1) { fields.put(fieldName, Iterables.getOnlyElement(ambiguousFields)); } else { T value = factory.createAmbiguousFieldSet(ambiguousFields); logger.severe( "Proto " + descriptor.getFullName() + " has multiple extensions with the name \"" + fieldName + "\": " + fullFieldNames(ambiguousFields) + "\nThis field will not be accessible from soy"); fields.put(fieldName, value); } } return fields.build(); }
[ "public", "static", "<", "T", "extends", "Field", ">", "ImmutableMap", "<", "String", ",", "T", ">", "getFieldsForType", "(", "Descriptor", "descriptor", ",", "Set", "<", "FieldDescriptor", ">", "extensions", ",", "Factory", "<", "T", ">", "factory", ")", ...
Returns the set of fields indexed by soy accessor name for the given type.
[ "Returns", "the", "set", "of", "fields", "indexed", "by", "soy", "accessor", "name", "for", "the", "given", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/Field.java#L57-L94
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcValueFactory.java
JbcSrcValueFactory.soyTypeForProtoOrEnum
private Optional<SoyType> soyTypeForProtoOrEnum(Class<?> type, Method method) { // Message isn't supported because we can't get a descriptor from it. if (type == Message.class) { reporter.invalidReturnType(Message.class, method); return Optional.absent(); } Optional<String> fullName = nameFromDescriptor(type); if (!fullName.isPresent()) { reporter.incompatibleReturnType(type, method); return Optional.absent(); } SoyType returnType = registry.getType(fullName.get()); if (returnType == null) { reporter.incompatibleReturnType(type, method); return Optional.absent(); } return Optional.of(returnType); }
java
private Optional<SoyType> soyTypeForProtoOrEnum(Class<?> type, Method method) { // Message isn't supported because we can't get a descriptor from it. if (type == Message.class) { reporter.invalidReturnType(Message.class, method); return Optional.absent(); } Optional<String> fullName = nameFromDescriptor(type); if (!fullName.isPresent()) { reporter.incompatibleReturnType(type, method); return Optional.absent(); } SoyType returnType = registry.getType(fullName.get()); if (returnType == null) { reporter.incompatibleReturnType(type, method); return Optional.absent(); } return Optional.of(returnType); }
[ "private", "Optional", "<", "SoyType", ">", "soyTypeForProtoOrEnum", "(", "Class", "<", "?", ">", "type", ",", "Method", "method", ")", "{", "// Message isn't supported because we can't get a descriptor from it.", "if", "(", "type", "==", "Message", ".", "class", ")...
Attempts to discover the SoyType for a proto or proto enum, reporting an error if unable to.
[ "Attempts", "to", "discover", "the", "SoyType", "for", "a", "proto", "or", "proto", "enum", "reporting", "an", "error", "if", "unable", "to", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcValueFactory.java#L720-L737
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/JbcSrcValueFactory.java
JbcSrcValueFactory.isOrContains
private boolean isOrContains(SoyType type, SoyType.Kind kind) { if (type.getKind() == kind) { return true; } if (type.getKind() == SoyType.Kind.UNION) { for (SoyType member : ((UnionType) type).getMembers()) { if (member.getKind() == kind) { return true; } } } return false; }
java
private boolean isOrContains(SoyType type, SoyType.Kind kind) { if (type.getKind() == kind) { return true; } if (type.getKind() == SoyType.Kind.UNION) { for (SoyType member : ((UnionType) type).getMembers()) { if (member.getKind() == kind) { return true; } } } return false; }
[ "private", "boolean", "isOrContains", "(", "SoyType", "type", ",", "SoyType", ".", "Kind", "kind", ")", "{", "if", "(", "type", ".", "getKind", "(", ")", "==", "kind", ")", "{", "return", "true", ";", "}", "if", "(", "type", ".", "getKind", "(", ")...
Returns true if the type is the given kind or contains the given kind.
[ "Returns", "true", "if", "the", "type", "is", "the", "given", "kind", "or", "contains", "the", "given", "kind", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/JbcSrcValueFactory.java#L740-L752
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java
JavaQualifiedNames.getFieldName
public static String getFieldName( Descriptors.FieldDescriptor field, boolean capitializeFirstLetter) { String fieldName = field.getName(); if (SPECIAL_CASES.containsKey(fieldName)) { String output = SPECIAL_CASES.get(fieldName); if (capitializeFirstLetter) { return output; } else { return ((char) (output.charAt(0) + ('a' - 'A'))) + output.substring(1); } } return underscoresToCamelCase(fieldName, capitializeFirstLetter); }
java
public static String getFieldName( Descriptors.FieldDescriptor field, boolean capitializeFirstLetter) { String fieldName = field.getName(); if (SPECIAL_CASES.containsKey(fieldName)) { String output = SPECIAL_CASES.get(fieldName); if (capitializeFirstLetter) { return output; } else { return ((char) (output.charAt(0) + ('a' - 'A'))) + output.substring(1); } } return underscoresToCamelCase(fieldName, capitializeFirstLetter); }
[ "public", "static", "String", "getFieldName", "(", "Descriptors", ".", "FieldDescriptor", "field", ",", "boolean", "capitializeFirstLetter", ")", "{", "String", "fieldName", "=", "field", ".", "getName", "(", ")", ";", "if", "(", "SPECIAL_CASES", ".", "containsK...
Returns the Java name for a proto field.
[ "Returns", "the", "Java", "name", "for", "a", "proto", "field", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java#L137-L149
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java
JavaQualifiedNames.underscoresToCamelCase
public static String underscoresToCamelCase(String input, boolean capitializeNextLetter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if ('a' <= ch && ch <= 'z') { if (capitializeNextLetter) { result.append((char) (ch + ('A' - 'a'))); } else { result.append(ch); } capitializeNextLetter = false; } else if ('A' <= ch && ch <= 'Z') { if (i == 0 && !capitializeNextLetter) { // Force first letter to lower-case unless explicitly told to // capitalize it. result.append((char) (ch + ('a' - 'A'))); } else { // Capital letters after the first are left as-is. result.append(ch); } capitializeNextLetter = false; } else if ('0' <= ch && ch <= '9') { result.append(ch); capitializeNextLetter = true; } else { capitializeNextLetter = true; } } return result.toString(); }
java
public static String underscoresToCamelCase(String input, boolean capitializeNextLetter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if ('a' <= ch && ch <= 'z') { if (capitializeNextLetter) { result.append((char) (ch + ('A' - 'a'))); } else { result.append(ch); } capitializeNextLetter = false; } else if ('A' <= ch && ch <= 'Z') { if (i == 0 && !capitializeNextLetter) { // Force first letter to lower-case unless explicitly told to // capitalize it. result.append((char) (ch + ('a' - 'A'))); } else { // Capital letters after the first are left as-is. result.append(ch); } capitializeNextLetter = false; } else if ('0' <= ch && ch <= '9') { result.append(ch); capitializeNextLetter = true; } else { capitializeNextLetter = true; } } return result.toString(); }
[ "public", "static", "String", "underscoresToCamelCase", "(", "String", "input", ",", "boolean", "capitializeNextLetter", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "input"...
Converts underscore field names to camel case, while preserving camel case field names.
[ "Converts", "underscore", "field", "names", "to", "camel", "case", "while", "preserving", "camel", "case", "field", "names", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java#L160-L189
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java
JavaQualifiedNames.hasConflictingClassName
private static boolean hasConflictingClassName(DescriptorProto messageDesc, String name) { if (name.equals(messageDesc.getName())) { return true; } for (EnumDescriptorProto enumDesc : messageDesc.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (DescriptorProto nestedMessageDesc : messageDesc.getNestedTypeList()) { if (hasConflictingClassName(nestedMessageDesc, name)) { return true; } } return false; }
java
private static boolean hasConflictingClassName(DescriptorProto messageDesc, String name) { if (name.equals(messageDesc.getName())) { return true; } for (EnumDescriptorProto enumDesc : messageDesc.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (DescriptorProto nestedMessageDesc : messageDesc.getNestedTypeList()) { if (hasConflictingClassName(nestedMessageDesc, name)) { return true; } } return false; }
[ "private", "static", "boolean", "hasConflictingClassName", "(", "DescriptorProto", "messageDesc", ",", "String", "name", ")", "{", "if", "(", "name", ".", "equals", "(", "messageDesc", ".", "getName", "(", ")", ")", ")", "{", "return", "true", ";", "}", "f...
Used by the other overload, descends recursively into messages.
[ "Used", "by", "the", "other", "overload", "descends", "recursively", "into", "messages", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java#L298-L313
train
google/closure-templates
java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java
JavaQualifiedNames.hasConflictingClassName
private static boolean hasConflictingClassName(FileDescriptorProto file, String name) { for (EnumDescriptorProto enumDesc : file.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (ServiceDescriptorProto serviceDesc : file.getServiceList()) { if (name.equals(serviceDesc.getName())) { return true; } } for (DescriptorProto messageDesc : file.getMessageTypeList()) { if (hasConflictingClassName(messageDesc, name)) { return true; } } return false; }
java
private static boolean hasConflictingClassName(FileDescriptorProto file, String name) { for (EnumDescriptorProto enumDesc : file.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (ServiceDescriptorProto serviceDesc : file.getServiceList()) { if (name.equals(serviceDesc.getName())) { return true; } } for (DescriptorProto messageDesc : file.getMessageTypeList()) { if (hasConflictingClassName(messageDesc, name)) { return true; } } return false; }
[ "private", "static", "boolean", "hasConflictingClassName", "(", "FileDescriptorProto", "file", ",", "String", "name", ")", "{", "for", "(", "EnumDescriptorProto", "enumDesc", ":", "file", ".", "getEnumTypeList", "(", ")", ")", "{", "if", "(", "name", ".", "equ...
Checks whether any generated classes conflict with the given name.
[ "Checks", "whether", "any", "generated", "classes", "conflict", "with", "the", "given", "name", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java#L316-L333
train
google/closure-templates
java/src/com/google/template/soy/data/restricted/IntegerData.java
IntegerData.forValue
public static IntegerData forValue(long value) { if (value > 10 || value < -1) { return new IntegerData(value); } switch ((int) value) { case -1: return MINUS_ONE; case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case 8: return EIGHT; case 9: return NINE; case 10: return TEN; default: throw new AssertionError("Impossible case"); } }
java
public static IntegerData forValue(long value) { if (value > 10 || value < -1) { return new IntegerData(value); } switch ((int) value) { case -1: return MINUS_ONE; case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case 8: return EIGHT; case 9: return NINE; case 10: return TEN; default: throw new AssertionError("Impossible case"); } }
[ "public", "static", "IntegerData", "forValue", "(", "long", "value", ")", "{", "if", "(", "value", ">", "10", "||", "value", "<", "-", "1", ")", "{", "return", "new", "IntegerData", "(", "value", ")", ";", "}", "switch", "(", "(", "int", ")", "valu...
Gets a IntegerData instance for the given value. @param value The desired value. @return A IntegerData instance with the given value.
[ "Gets", "a", "IntegerData", "instance", "for", "the", "given", "value", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/restricted/IntegerData.java#L82-L114
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.exec
PyExpr exec(CallNode callNode, LocalVariableStack localVarStack, ErrorReporter errorReporter) { this.localVarStack = localVarStack; this.errorReporter = errorReporter; PyExpr callExpr = visit(callNode); this.localVarStack = null; this.errorReporter = null; return callExpr; }
java
PyExpr exec(CallNode callNode, LocalVariableStack localVarStack, ErrorReporter errorReporter) { this.localVarStack = localVarStack; this.errorReporter = errorReporter; PyExpr callExpr = visit(callNode); this.localVarStack = null; this.errorReporter = null; return callExpr; }
[ "PyExpr", "exec", "(", "CallNode", "callNode", ",", "LocalVariableStack", "localVarStack", ",", "ErrorReporter", "errorReporter", ")", "{", "this", ".", "localVarStack", "=", "localVarStack", ";", "this", ".", "errorReporter", "=", "errorReporter", ";", "PyExpr", ...
Generates the Python expression for a given call. <p>Important: If there are CallParamContentNode children whose contents are not computable as Python expressions, then this function assumes that, elsewhere, code has been generated to define their respective {@code param<n>} temporary variables. <p>Here are five example calls: <pre> {call some.func data="all" /} {call some.func data="$boo" /} {call some.func} {param goo = $moo /} {/call} {call some.func data="$boo"} {param goo}Blah{/param} {/call} {call some.func} {param goo} {for $i in range(3)}{$i}{/for} {/param} {/call} </pre> Their respective generated calls might be the following: <pre> some.func(data) some.func(data.get('boo')) some.func({'goo': opt_data.get('moo')}) some.func(runtime.merge_into_dict({'goo': 'Blah'}, data.get('boo'))) some.func({'goo': param65}) </pre> Note that in the last case, the param content is not computable as Python expressions, so we assume that code has been generated to define the temporary variable {@code param<n>}. @param callNode The call to generate code for. @param localVarStack The current stack of replacement Python expressions for the local variables (and foreach-loop special functions) current in scope. @return The Python expression for the call.
[ "Generates", "the", "Python", "expression", "for", "a", "given", "call", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L114-L121
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.visitCallBasicNode
@Override protected PyExpr visitCallBasicNode(CallBasicNode node) { String calleeName = node.getCalleeName(); // Build the Python expr text for the callee. String calleeExprText; TemplateNode template = getTemplateIfInSameFile(node); if (template != null) { // If in the same module no namespace is required. calleeExprText = getLocalTemplateName(template); } else { // If in another module, the module name is required along with the function name. int secondToLastDotIndex = calleeName.lastIndexOf('.', calleeName.lastIndexOf('.') - 1); calleeExprText = calleeName.substring(secondToLastDotIndex + 1); } String callExprText = calleeExprText + "(" + genObjToPass(node) + ", ijData)"; return escapeCall(callExprText, node.getEscapingDirectives()); }
java
@Override protected PyExpr visitCallBasicNode(CallBasicNode node) { String calleeName = node.getCalleeName(); // Build the Python expr text for the callee. String calleeExprText; TemplateNode template = getTemplateIfInSameFile(node); if (template != null) { // If in the same module no namespace is required. calleeExprText = getLocalTemplateName(template); } else { // If in another module, the module name is required along with the function name. int secondToLastDotIndex = calleeName.lastIndexOf('.', calleeName.lastIndexOf('.') - 1); calleeExprText = calleeName.substring(secondToLastDotIndex + 1); } String callExprText = calleeExprText + "(" + genObjToPass(node) + ", ijData)"; return escapeCall(callExprText, node.getEscapingDirectives()); }
[ "@", "Override", "protected", "PyExpr", "visitCallBasicNode", "(", "CallBasicNode", "node", ")", "{", "String", "calleeName", "=", "node", ".", "getCalleeName", "(", ")", ";", "// Build the Python expr text for the callee.", "String", "calleeExprText", ";", "TemplateNod...
Visits basic call nodes and builds the call expression. If the callee is in the file, it can be accessed directly, but if it's in another file, the module name must be prefixed. @param node The basic call node. @return The call Python expression.
[ "Visits", "basic", "call", "nodes", "and", "builds", "the", "call", "expression", ".", "If", "the", "callee", "is", "in", "the", "file", "it", "can", "be", "accessed", "directly", "but", "if", "it", "s", "in", "another", "file", "the", "module", "name", ...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L130-L148
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.visitCallDelegateNode
@Override protected PyExpr visitCallDelegateNode(CallDelegateNode node) { ExprRootNode variantSoyExpr = node.getDelCalleeVariantExpr(); PyExpr variantPyExpr; if (variantSoyExpr == null) { // Case 1: Delegate call with empty variant. variantPyExpr = new PyStringExpr("''"); } else { // Case 2: Delegate call with variant expression. TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor(localVarStack, pluginValueFactory, errorReporter); variantPyExpr = translator.exec(variantSoyExpr); } String calleeExprText = new PyFunctionExprBuilder("runtime.get_delegate_fn") .addArg(node.getDelCalleeName()) .addArg(variantPyExpr) .addArg(node.allowEmptyDefault()) .build(); String callExprText = calleeExprText + "(" + genObjToPass(node) + ", ijData)"; return escapeCall(callExprText, node.getEscapingDirectives()); }
java
@Override protected PyExpr visitCallDelegateNode(CallDelegateNode node) { ExprRootNode variantSoyExpr = node.getDelCalleeVariantExpr(); PyExpr variantPyExpr; if (variantSoyExpr == null) { // Case 1: Delegate call with empty variant. variantPyExpr = new PyStringExpr("''"); } else { // Case 2: Delegate call with variant expression. TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor(localVarStack, pluginValueFactory, errorReporter); variantPyExpr = translator.exec(variantSoyExpr); } String calleeExprText = new PyFunctionExprBuilder("runtime.get_delegate_fn") .addArg(node.getDelCalleeName()) .addArg(variantPyExpr) .addArg(node.allowEmptyDefault()) .build(); String callExprText = calleeExprText + "(" + genObjToPass(node) + ", ijData)"; return escapeCall(callExprText, node.getEscapingDirectives()); }
[ "@", "Override", "protected", "PyExpr", "visitCallDelegateNode", "(", "CallDelegateNode", "node", ")", "{", "ExprRootNode", "variantSoyExpr", "=", "node", ".", "getDelCalleeVariantExpr", "(", ")", ";", "PyExpr", "variantPyExpr", ";", "if", "(", "variantSoyExpr", "==...
Visits a delegate call node and builds the call expression to retrieve the function and execute it. The get_delegate_fn returns the function directly, so its output can be called directly. @param node The delegate call node. @return The call Python expression.
[ "Visits", "a", "delegate", "call", "node", "and", "builds", "the", "call", "expression", "to", "retrieve", "the", "function", "and", "execute", "it", ".", "The", "get_delegate_fn", "returns", "the", "function", "directly", "so", "its", "output", "can", "be", ...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L157-L179
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.genObjToPass
public String genObjToPass(CallNode callNode) { TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor(localVarStack, pluginValueFactory, errorReporter); // Generate the expression for the original data to pass. String dataToPass; if (callNode.isPassingAllData()) { dataToPass = "data"; } else if (callNode.isPassingData()) { dataToPass = translator.exec(callNode.getDataExpr()).getText(); } else { dataToPass = "{}"; } // Build an object literal containing the additional params. Map<PyExpr, PyExpr> additionalParams = new LinkedHashMap<>(); for (CallParamNode child : callNode.getChildren()) { PyExpr key = new PyStringExpr("'" + child.getKey().identifier() + "'"); if (child instanceof CallParamValueNode) { CallParamValueNode cpvn = (CallParamValueNode) child; additionalParams.put(key, translator.exec(cpvn.getExpr())); } else { CallParamContentNode cpcn = (CallParamContentNode) child; PyExpr valuePyExpr; if (isComputableAsPyExprVisitor.exec(cpcn)) { valuePyExpr = PyExprUtils.concatPyExprs( genPyExprsVisitorFactory.create(localVarStack, errorReporter).exec(cpcn)); } else { // This is a param with content that cannot be represented as Python expressions, so we // assume that code has been generated to define the temporary variable 'param<n>'. String paramExpr = "param" + cpcn.getId(); // The param can be assumed to be a list at this point since it was created as an output // variable. valuePyExpr = new PyListExpr(paramExpr, Integer.MAX_VALUE); } // Param content nodes require a content kind in strict autoescaping, so the content must be // wrapped as SanitizedContent. valuePyExpr = InternalPyExprUtils.wrapAsSanitizedContent( cpcn.getContentKind(), valuePyExpr.toPyString()); additionalParams.put(key, valuePyExpr); } } Map<PyExpr, PyExpr> defaultParams = new LinkedHashMap<>(); for (TemplateParam param : callNode.getNearestAncestor(TemplateNode.class).getParams()) { if (param.hasDefault()) { defaultParams.put( new PyStringExpr("'" + param.name() + "'"), translator.exec(param.defaultValue())); } } PyExpr additionalParamsExpr = PyExprUtils.convertMapToPyExpr(additionalParams); // Cases 2 and 3: Additional params with and without original data to pass. if (callNode.isPassingData()) { if (callNode.numChildren() > 0) { // make a shallow copy so we don't accidentally modify the param dataToPass = "dict(" + dataToPass + ")"; dataToPass = "runtime.merge_into_dict(" + dataToPass + ", " + additionalParamsExpr.getText() + ")"; } if (!defaultParams.isEmpty()) { // If there are default parameters, merge the data we have so far into a dict of the default // parameters. This will override the parameter defaults with actual values (if there are // actual values). PyExpr defaultParamsExpr = PyExprUtils.convertMapToPyExpr(defaultParams); dataToPass = "runtime.merge_into_dict(" + defaultParamsExpr.getText() + ", " + dataToPass + ")"; } return dataToPass; } else { return additionalParamsExpr.getText(); } }
java
public String genObjToPass(CallNode callNode) { TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor(localVarStack, pluginValueFactory, errorReporter); // Generate the expression for the original data to pass. String dataToPass; if (callNode.isPassingAllData()) { dataToPass = "data"; } else if (callNode.isPassingData()) { dataToPass = translator.exec(callNode.getDataExpr()).getText(); } else { dataToPass = "{}"; } // Build an object literal containing the additional params. Map<PyExpr, PyExpr> additionalParams = new LinkedHashMap<>(); for (CallParamNode child : callNode.getChildren()) { PyExpr key = new PyStringExpr("'" + child.getKey().identifier() + "'"); if (child instanceof CallParamValueNode) { CallParamValueNode cpvn = (CallParamValueNode) child; additionalParams.put(key, translator.exec(cpvn.getExpr())); } else { CallParamContentNode cpcn = (CallParamContentNode) child; PyExpr valuePyExpr; if (isComputableAsPyExprVisitor.exec(cpcn)) { valuePyExpr = PyExprUtils.concatPyExprs( genPyExprsVisitorFactory.create(localVarStack, errorReporter).exec(cpcn)); } else { // This is a param with content that cannot be represented as Python expressions, so we // assume that code has been generated to define the temporary variable 'param<n>'. String paramExpr = "param" + cpcn.getId(); // The param can be assumed to be a list at this point since it was created as an output // variable. valuePyExpr = new PyListExpr(paramExpr, Integer.MAX_VALUE); } // Param content nodes require a content kind in strict autoescaping, so the content must be // wrapped as SanitizedContent. valuePyExpr = InternalPyExprUtils.wrapAsSanitizedContent( cpcn.getContentKind(), valuePyExpr.toPyString()); additionalParams.put(key, valuePyExpr); } } Map<PyExpr, PyExpr> defaultParams = new LinkedHashMap<>(); for (TemplateParam param : callNode.getNearestAncestor(TemplateNode.class).getParams()) { if (param.hasDefault()) { defaultParams.put( new PyStringExpr("'" + param.name() + "'"), translator.exec(param.defaultValue())); } } PyExpr additionalParamsExpr = PyExprUtils.convertMapToPyExpr(additionalParams); // Cases 2 and 3: Additional params with and without original data to pass. if (callNode.isPassingData()) { if (callNode.numChildren() > 0) { // make a shallow copy so we don't accidentally modify the param dataToPass = "dict(" + dataToPass + ")"; dataToPass = "runtime.merge_into_dict(" + dataToPass + ", " + additionalParamsExpr.getText() + ")"; } if (!defaultParams.isEmpty()) { // If there are default parameters, merge the data we have so far into a dict of the default // parameters. This will override the parameter defaults with actual values (if there are // actual values). PyExpr defaultParamsExpr = PyExprUtils.convertMapToPyExpr(defaultParams); dataToPass = "runtime.merge_into_dict(" + defaultParamsExpr.getText() + ", " + dataToPass + ")"; } return dataToPass; } else { return additionalParamsExpr.getText(); } }
[ "public", "String", "genObjToPass", "(", "CallNode", "callNode", ")", "{", "TranslateToPyExprVisitor", "translator", "=", "new", "TranslateToPyExprVisitor", "(", "localVarStack", ",", "pluginValueFactory", ",", "errorReporter", ")", ";", "// Generate the expression for the ...
Generates the Python expression for the object to pass in a given call. This expression will be a combination of passed data and additional content params. If both are passed, they'll be combined into one dictionary. @param callNode The call to generate code for. @return The Python expression for the object to pass in the call.
[ "Generates", "the", "Python", "expression", "for", "the", "object", "to", "pass", "in", "a", "given", "call", ".", "This", "expression", "will", "be", "a", "combination", "of", "passed", "data", "and", "additional", "content", "params", ".", "If", "both", ...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L189-L270
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.escapeCall
private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) { PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE); if (directives.isEmpty()) { return escapedExpr; } // Successively wrap each escapedExpr in various directives. for (SoyPrintDirective directive : directives) { Preconditions.checkState( directive instanceof SoyPySrcPrintDirective, "Autoescaping produced a bogus directive: %s", directive.getName()); escapedExpr = ((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of()); } return escapedExpr; }
java
private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) { PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE); if (directives.isEmpty()) { return escapedExpr; } // Successively wrap each escapedExpr in various directives. for (SoyPrintDirective directive : directives) { Preconditions.checkState( directive instanceof SoyPySrcPrintDirective, "Autoescaping produced a bogus directive: %s", directive.getName()); escapedExpr = ((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of()); } return escapedExpr; }
[ "private", "PyExpr", "escapeCall", "(", "String", "callExpr", ",", "ImmutableList", "<", "SoyPrintDirective", ">", "directives", ")", "{", "PyExpr", "escapedExpr", "=", "new", "PyExpr", "(", "callExpr", ",", "Integer", ".", "MAX_VALUE", ")", ";", "if", "(", ...
Escaping directives might apply to the output of the call node, so wrap the output with all required directives. @param callExpr The expression text of the call itself. @param directives The list of the directives to be applied to the call. @return A PyExpr containing the call expression with all directives applied.
[ "Escaping", "directives", "might", "apply", "to", "the", "output", "of", "the", "call", "node", "so", "wrap", "the", "output", "with", "all", "required", "directives", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L280-L296
train
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java
GenPyCallExprVisitor.getLocalTemplateName
static String getLocalTemplateName(TemplateNode node) { String templateName = node.getPartialTemplateName().substring(1); if (node.getVisibility() == Visibility.PRIVATE) { return "__" + templateName; } return templateName; }
java
static String getLocalTemplateName(TemplateNode node) { String templateName = node.getPartialTemplateName().substring(1); if (node.getVisibility() == Visibility.PRIVATE) { return "__" + templateName; } return templateName; }
[ "static", "String", "getLocalTemplateName", "(", "TemplateNode", "node", ")", "{", "String", "templateName", "=", "node", ".", "getPartialTemplateName", "(", ")", ".", "substring", "(", "1", ")", ";", "if", "(", "node", ".", "getVisibility", "(", ")", "==", ...
Returns the python name for the template. Suitable for calling within the same module.
[ "Returns", "the", "python", "name", "for", "the", "template", ".", "Suitable", "for", "calling", "within", "the", "same", "module", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/GenPyCallExprVisitor.java#L299-L305
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.checkConformance
void checkConformance() { resetErrorReporter(); // to check conformance we only need to run as much as it takes to execute the SoyConformance // pass. parse( passManagerBuilder() // We have to set disableAllTypeChecking to make sure default parameter types don't // break calculating TemplateMetadata objects. This is because SoyConformancePass runs // before ResolveExpressionTypesPass which normally populates the parameter types for // default params. With disableAllTypeChecking set an earlier pass will just set those // types to unknown // TODO(lukes): change the pass continuation mechanism to avoid generating a template // registry if we halt prior to cross template passes. .disableAllTypeChecking() .addPassContinuationRule( SoyConformancePass.class, PassContinuationRule.STOP_AFTER_PASS)); throwIfErrorsPresent(); reportWarnings(); }
java
void checkConformance() { resetErrorReporter(); // to check conformance we only need to run as much as it takes to execute the SoyConformance // pass. parse( passManagerBuilder() // We have to set disableAllTypeChecking to make sure default parameter types don't // break calculating TemplateMetadata objects. This is because SoyConformancePass runs // before ResolveExpressionTypesPass which normally populates the parameter types for // default params. With disableAllTypeChecking set an earlier pass will just set those // types to unknown // TODO(lukes): change the pass continuation mechanism to avoid generating a template // registry if we halt prior to cross template passes. .disableAllTypeChecking() .addPassContinuationRule( SoyConformancePass.class, PassContinuationRule.STOP_AFTER_PASS)); throwIfErrorsPresent(); reportWarnings(); }
[ "void", "checkConformance", "(", ")", "{", "resetErrorReporter", "(", ")", ";", "// to check conformance we only need to run as much as it takes to execute the SoyConformance", "// pass.", "parse", "(", "passManagerBuilder", "(", ")", "// We have to set disableAllTypeChecking to make...
A simple tool to enforce conformance and only conformance.
[ "A", "simple", "tool", "to", "enforce", "conformance", "and", "only", "conformance", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L642-L660
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.extractAndWriteMsgs
public void extractAndWriteMsgs( SoyMsgBundleHandler msgBundleHandler, OutputFileOptions options, ByteSink output) throws IOException { resetErrorReporter(); SoyMsgBundle bundle = doExtractMsgs(); msgBundleHandler.writeExtractedMsgs(bundle, options, output, errorReporter); throwIfErrorsPresent(); reportWarnings(); }
java
public void extractAndWriteMsgs( SoyMsgBundleHandler msgBundleHandler, OutputFileOptions options, ByteSink output) throws IOException { resetErrorReporter(); SoyMsgBundle bundle = doExtractMsgs(); msgBundleHandler.writeExtractedMsgs(bundle, options, output, errorReporter); throwIfErrorsPresent(); reportWarnings(); }
[ "public", "void", "extractAndWriteMsgs", "(", "SoyMsgBundleHandler", "msgBundleHandler", ",", "OutputFileOptions", "options", ",", "ByteSink", "output", ")", "throws", "IOException", "{", "resetErrorReporter", "(", ")", ";", "SoyMsgBundle", "bundle", "=", "doExtractMsgs...
Extracts all messages from this Soy file set and writes the messages to an output sink. @param msgBundleHandler Handler to write the messages. @param options Options to configure how to write the extracted messages. @param output Where to write the extracted messages. @throws IOException If there are errors writing to the output.
[ "Extracts", "all", "messages", "from", "this", "Soy", "file", "set", "and", "writes", "the", "messages", "to", "an", "output", "sink", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L684-L692
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.doExtractMsgs
private SoyMsgBundle doExtractMsgs() { // extractMsgs disables a bunch of passes since it is typically not configured with things // like global definitions, type definitions, plugins, etc. SoyFileSetNode soyTree = parse( passManagerBuilder() .allowUnknownGlobals() .allowV1Expression() .setTypeRegistry(SoyTypeRegistry.DEFAULT_UNKNOWN) // TODO(lukes): consider changing this to pass a null resolver instead of the // ALLOW_UNDEFINED mode .setPluginResolver( new PluginResolver( PluginResolver.Mode.ALLOW_UNDEFINED, printDirectives, soyFunctionMap, soySourceFunctionMap, errorReporter)) .disableAllTypeChecking(), // override the type registry so that the parser doesn't report errors when it // can't resolve strict types SoyTypeRegistry.DEFAULT_UNKNOWN) .fileSet(); throwIfErrorsPresent(); SoyMsgBundle bundle = new ExtractMsgsVisitor().exec(soyTree); throwIfErrorsPresent(); return bundle; }
java
private SoyMsgBundle doExtractMsgs() { // extractMsgs disables a bunch of passes since it is typically not configured with things // like global definitions, type definitions, plugins, etc. SoyFileSetNode soyTree = parse( passManagerBuilder() .allowUnknownGlobals() .allowV1Expression() .setTypeRegistry(SoyTypeRegistry.DEFAULT_UNKNOWN) // TODO(lukes): consider changing this to pass a null resolver instead of the // ALLOW_UNDEFINED mode .setPluginResolver( new PluginResolver( PluginResolver.Mode.ALLOW_UNDEFINED, printDirectives, soyFunctionMap, soySourceFunctionMap, errorReporter)) .disableAllTypeChecking(), // override the type registry so that the parser doesn't report errors when it // can't resolve strict types SoyTypeRegistry.DEFAULT_UNKNOWN) .fileSet(); throwIfErrorsPresent(); SoyMsgBundle bundle = new ExtractMsgsVisitor().exec(soyTree); throwIfErrorsPresent(); return bundle; }
[ "private", "SoyMsgBundle", "doExtractMsgs", "(", ")", "{", "// extractMsgs disables a bunch of passes since it is typically not configured with things", "// like global definitions, type definitions, plugins, etc.", "SoyFileSetNode", "soyTree", "=", "parse", "(", "passManagerBuilder", "(...
Performs the parsing and extraction logic.
[ "Performs", "the", "parsing", "and", "extraction", "logic", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L695-L722
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.compileForServerRendering
private ServerCompilationPrimitives compileForServerRendering() { ParseResult result = parse(); throwIfErrorsPresent(); SoyFileSetNode soyTree = result.fileSet(); TemplateRegistry registry = result.registry(); // Clear the SoyDoc strings because they use unnecessary memory, unless we have a cache, in // which case it is pointless. if (cache == null) { new ClearSoyDocStringsVisitor().exec(soyTree); } throwIfErrorsPresent(); return new ServerCompilationPrimitives(registry, soyTree); }
java
private ServerCompilationPrimitives compileForServerRendering() { ParseResult result = parse(); throwIfErrorsPresent(); SoyFileSetNode soyTree = result.fileSet(); TemplateRegistry registry = result.registry(); // Clear the SoyDoc strings because they use unnecessary memory, unless we have a cache, in // which case it is pointless. if (cache == null) { new ClearSoyDocStringsVisitor().exec(soyTree); } throwIfErrorsPresent(); return new ServerCompilationPrimitives(registry, soyTree); }
[ "private", "ServerCompilationPrimitives", "compileForServerRendering", "(", ")", "{", "ParseResult", "result", "=", "parse", "(", ")", ";", "throwIfErrorsPresent", "(", ")", ";", "SoyFileSetNode", "soyTree", "=", "result", ".", "fileSet", "(", ")", ";", "TemplateR...
Runs common compiler logic shared by tofu and jbcsrc backends.
[ "Runs", "common", "compiler", "logic", "shared", "by", "tofu", "and", "jbcsrc", "backends", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L857-L871
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.compileToIncrementalDomSrc
public List<String> compileToIncrementalDomSrc(SoyIncrementalDomSrcOptions jsSrcOptions) { resetErrorReporter(); // For incremental dom backend, we don't desugar HTML nodes since it requires HTML context. ParseResult result = parse(passManagerBuilder().desugarHtmlNodes(false)); throwIfErrorsPresent(); List<String> generatedSrcs = new IncrementalDomSrcMain(scopedData.enterable(), typeRegistry) .genJsSrc(result.fileSet(), result.registry(), jsSrcOptions, errorReporter); throwIfErrorsPresent(); reportWarnings(); return generatedSrcs; }
java
public List<String> compileToIncrementalDomSrc(SoyIncrementalDomSrcOptions jsSrcOptions) { resetErrorReporter(); // For incremental dom backend, we don't desugar HTML nodes since it requires HTML context. ParseResult result = parse(passManagerBuilder().desugarHtmlNodes(false)); throwIfErrorsPresent(); List<String> generatedSrcs = new IncrementalDomSrcMain(scopedData.enterable(), typeRegistry) .genJsSrc(result.fileSet(), result.registry(), jsSrcOptions, errorReporter); throwIfErrorsPresent(); reportWarnings(); return generatedSrcs; }
[ "public", "List", "<", "String", ">", "compileToIncrementalDomSrc", "(", "SoyIncrementalDomSrcOptions", "jsSrcOptions", ")", "{", "resetErrorReporter", "(", ")", ";", "// For incremental dom backend, we don't desugar HTML nodes since it requires HTML context.", "ParseResult", "resu...
Compiles this Soy file set into iDOM source code files and returns these JS files as a list of strings, one per file. @param jsSrcOptions The compilation options for the JS Src output target. @return A list of strings where each string represents the JS source code that belongs in one JS file. The generated JS files correspond one-to-one to the original Soy source files. @throws SoyCompilationException If compilation fails.
[ "Compiles", "this", "Soy", "file", "set", "into", "iDOM", "source", "code", "files", "and", "returns", "these", "JS", "files", "as", "a", "list", "of", "strings", "one", "per", "file", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L927-L938
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.compileToPySrcFiles
void compileToPySrcFiles(String outputPathFormat, SoyPySrcOptions pySrcOptions) throws IOException { resetErrorReporter(); ParseResult result = parse(); throwIfErrorsPresent(); new PySrcMain(scopedData.enterable()) .genPyFiles(result.fileSet(), pySrcOptions, outputPathFormat, errorReporter); throwIfErrorsPresent(); reportWarnings(); }
java
void compileToPySrcFiles(String outputPathFormat, SoyPySrcOptions pySrcOptions) throws IOException { resetErrorReporter(); ParseResult result = parse(); throwIfErrorsPresent(); new PySrcMain(scopedData.enterable()) .genPyFiles(result.fileSet(), pySrcOptions, outputPathFormat, errorReporter); throwIfErrorsPresent(); reportWarnings(); }
[ "void", "compileToPySrcFiles", "(", "String", "outputPathFormat", ",", "SoyPySrcOptions", "pySrcOptions", ")", "throws", "IOException", "{", "resetErrorReporter", "(", ")", ";", "ParseResult", "result", "=", "parse", "(", ")", ";", "throwIfErrorsPresent", "(", ")", ...
Compiles this Soy file set into Python source code files and writes these Python files to disk. @param outputPathFormat The format string defining how to build the output file path corresponding to an input file path. @param pySrcOptions The compilation options for the Python Src output target. @throws SoyCompilationException If compilation fails. @throws IOException If there is an error in opening/reading a message file or opening/writing an output JS file.
[ "Compiles", "this", "Soy", "file", "set", "into", "Python", "source", "code", "files", "and", "writes", "these", "Python", "files", "to", "disk", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L950-L960
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.compileMinimallyForHeaders
ParseResult compileMinimallyForHeaders() { resetErrorReporter(); ParseResult result = parse( passManagerBuilder() // ResolveExpressionTypesPass resolve types (specifically on default parameter // values) which is necessary for template metadatas .addPassContinuationRule( ResolveExpressionTypesPass.class, PassContinuationRule.STOP_AFTER_PASS) .allowV1Expression(), typeRegistry); throwIfErrorsPresent(); reportWarnings(); return result; }
java
ParseResult compileMinimallyForHeaders() { resetErrorReporter(); ParseResult result = parse( passManagerBuilder() // ResolveExpressionTypesPass resolve types (specifically on default parameter // values) which is necessary for template metadatas .addPassContinuationRule( ResolveExpressionTypesPass.class, PassContinuationRule.STOP_AFTER_PASS) .allowV1Expression(), typeRegistry); throwIfErrorsPresent(); reportWarnings(); return result; }
[ "ParseResult", "compileMinimallyForHeaders", "(", ")", "{", "resetErrorReporter", "(", ")", ";", "ParseResult", "result", "=", "parse", "(", "passManagerBuilder", "(", ")", "// ResolveExpressionTypesPass resolve types (specifically on default parameter", "// values) which is nece...
Performs the minimal amount of work needed to calculate TemplateMetadata objects for header compilation.
[ "Performs", "the", "minimal", "amount", "of", "work", "needed", "to", "calculate", "TemplateMetadata", "objects", "for", "header", "compilation", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L966-L981
train
google/closure-templates
java/src/com/google/template/soy/SoyFileSet.java
SoyFileSet.reportWarnings
private void reportWarnings() { ImmutableList<SoyError> warnings = errorReporter.getWarnings(); if (warnings.isEmpty()) { return; } // this is a custom feature used by the integration test suite. if (generalOptions.getExperimentalFeatures().contains("testonly_throw_on_warnings")) { errorReporter = null; throw new SoyCompilationException(warnings); } String formatted = SoyErrors.formatErrors(warnings); if (warningSink != null) { try { warningSink.append(formatted); } catch (IOException ioe) { System.err.println("error while printing warnings"); ioe.printStackTrace(); } } else { logger.warning(formatted); } }
java
private void reportWarnings() { ImmutableList<SoyError> warnings = errorReporter.getWarnings(); if (warnings.isEmpty()) { return; } // this is a custom feature used by the integration test suite. if (generalOptions.getExperimentalFeatures().contains("testonly_throw_on_warnings")) { errorReporter = null; throw new SoyCompilationException(warnings); } String formatted = SoyErrors.formatErrors(warnings); if (warningSink != null) { try { warningSink.append(formatted); } catch (IOException ioe) { System.err.println("error while printing warnings"); ioe.printStackTrace(); } } else { logger.warning(formatted); } }
[ "private", "void", "reportWarnings", "(", ")", "{", "ImmutableList", "<", "SoyError", ">", "warnings", "=", "errorReporter", ".", "getWarnings", "(", ")", ";", "if", "(", "warnings", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "// this is a cus...
Reports warnings ot the user configured warning sink. Should be called at the end of successful compiles.
[ "Reports", "warnings", "ot", "the", "user", "configured", "warning", "sink", ".", "Should", "be", "called", "at", "the", "end", "of", "successful", "compiles", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L1058-L1079
train
google/closure-templates
java/src/com/google/template/soy/msgs/restricted/CompactInterner.java
CompactInterner.intern
@SuppressWarnings("unchecked") // If a.equals(b) then a and b have the same type. public synchronized <T> T intern(T value) { Preconditions.checkNotNull(value); // Use a pseudo-random number generator to mix up the high and low bits of the hash code. Random generator = new java.util.Random(value.hashCode()); int tries = 0; while (true) { int index = generator.nextInt(table.length); Object candidate = table[index]; if (candidate == null) { // Found a good place to hash it. count++; collisions += tries; table[index] = value; rehashIfNeeded(); return value; } if (candidate.equals(value)) { Preconditions.checkArgument( value.getClass() == candidate.getClass(), "Interned objects are equals() but different classes: %s and %s", value, candidate); return (T) candidate; } tries++; } }
java
@SuppressWarnings("unchecked") // If a.equals(b) then a and b have the same type. public synchronized <T> T intern(T value) { Preconditions.checkNotNull(value); // Use a pseudo-random number generator to mix up the high and low bits of the hash code. Random generator = new java.util.Random(value.hashCode()); int tries = 0; while (true) { int index = generator.nextInt(table.length); Object candidate = table[index]; if (candidate == null) { // Found a good place to hash it. count++; collisions += tries; table[index] = value; rehashIfNeeded(); return value; } if (candidate.equals(value)) { Preconditions.checkArgument( value.getClass() == candidate.getClass(), "Interned objects are equals() but different classes: %s and %s", value, candidate); return (T) candidate; } tries++; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// If a.equals(b) then a and b have the same type.", "public", "synchronized", "<", "T", ">", "T", "intern", "(", "T", "value", ")", "{", "Preconditions", ".", "checkNotNull", "(", "value", ")", ";", "// Use a pse...
Returns either the input, or an instance that equals it that was previously passed to this method. <p>This operation performs in amortized constant time.
[ "Returns", "either", "the", "input", "or", "an", "instance", "that", "equals", "it", "that", "was", "previously", "passed", "to", "this", "method", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/CompactInterner.java#L87-L119
train
google/closure-templates
java/src/com/google/template/soy/msgs/restricted/CompactInterner.java
CompactInterner.rehashIfNeeded
@GuardedBy("this") private void rehashIfNeeded() { int currentSize = table.length; if (currentSize - count >= currentSize / (MAX_EXPECTED_COLLISION_COUNT + 1)) { // Still enough overhead. return; } Object[] oldTable = table; // Grow the table so it increases by 1 / GROWTH_DENOMINATOR. int newSize = currentSize + currentSize / GROWTH_DENOMINATOR; table = new Object[newSize]; count = 0; for (Object element : oldTable) { if (element != null) { intern(element); } } }
java
@GuardedBy("this") private void rehashIfNeeded() { int currentSize = table.length; if (currentSize - count >= currentSize / (MAX_EXPECTED_COLLISION_COUNT + 1)) { // Still enough overhead. return; } Object[] oldTable = table; // Grow the table so it increases by 1 / GROWTH_DENOMINATOR. int newSize = currentSize + currentSize / GROWTH_DENOMINATOR; table = new Object[newSize]; count = 0; for (Object element : oldTable) { if (element != null) { intern(element); } } }
[ "@", "GuardedBy", "(", "\"this\"", ")", "private", "void", "rehashIfNeeded", "(", ")", "{", "int", "currentSize", "=", "table", ".", "length", ";", "if", "(", "currentSize", "-", "count", ">=", "currentSize", "/", "(", "MAX_EXPECTED_COLLISION_COUNT", "+", "1...
Doubles the table size.
[ "Doubles", "the", "table", "size", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/restricted/CompactInterner.java#L122-L142
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/MsgCompiler.java
MsgCompiler.handleBasicTranslation
private Statement handleBasicTranslation( List<SoyPrintDirective> escapingDirectives, Expression soyMsgParts) { // optimize for simple constant translations (very common) // this becomes: renderContext.getSoyMessge(<id>).getParts().get(0).getRawText() SoyExpression text = SoyExpression.forString( soyMsgParts .invoke(MethodRef.LIST_GET, constant(0)) .checkedCast(SoyMsgRawTextPart.class) .invoke(MethodRef.SOY_MSG_RAW_TEXT_PART_GET_RAW_TEXT)); // Note: there is no point in trying to stream here, since we are starting with a constant // string. for (SoyPrintDirective directive : escapingDirectives) { text = parameterLookup.getRenderContext().applyPrintDirective(directive, text); } return appendableExpression.appendString(text.coerceToString()).toStatement(); }
java
private Statement handleBasicTranslation( List<SoyPrintDirective> escapingDirectives, Expression soyMsgParts) { // optimize for simple constant translations (very common) // this becomes: renderContext.getSoyMessge(<id>).getParts().get(0).getRawText() SoyExpression text = SoyExpression.forString( soyMsgParts .invoke(MethodRef.LIST_GET, constant(0)) .checkedCast(SoyMsgRawTextPart.class) .invoke(MethodRef.SOY_MSG_RAW_TEXT_PART_GET_RAW_TEXT)); // Note: there is no point in trying to stream here, since we are starting with a constant // string. for (SoyPrintDirective directive : escapingDirectives) { text = parameterLookup.getRenderContext().applyPrintDirective(directive, text); } return appendableExpression.appendString(text.coerceToString()).toStatement(); }
[ "private", "Statement", "handleBasicTranslation", "(", "List", "<", "SoyPrintDirective", ">", "escapingDirectives", ",", "Expression", "soyMsgParts", ")", "{", "// optimize for simple constant translations (very common)", "// this becomes: renderContext.getSoyMessge(<id>).getParts().ge...
Handles a translation consisting of a single raw text node.
[ "Handles", "a", "translation", "consisting", "of", "a", "single", "raw", "text", "node", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/MsgCompiler.java#L263-L279
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/MsgCompiler.java
MsgCompiler.handleTranslationWithPlaceholders
private Statement handleTranslationWithPlaceholders( MsgNode msg, ImmutableList<SoyPrintDirective> escapingDirectives, Expression soyMsgParts, Expression locale, MsgPartsAndIds partsAndId) { // We need to render placeholders into a buffer and then pack them into a map to pass to // Runtime.renderSoyMsgWithPlaceholders. Map<String, Function<Expression, Statement>> placeholderNameToPutStatement = new LinkedHashMap<>(); putPlaceholdersIntoMap(msg, partsAndId.parts, placeholderNameToPutStatement); // sanity check checkState(!placeholderNameToPutStatement.isEmpty()); ConstructorRef cstruct = msg.isPlrselMsg() ? ConstructorRef.PLRSEL_MSG_RENDERER : ConstructorRef.MSG_RENDERER; Statement initRendererStatement = variables .getCurrentRenderee() .putInstanceField( thisVar, cstruct.construct( constant(partsAndId.id), soyMsgParts, locale, constant(placeholderNameToPutStatement.size()))); List<Statement> initializationStatements = new ArrayList<>(); initializationStatements.add(initRendererStatement); for (Function<Expression, Statement> fn : placeholderNameToPutStatement.values()) { initializationStatements.add(fn.apply(variables.getCurrentRenderee().accessor(thisVar))); } Statement initMsgRenderer = Statement.concat(initializationStatements); Statement render; if (areAllPrintDirectivesStreamable(escapingDirectives)) { AppendableAndOptions wrappedAppendable = applyStreamingEscapingDirectives( escapingDirectives, appendableExpression, parameterLookup.getPluginContext(), variables); FieldRef currentAppendableField = variables.getCurrentAppendable(); Statement initAppendable = currentAppendableField.putInstanceField(thisVar, wrappedAppendable.appendable()); Expression appendableExpression = currentAppendableField.accessor(thisVar); Statement clearAppendable = currentAppendableField.putInstanceField( thisVar, constantNull(LOGGING_ADVISING_APPENDABLE_TYPE)); if (wrappedAppendable.closeable()) { clearAppendable = Statement.concat( appendableExpression .checkedCast(BytecodeUtils.CLOSEABLE_TYPE) .invokeVoid(MethodRef.CLOSEABLE_CLOSE), clearAppendable); } render = Statement.concat( initAppendable, detachState.detachForRender( variables .getCurrentRenderee() .accessor(thisVar) .invoke( MethodRef.SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE, appendableExpression, // set the isLast field to true since we know this will only be rendered // once. /* isLast=*/ constant(true))), clearAppendable); } else { Label start = new Label(); SoyExpression value = SoyExpression.forSoyValue( StringType.getInstance(), detachState .createExpressionDetacher(start) .resolveSoyValueProvider(variables.getCurrentRenderee().accessor(thisVar)) .checkedCast(SOY_STRING_TYPE)); for (SoyPrintDirective directive : escapingDirectives) { value = parameterLookup.getRenderContext().applyPrintDirective(directive, value); } render = appendableExpression.appendString(value.unboxAsString()).toStatement().labelStart(start); } return Statement.concat( initMsgRenderer, render, // clear the field variables .getCurrentRenderee() .putInstanceField( thisVar, BytecodeUtils.constantNull(ConstructorRef.MSG_RENDERER.instanceClass().type()))); }
java
private Statement handleTranslationWithPlaceholders( MsgNode msg, ImmutableList<SoyPrintDirective> escapingDirectives, Expression soyMsgParts, Expression locale, MsgPartsAndIds partsAndId) { // We need to render placeholders into a buffer and then pack them into a map to pass to // Runtime.renderSoyMsgWithPlaceholders. Map<String, Function<Expression, Statement>> placeholderNameToPutStatement = new LinkedHashMap<>(); putPlaceholdersIntoMap(msg, partsAndId.parts, placeholderNameToPutStatement); // sanity check checkState(!placeholderNameToPutStatement.isEmpty()); ConstructorRef cstruct = msg.isPlrselMsg() ? ConstructorRef.PLRSEL_MSG_RENDERER : ConstructorRef.MSG_RENDERER; Statement initRendererStatement = variables .getCurrentRenderee() .putInstanceField( thisVar, cstruct.construct( constant(partsAndId.id), soyMsgParts, locale, constant(placeholderNameToPutStatement.size()))); List<Statement> initializationStatements = new ArrayList<>(); initializationStatements.add(initRendererStatement); for (Function<Expression, Statement> fn : placeholderNameToPutStatement.values()) { initializationStatements.add(fn.apply(variables.getCurrentRenderee().accessor(thisVar))); } Statement initMsgRenderer = Statement.concat(initializationStatements); Statement render; if (areAllPrintDirectivesStreamable(escapingDirectives)) { AppendableAndOptions wrappedAppendable = applyStreamingEscapingDirectives( escapingDirectives, appendableExpression, parameterLookup.getPluginContext(), variables); FieldRef currentAppendableField = variables.getCurrentAppendable(); Statement initAppendable = currentAppendableField.putInstanceField(thisVar, wrappedAppendable.appendable()); Expression appendableExpression = currentAppendableField.accessor(thisVar); Statement clearAppendable = currentAppendableField.putInstanceField( thisVar, constantNull(LOGGING_ADVISING_APPENDABLE_TYPE)); if (wrappedAppendable.closeable()) { clearAppendable = Statement.concat( appendableExpression .checkedCast(BytecodeUtils.CLOSEABLE_TYPE) .invokeVoid(MethodRef.CLOSEABLE_CLOSE), clearAppendable); } render = Statement.concat( initAppendable, detachState.detachForRender( variables .getCurrentRenderee() .accessor(thisVar) .invoke( MethodRef.SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE, appendableExpression, // set the isLast field to true since we know this will only be rendered // once. /* isLast=*/ constant(true))), clearAppendable); } else { Label start = new Label(); SoyExpression value = SoyExpression.forSoyValue( StringType.getInstance(), detachState .createExpressionDetacher(start) .resolveSoyValueProvider(variables.getCurrentRenderee().accessor(thisVar)) .checkedCast(SOY_STRING_TYPE)); for (SoyPrintDirective directive : escapingDirectives) { value = parameterLookup.getRenderContext().applyPrintDirective(directive, value); } render = appendableExpression.appendString(value.unboxAsString()).toStatement().labelStart(start); } return Statement.concat( initMsgRenderer, render, // clear the field variables .getCurrentRenderee() .putInstanceField( thisVar, BytecodeUtils.constantNull(ConstructorRef.MSG_RENDERER.instanceClass().type()))); }
[ "private", "Statement", "handleTranslationWithPlaceholders", "(", "MsgNode", "msg", ",", "ImmutableList", "<", "SoyPrintDirective", ">", "escapingDirectives", ",", "Expression", "soyMsgParts", ",", "Expression", "locale", ",", "MsgPartsAndIds", "partsAndId", ")", "{", "...
Handles a complex message with placeholders.
[ "Handles", "a", "complex", "message", "with", "placeholders", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/MsgCompiler.java#L282-L376
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/MsgCompiler.java
MsgCompiler.addNodeToPlaceholderMap
private Function<Expression, Statement> addNodeToPlaceholderMap( String mapKey, StandaloneNode node) { return putToMapFunction( mapKey, placeholderCompiler.compileToSoyValueProvider( mapKey, node, /* prefix= */ ExtraCodeCompiler.NO_OP, /* suffix= */ ExtraCodeCompiler.NO_OP)); }
java
private Function<Expression, Statement> addNodeToPlaceholderMap( String mapKey, StandaloneNode node) { return putToMapFunction( mapKey, placeholderCompiler.compileToSoyValueProvider( mapKey, node, /* prefix= */ ExtraCodeCompiler.NO_OP, /* suffix= */ ExtraCodeCompiler.NO_OP)); }
[ "private", "Function", "<", "Expression", ",", "Statement", ">", "addNodeToPlaceholderMap", "(", "String", "mapKey", ",", "StandaloneNode", "node", ")", "{", "return", "putToMapFunction", "(", "mapKey", ",", "placeholderCompiler", ".", "compileToSoyValueProvider", "("...
Returns a statement that adds the content rendered by the call to the map. @param mapKey The map key @param node The node
[ "Returns", "a", "statement", "that", "adds", "the", "content", "rendered", "by", "the", "call", "to", "the", "map", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/MsgCompiler.java#L554-L563
train
google/closure-templates
java/src/com/google/template/soy/jssrc/restricted/JsExprUtils.java
JsExprUtils.concatJsExprs
public static JsExpr concatJsExprs(List<? extends JsExpr> jsExprs) { if (jsExprs.isEmpty()) { return EMPTY_STRING; } if (jsExprs.size() == 1) { return jsExprs.get(0); } int plusOpPrec = Operator.PLUS.getPrecedence(); StringBuilder resultSb = new StringBuilder(); boolean isFirst = true; for (JsExpr jsExpr : jsExprs) { // The first operand needs protection only if it's strictly lower precedence. The non-first // operands need protection when they're lower or equal precedence. (This is true for all // left-associative operators.) boolean needsProtection = isFirst ? jsExpr.getPrecedence() < plusOpPrec : jsExpr.getPrecedence() <= plusOpPrec; if (isFirst) { isFirst = false; } else { resultSb.append(" + "); } if (needsProtection) { resultSb.append('(').append(jsExpr.getText()).append(')'); } else { resultSb.append(jsExpr.getText()); } } return new JsExpr(resultSb.toString(), plusOpPrec); }
java
public static JsExpr concatJsExprs(List<? extends JsExpr> jsExprs) { if (jsExprs.isEmpty()) { return EMPTY_STRING; } if (jsExprs.size() == 1) { return jsExprs.get(0); } int plusOpPrec = Operator.PLUS.getPrecedence(); StringBuilder resultSb = new StringBuilder(); boolean isFirst = true; for (JsExpr jsExpr : jsExprs) { // The first operand needs protection only if it's strictly lower precedence. The non-first // operands need protection when they're lower or equal precedence. (This is true for all // left-associative operators.) boolean needsProtection = isFirst ? jsExpr.getPrecedence() < plusOpPrec : jsExpr.getPrecedence() <= plusOpPrec; if (isFirst) { isFirst = false; } else { resultSb.append(" + "); } if (needsProtection) { resultSb.append('(').append(jsExpr.getText()).append(')'); } else { resultSb.append(jsExpr.getText()); } } return new JsExpr(resultSb.toString(), plusOpPrec); }
[ "public", "static", "JsExpr", "concatJsExprs", "(", "List", "<", "?", "extends", "JsExpr", ">", "jsExprs", ")", "{", "if", "(", "jsExprs", ".", "isEmpty", "(", ")", ")", "{", "return", "EMPTY_STRING", ";", "}", "if", "(", "jsExprs", ".", "size", "(", ...
Builds one JS expression that computes the concatenation of the given JS expressions. The '+' operator is used for concatenation. Operands will be protected with an extra pair of parentheses if and only if needed. <p>The resulting expression is not guaranteed to be a string if the operands do not produce strings when combined with the plus operator; e.g. 2+2 might be 4 instead of '22'. @param jsExprs The JS expressions to concatentate. @return One JS expression that computes the concatenation of the given JS expressions.
[ "Builds", "one", "JS", "expression", "that", "computes", "the", "concatenation", "of", "the", "given", "JS", "expressions", ".", "The", "+", "operator", "is", "used", "for", "concatenation", ".", "Operands", "will", "be", "protected", "with", "an", "extra", ...
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/restricted/JsExprUtils.java#L53-L88
train
google/closure-templates
java/src/com/google/template/soy/jssrc/restricted/JsExprUtils.java
JsExprUtils.wrapWithFunction
@VisibleForTesting static JsExpr wrapWithFunction(String functionExprText, JsExpr jsExpr) { Preconditions.checkNotNull(functionExprText); return new JsExpr(functionExprText + "(" + jsExpr.getText() + ")", Integer.MAX_VALUE); }
java
@VisibleForTesting static JsExpr wrapWithFunction(String functionExprText, JsExpr jsExpr) { Preconditions.checkNotNull(functionExprText); return new JsExpr(functionExprText + "(" + jsExpr.getText() + ")", Integer.MAX_VALUE); }
[ "@", "VisibleForTesting", "static", "JsExpr", "wrapWithFunction", "(", "String", "functionExprText", ",", "JsExpr", "jsExpr", ")", "{", "Preconditions", ".", "checkNotNull", "(", "functionExprText", ")", ";", "return", "new", "JsExpr", "(", "functionExprText", "+", ...
Wraps an expression in a function call. @param functionExprText expression for the function to invoke, such as a function name or constructor phrase (such as "new SomeClass"). @param jsExpr the expression to compute the argument to the function @return a JS expression consisting of a call to the specified function, applied to the provided expression.
[ "Wraps", "an", "expression", "in", "a", "function", "call", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/restricted/JsExprUtils.java#L135-L139
train
google/closure-templates
java/src/com/google/template/soy/passes/CombineConsecutiveRawTextNodesPass.java
CombineConsecutiveRawTextNodesPass.mergeRange
@SuppressWarnings("unchecked") private int mergeRange(ParentSoyNode<?> parent, int start, int lastNonEmptyRawTextNode, int end) { checkArgument(start < end); if (start == -1 || end == start + 1) { return end; } // general case, there are N rawtextnodes to merge where n > 1 // merge all the nodes together, then drop all the raw text nodes from the end RawTextNode newNode = RawTextNode.concat( (List<RawTextNode>) parent.getChildren().subList(start, lastNonEmptyRawTextNode + 1)); ((ParentSoyNode) parent).replaceChild(start, newNode); for (int i = end - 1; i > start; i--) { parent.removeChild(i); } return start + 1; }
java
@SuppressWarnings("unchecked") private int mergeRange(ParentSoyNode<?> parent, int start, int lastNonEmptyRawTextNode, int end) { checkArgument(start < end); if (start == -1 || end == start + 1) { return end; } // general case, there are N rawtextnodes to merge where n > 1 // merge all the nodes together, then drop all the raw text nodes from the end RawTextNode newNode = RawTextNode.concat( (List<RawTextNode>) parent.getChildren().subList(start, lastNonEmptyRawTextNode + 1)); ((ParentSoyNode) parent).replaceChild(start, newNode); for (int i = end - 1; i > start; i--) { parent.removeChild(i); } return start + 1; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "int", "mergeRange", "(", "ParentSoyNode", "<", "?", ">", "parent", ",", "int", "start", ",", "int", "lastNonEmptyRawTextNode", ",", "int", "end", ")", "{", "checkArgument", "(", "start", "<", "e...
RawTextNodes and if we can remove a RawTextNode, we can also add one.
[ "RawTextNodes", "and", "if", "we", "can", "remove", "a", "RawTextNode", "we", "can", "also", "add", "one", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/CombineConsecutiveRawTextNodesPass.java#L96-L112
train
google/closure-templates
java/src/com/google/template/soy/base/internal/SoyJarFileWriter.java
SoyJarFileWriter.writeEntry
public void writeEntry(String path, ByteSource contents) throws IOException { stream.putNextEntry(new ZipEntry(path)); contents.copyTo(stream); stream.closeEntry(); }
java
public void writeEntry(String path, ByteSource contents) throws IOException { stream.putNextEntry(new ZipEntry(path)); contents.copyTo(stream); stream.closeEntry(); }
[ "public", "void", "writeEntry", "(", "String", "path", ",", "ByteSource", "contents", ")", "throws", "IOException", "{", "stream", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "path", ")", ")", ";", "contents", ".", "copyTo", "(", "stream", ")", ";", ...
Writes a single entry to the jar.
[ "Writes", "a", "single", "entry", "to", "the", "jar", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/SoyJarFileWriter.java#L40-L44
train
google/closure-templates
java/src/com/google/template/soy/base/internal/SoyJarFileWriter.java
SoyJarFileWriter.standardSoyJarManifest
private static Manifest standardSoyJarManifest() { Manifest mf = new Manifest(); mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); mf.getMainAttributes().put(new Attributes.Name("Created-By"), "soy"); return mf; }
java
private static Manifest standardSoyJarManifest() { Manifest mf = new Manifest(); mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); mf.getMainAttributes().put(new Attributes.Name("Created-By"), "soy"); return mf; }
[ "private", "static", "Manifest", "standardSoyJarManifest", "(", ")", "{", "Manifest", "mf", "=", "new", "Manifest", "(", ")", ";", "mf", ".", "getMainAttributes", "(", ")", ".", "put", "(", "Attributes", ".", "Name", ".", "MANIFEST_VERSION", ",", "\"1.0\"", ...
Returns a simple jar manifest.
[ "Returns", "a", "simple", "jar", "manifest", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/internal/SoyJarFileWriter.java#L64-L69
train
google/closure-templates
java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java
ResolveExpressionTypesPass.addTypeSubstitutions
private void addTypeSubstitutions(Map<Wrapper<ExprNode>, SoyType> substitutionsToAdd) { for (Map.Entry<Wrapper<ExprNode>, SoyType> entry : substitutionsToAdd.entrySet()) { ExprNode expr = entry.getKey().get(); // Get the existing type SoyType previousType = expr.getType(); for (TypeSubstitution subst = substitutions; subst != null; subst = subst.parent) { if (ExprEquivalence.get().equivalent(subst.expression, expr)) { previousType = subst.type; break; } } // If the new type is different than the current type, then add a new type substitution. if (!entry.getValue().equals(previousType)) { substitutions = new TypeSubstitution(substitutions, expr, entry.getValue()); } } }
java
private void addTypeSubstitutions(Map<Wrapper<ExprNode>, SoyType> substitutionsToAdd) { for (Map.Entry<Wrapper<ExprNode>, SoyType> entry : substitutionsToAdd.entrySet()) { ExprNode expr = entry.getKey().get(); // Get the existing type SoyType previousType = expr.getType(); for (TypeSubstitution subst = substitutions; subst != null; subst = subst.parent) { if (ExprEquivalence.get().equivalent(subst.expression, expr)) { previousType = subst.type; break; } } // If the new type is different than the current type, then add a new type substitution. if (!entry.getValue().equals(previousType)) { substitutions = new TypeSubstitution(substitutions, expr, entry.getValue()); } } }
[ "private", "void", "addTypeSubstitutions", "(", "Map", "<", "Wrapper", "<", "ExprNode", ">", ",", "SoyType", ">", "substitutionsToAdd", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Wrapper", "<", "ExprNode", ">", ",", "SoyType", ">", "entry", ":", "s...
active substitutions.
[ "active", "substitutions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java#L478-L495
train
google/closure-templates
java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java
ResolveExpressionTypesPass.getElementType
private SoyType getElementType(SoyType collectionType, ForNonemptyNode node) { Preconditions.checkNotNull(collectionType); switch (collectionType.getKind()) { case UNKNOWN: // If we don't know anything about the base type, then make no assumptions // about the field type. return UnknownType.getInstance(); case LIST: if (collectionType == ListType.EMPTY_LIST) { errorReporter.report(node.getParent().getSourceLocation(), EMPTY_LIST_FOREACH); return ErrorType.getInstance(); } return ((ListType) collectionType).getElementType(); case UNION: { // If it's a union, then do the field type calculation for each member of // the union and combine the result. UnionType unionType = (UnionType) collectionType; List<SoyType> fieldTypes = new ArrayList<>(unionType.getMembers().size()); for (SoyType unionMember : unionType.getMembers()) { SoyType elementType = getElementType(unionMember, node); if (elementType.getKind() == SoyType.Kind.ERROR) { return ErrorType.getInstance(); } fieldTypes.add(elementType); } return SoyTypes.computeLowestCommonType(typeRegistry, fieldTypes); } default: errorReporter.report( node.getParent().getSourceLocation(), BAD_FOREACH_TYPE, node.getExpr().toSourceString(), node.getExpr().getType()); // Report the outermost union type in the error. return ErrorType.getInstance(); } }
java
private SoyType getElementType(SoyType collectionType, ForNonemptyNode node) { Preconditions.checkNotNull(collectionType); switch (collectionType.getKind()) { case UNKNOWN: // If we don't know anything about the base type, then make no assumptions // about the field type. return UnknownType.getInstance(); case LIST: if (collectionType == ListType.EMPTY_LIST) { errorReporter.report(node.getParent().getSourceLocation(), EMPTY_LIST_FOREACH); return ErrorType.getInstance(); } return ((ListType) collectionType).getElementType(); case UNION: { // If it's a union, then do the field type calculation for each member of // the union and combine the result. UnionType unionType = (UnionType) collectionType; List<SoyType> fieldTypes = new ArrayList<>(unionType.getMembers().size()); for (SoyType unionMember : unionType.getMembers()) { SoyType elementType = getElementType(unionMember, node); if (elementType.getKind() == SoyType.Kind.ERROR) { return ErrorType.getInstance(); } fieldTypes.add(elementType); } return SoyTypes.computeLowestCommonType(typeRegistry, fieldTypes); } default: errorReporter.report( node.getParent().getSourceLocation(), BAD_FOREACH_TYPE, node.getExpr().toSourceString(), node.getExpr().getType()); // Report the outermost union type in the error. return ErrorType.getInstance(); } }
[ "private", "SoyType", "getElementType", "(", "SoyType", "collectionType", ",", "ForNonemptyNode", "node", ")", "{", "Preconditions", ".", "checkNotNull", "(", "collectionType", ")", ";", "switch", "(", "collectionType", ".", "getKind", "(", ")", ")", "{", "case"...
Given a collection type, compute the element type. @param collectionType The base type. @param node The ForNonemptyNode being iterated. @return The type of the elements of the collection.
[ "Given", "a", "collection", "type", "compute", "the", "element", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/ResolveExpressionTypesPass.java#L511-L550
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java
SoySauceBuilder.withPluginInstances
public SoySauceBuilder withPluginInstances(Map<String, Supplier<Object>> pluginInstances) { this.userPluginInstances = ImmutableMap.copyOf(pluginInstances); return this; }
java
public SoySauceBuilder withPluginInstances(Map<String, Supplier<Object>> pluginInstances) { this.userPluginInstances = ImmutableMap.copyOf(pluginInstances); return this; }
[ "public", "SoySauceBuilder", "withPluginInstances", "(", "Map", "<", "String", ",", "Supplier", "<", "Object", ">", ">", "pluginInstances", ")", "{", "this", ".", "userPluginInstances", "=", "ImmutableMap", ".", "copyOf", "(", "pluginInstances", ")", ";", "retur...
Sets the plugin instance factories, to be used when constructing the SoySauce. <p>These are used to supply the runtime instances needed by SoyJavaSourceFunction implementations which use the {@code callInstanceMethod} API.
[ "Sets", "the", "plugin", "instance", "factories", "to", "be", "used", "when", "constructing", "the", "SoySauce", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java#L55-L58
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java
SoySauceBuilder.withFunctions
SoySauceBuilder withFunctions(Map<String, ? extends SoyFunction> userFunctions) { this.userFunctions = ImmutableMap.copyOf(userFunctions); return this; }
java
SoySauceBuilder withFunctions(Map<String, ? extends SoyFunction> userFunctions) { this.userFunctions = ImmutableMap.copyOf(userFunctions); return this; }
[ "SoySauceBuilder", "withFunctions", "(", "Map", "<", "String", ",", "?", "extends", "SoyFunction", ">", "userFunctions", ")", "{", "this", ".", "userFunctions", "=", "ImmutableMap", ".", "copyOf", "(", "userFunctions", ")", ";", "return", "this", ";", "}" ]
Sets the user functions.
[ "Sets", "the", "user", "functions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java#L74-L77
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java
SoySauceBuilder.withDirectives
SoySauceBuilder withDirectives(Map<String, ? extends SoyPrintDirective> userDirectives) { this.userDirectives = ImmutableMap.copyOf(userDirectives); return this; }
java
SoySauceBuilder withDirectives(Map<String, ? extends SoyPrintDirective> userDirectives) { this.userDirectives = ImmutableMap.copyOf(userDirectives); return this; }
[ "SoySauceBuilder", "withDirectives", "(", "Map", "<", "String", ",", "?", "extends", "SoyPrintDirective", ">", "userDirectives", ")", "{", "this", ".", "userDirectives", "=", "ImmutableMap", ".", "copyOf", "(", "userDirectives", ")", ";", "return", "this", ";", ...
Sets user directives. Not exposed externally because internal directives should be enough, and additional functionality can be built as SoySourceFunctions.
[ "Sets", "user", "directives", ".", "Not", "exposed", "externally", "because", "internal", "directives", "should", "be", "enough", "and", "additional", "functionality", "can", "be", "built", "as", "SoySourceFunctions", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java#L83-L86
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java
SoySauceBuilder.build
public SoySauce build() { if (scopedData == null) { scopedData = new SoySimpleScope(); } if (loader == null) { loader = SoySauceBuilder.class.getClassLoader(); } return new SoySauceImpl( new CompiledTemplates(readDelTemplatesFromMetaInf(loader), loader), scopedData.enterable(), userFunctions, // We don't need internal functions because they only matter at compile time ImmutableMap.<String, SoyPrintDirective>builder() // but internal directives are still required at render time. // in order to handle escaping logging function invocations. .putAll(InternalPlugins.internalDirectiveMap(scopedData)) .putAll(userDirectives) .build(), userPluginInstances); }
java
public SoySauce build() { if (scopedData == null) { scopedData = new SoySimpleScope(); } if (loader == null) { loader = SoySauceBuilder.class.getClassLoader(); } return new SoySauceImpl( new CompiledTemplates(readDelTemplatesFromMetaInf(loader), loader), scopedData.enterable(), userFunctions, // We don't need internal functions because they only matter at compile time ImmutableMap.<String, SoyPrintDirective>builder() // but internal directives are still required at render time. // in order to handle escaping logging function invocations. .putAll(InternalPlugins.internalDirectiveMap(scopedData)) .putAll(userDirectives) .build(), userPluginInstances); }
[ "public", "SoySauce", "build", "(", ")", "{", "if", "(", "scopedData", "==", "null", ")", "{", "scopedData", "=", "new", "SoySimpleScope", "(", ")", ";", "}", "if", "(", "loader", "==", "null", ")", "{", "loader", "=", "SoySauceBuilder", ".", "class", ...
Creates a SoySauce.
[ "Creates", "a", "SoySauce", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java#L95-L113
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java
SoySauceBuilder.readDelTemplatesFromMetaInf
private static ImmutableSet<String> readDelTemplatesFromMetaInf(ClassLoader loader) { try { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); Enumeration<URL> resources = loader.getResources(Names.META_INF_DELTEMPLATE_PATH); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try (InputStream in = url.openStream()) { BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { builder.add(line); } } } return builder.build(); } catch (IOException iox) { throw new RuntimeException("Unable to read deltemplate listing", iox); } }
java
private static ImmutableSet<String> readDelTemplatesFromMetaInf(ClassLoader loader) { try { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); Enumeration<URL> resources = loader.getResources(Names.META_INF_DELTEMPLATE_PATH); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try (InputStream in = url.openStream()) { BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { builder.add(line); } } } return builder.build(); } catch (IOException iox) { throw new RuntimeException("Unable to read deltemplate listing", iox); } }
[ "private", "static", "ImmutableSet", "<", "String", ">", "readDelTemplatesFromMetaInf", "(", "ClassLoader", "loader", ")", "{", "try", "{", "ImmutableSet", ".", "Builder", "<", "String", ">", "builder", "=", "ImmutableSet", ".", "builder", "(", ")", ";", "Enum...
Walks all resources with the META_INF_DELTEMPLATE_PATH and collects the deltemplates.
[ "Walks", "all", "resources", "with", "the", "META_INF_DELTEMPLATE_PATH", "and", "collects", "the", "deltemplates", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/api/SoySauceBuilder.java#L116-L133
train
google/closure-templates
java/src/com/google/template/soy/passes/ShouldEnsureDataIsDefinedVisitor.java
ShouldEnsureDataIsDefinedVisitor.exec
public boolean exec(TemplateNode template) { boolean hasOptional = false; for (TemplateParam param : template.getParams()) { if (param.isRequired()) { // If there exists a required param, then data should already be defined (no need to // ensure). return false; } else { hasOptional = true; } } if (hasOptional) { // If all params are optional (and there is at least one), then we need to ensure data is // defined. This is because the only legal way to have an optional param is if you reference // it somewhere in the template, so there is no need to check. return true; } // If we get here then the template has no declared params and we are observing a v1 compatible // template. Search for things that could be data references: // * possibleParams // * data=All calls // others? return new AbstractNodeVisitor<Node, Boolean>() { boolean shouldEnsureDataIsDefined; @Override public Boolean exec(Node node) { visit(node); return shouldEnsureDataIsDefined; } @Override public void visit(Node node) { if (node instanceof VarRefNode) { VarRefNode varRefNode = (VarRefNode) node; VarDefn var = varRefNode.getDefnDecl(); // Don't include injected params in this analysis if (varRefNode.isPossibleHeaderVar() && var.kind() != VarDefn.Kind.STATE && (var.kind() != VarDefn.Kind.PARAM // a soydoc param -> not ij || !((TemplateParam) var).isInjected())) { // an {@param but not {@inject shouldEnsureDataIsDefined = true; return; } } if (node instanceof CallNode) { if (((CallNode) node).isPassingAllData()) { shouldEnsureDataIsDefined = true; return; } } if (node instanceof ParentNode) { for (Node child : ((ParentNode<?>) node).getChildren()) { visit(child); if (shouldEnsureDataIsDefined) { return; } } } if (node instanceof ExprHolderNode) { for (ExprRootNode expr : ((ExprHolderNode) node).getExprList()) { visit(expr); if (shouldEnsureDataIsDefined) { return; } } } } }.exec(template); }
java
public boolean exec(TemplateNode template) { boolean hasOptional = false; for (TemplateParam param : template.getParams()) { if (param.isRequired()) { // If there exists a required param, then data should already be defined (no need to // ensure). return false; } else { hasOptional = true; } } if (hasOptional) { // If all params are optional (and there is at least one), then we need to ensure data is // defined. This is because the only legal way to have an optional param is if you reference // it somewhere in the template, so there is no need to check. return true; } // If we get here then the template has no declared params and we are observing a v1 compatible // template. Search for things that could be data references: // * possibleParams // * data=All calls // others? return new AbstractNodeVisitor<Node, Boolean>() { boolean shouldEnsureDataIsDefined; @Override public Boolean exec(Node node) { visit(node); return shouldEnsureDataIsDefined; } @Override public void visit(Node node) { if (node instanceof VarRefNode) { VarRefNode varRefNode = (VarRefNode) node; VarDefn var = varRefNode.getDefnDecl(); // Don't include injected params in this analysis if (varRefNode.isPossibleHeaderVar() && var.kind() != VarDefn.Kind.STATE && (var.kind() != VarDefn.Kind.PARAM // a soydoc param -> not ij || !((TemplateParam) var).isInjected())) { // an {@param but not {@inject shouldEnsureDataIsDefined = true; return; } } if (node instanceof CallNode) { if (((CallNode) node).isPassingAllData()) { shouldEnsureDataIsDefined = true; return; } } if (node instanceof ParentNode) { for (Node child : ((ParentNode<?>) node).getChildren()) { visit(child); if (shouldEnsureDataIsDefined) { return; } } } if (node instanceof ExprHolderNode) { for (ExprRootNode expr : ((ExprHolderNode) node).getExprList()) { visit(expr); if (shouldEnsureDataIsDefined) { return; } } } } }.exec(template); }
[ "public", "boolean", "exec", "(", "TemplateNode", "template", ")", "{", "boolean", "hasOptional", "=", "false", ";", "for", "(", "TemplateParam", "param", ":", "template", ".", "getParams", "(", ")", ")", "{", "if", "(", "param", ".", "isRequired", "(", ...
Runs this pass on the given template.
[ "Runs", "this", "pass", "on", "the", "given", "template", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/ShouldEnsureDataIsDefinedVisitor.java#L39-L109
train
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/CodeChunkUtils.java
CodeChunkUtils.checkId
static void checkId(String id) { if (!ID.matcher(id).matches()) { throw new IllegalArgumentException(String.format("not a valid js identifier: %s", id)); } }
java
static void checkId(String id) { if (!ID.matcher(id).matches()) { throw new IllegalArgumentException(String.format("not a valid js identifier: %s", id)); } }
[ "static", "void", "checkId", "(", "String", "id", ")", "{", "if", "(", "!", "ID", ".", "matcher", "(", "id", ")", ".", "matches", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"not a valid js identif...
Validates that the given string is a valid javascript identifier.
[ "Validates", "that", "the", "given", "string", "is", "a", "valid", "javascript", "identifier", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/CodeChunkUtils.java#L44-L48
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/TemplateCompiler.java
TemplateCompiler.compile
Iterable<ClassData> compile() { List<ClassData> classes = new ArrayList<>(); // first generate the factory if (templateNode.getVisibility() != Visibility.PRIVATE) { // Don't generate factory if the template is private. The factories are only // useful to instantiate templates for calls from java. Soy->Soy calls should invoke // constructors directly. new TemplateFactoryCompiler(template, templateNode, innerClasses).compile(); } writer = SoyClassWriter.builder(template.typeInfo()) .setAccess(Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER + Opcodes.ACC_FINAL) .implementing(TEMPLATE_TYPE) .sourceFileName(templateNode.getSourceLocation().getFileName()) .build(); generateTemplateMetadata(); generateKindMethod(); stateField.defineField(writer); paramsField.defineField(writer); ijField.defineField(writer); for (FieldRef field : paramFields.values()) { field.defineField(writer); } ImmutableMap<TemplateParam, SoyExpression> defaultParamInitializers = generateRenderMethod(); generateConstructor(defaultParamInitializers); innerClasses.registerAllInnerClasses(writer); writer.visitEnd(); classes.add(writer.toClassData()); classes.addAll(innerClasses.getInnerClassData()); writer = null; return classes; }
java
Iterable<ClassData> compile() { List<ClassData> classes = new ArrayList<>(); // first generate the factory if (templateNode.getVisibility() != Visibility.PRIVATE) { // Don't generate factory if the template is private. The factories are only // useful to instantiate templates for calls from java. Soy->Soy calls should invoke // constructors directly. new TemplateFactoryCompiler(template, templateNode, innerClasses).compile(); } writer = SoyClassWriter.builder(template.typeInfo()) .setAccess(Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER + Opcodes.ACC_FINAL) .implementing(TEMPLATE_TYPE) .sourceFileName(templateNode.getSourceLocation().getFileName()) .build(); generateTemplateMetadata(); generateKindMethod(); stateField.defineField(writer); paramsField.defineField(writer); ijField.defineField(writer); for (FieldRef field : paramFields.values()) { field.defineField(writer); } ImmutableMap<TemplateParam, SoyExpression> defaultParamInitializers = generateRenderMethod(); generateConstructor(defaultParamInitializers); innerClasses.registerAllInnerClasses(writer); writer.visitEnd(); classes.add(writer.toClassData()); classes.addAll(innerClasses.getInnerClassData()); writer = null; return classes; }
[ "Iterable", "<", "ClassData", ">", "compile", "(", ")", "{", "List", "<", "ClassData", ">", "classes", "=", "new", "ArrayList", "<>", "(", ")", ";", "// first generate the factory", "if", "(", "templateNode", ".", "getVisibility", "(", ")", "!=", "Visibility...
Returns the list of classes needed to implement this template. <p>For each template, we generate: <ul> <li>A {@link com.google.template.soy.jbcsrc.shared.CompiledTemplate.Factory} <li>A {@link CompiledTemplate} <li>A DetachableSoyValueProvider subclass for each {@link LetValueNode} and {@link CallParamValueNode} <li>A DetachableContentProvider subclass for each {@link LetContentNode} and {@link CallParamContentNode} <p>Note: This will <em>not</em> generate classes for other templates, only the template configured in the constructor. But it will generate classes that <em>reference</em> the classes that are generated for other templates. It is the callers responsibility to ensure that all referenced templates are generated and available in the classloader that ultimately loads the returned classes.
[ "Returns", "the", "list", "of", "classes", "needed", "to", "implement", "this", "template", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/TemplateCompiler.java#L157-L194
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/TemplateCompiler.java
TemplateCompiler.generateConstructor
private void generateConstructor( ImmutableMap<TemplateParam, SoyExpression> defaultParamInitializers) { final Label start = new Label(); final Label end = new Label(); final LocalVariable thisVar = createThisVar(template.typeInfo(), start, end); final LocalVariable paramsVar = createLocal("params", 1, SOY_RECORD_TYPE, start, end); final LocalVariable ijVar = createLocal("ij", 2, SOY_RECORD_TYPE, start, end); final List<Statement> assignments = new ArrayList<>(); assignments.add(paramsField.putInstanceField(thisVar, paramsVar)); assignments.add(ijField.putInstanceField(thisVar, ijVar)); for (TemplateParam param : templateNode.getAllParams()) { Expression paramProvider = getParam(paramsVar, ijVar, param, defaultParamInitializers.get(param)); assignments.add(paramFields.get(param.name()).putInstanceField(thisVar, paramProvider)); } Statement constructorBody = new Statement() { @Override protected void doGen(CodeBuilder ga) { ga.mark(start); // call super() thisVar.gen(ga); ga.invokeConstructor(OBJECT.type(), NULLARY_INIT); for (Statement assignment : assignments) { assignment.gen(ga); } ga.visitInsn(Opcodes.RETURN); ga.visitLabel(end); thisVar.tableEntry(ga); paramsVar.tableEntry(ga); ijVar.tableEntry(ga); } }; constructorBody.writeMethod(Opcodes.ACC_PUBLIC, template.constructor().method(), writer); }
java
private void generateConstructor( ImmutableMap<TemplateParam, SoyExpression> defaultParamInitializers) { final Label start = new Label(); final Label end = new Label(); final LocalVariable thisVar = createThisVar(template.typeInfo(), start, end); final LocalVariable paramsVar = createLocal("params", 1, SOY_RECORD_TYPE, start, end); final LocalVariable ijVar = createLocal("ij", 2, SOY_RECORD_TYPE, start, end); final List<Statement> assignments = new ArrayList<>(); assignments.add(paramsField.putInstanceField(thisVar, paramsVar)); assignments.add(ijField.putInstanceField(thisVar, ijVar)); for (TemplateParam param : templateNode.getAllParams()) { Expression paramProvider = getParam(paramsVar, ijVar, param, defaultParamInitializers.get(param)); assignments.add(paramFields.get(param.name()).putInstanceField(thisVar, paramProvider)); } Statement constructorBody = new Statement() { @Override protected void doGen(CodeBuilder ga) { ga.mark(start); // call super() thisVar.gen(ga); ga.invokeConstructor(OBJECT.type(), NULLARY_INIT); for (Statement assignment : assignments) { assignment.gen(ga); } ga.visitInsn(Opcodes.RETURN); ga.visitLabel(end); thisVar.tableEntry(ga); paramsVar.tableEntry(ga); ijVar.tableEntry(ga); } }; constructorBody.writeMethod(Opcodes.ACC_PUBLIC, template.constructor().method(), writer); }
[ "private", "void", "generateConstructor", "(", "ImmutableMap", "<", "TemplateParam", ",", "SoyExpression", ">", "defaultParamInitializers", ")", "{", "final", "Label", "start", "=", "new", "Label", "(", ")", ";", "final", "Label", "end", "=", "new", "Label", "...
Generate a public constructor that assigns our final field and checks for missing required params. <p>This constructor is called by the generate factory classes.
[ "Generate", "a", "public", "constructor", "that", "assigns", "our", "final", "field", "and", "checks", "for", "missing", "required", "params", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/TemplateCompiler.java#L381-L415
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Expression.java
Expression.checkTypes
static void checkTypes(ImmutableList<Type> types, Iterable<? extends Expression> exprs) { int size = Iterables.size(exprs); checkArgument( size == types.size(), "Supplied the wrong number of parameters. Expected %s, got %s", types.size(), size); // checkIsAssignableTo is an no-op if DEBUG is false if (Flags.DEBUG) { int i = 0; for (Expression expr : exprs) { expr.checkAssignableTo(types.get(i), "Parameter %s", i); i++; } } }
java
static void checkTypes(ImmutableList<Type> types, Iterable<? extends Expression> exprs) { int size = Iterables.size(exprs); checkArgument( size == types.size(), "Supplied the wrong number of parameters. Expected %s, got %s", types.size(), size); // checkIsAssignableTo is an no-op if DEBUG is false if (Flags.DEBUG) { int i = 0; for (Expression expr : exprs) { expr.checkAssignableTo(types.get(i), "Parameter %s", i); i++; } } }
[ "static", "void", "checkTypes", "(", "ImmutableList", "<", "Type", ">", "types", ",", "Iterable", "<", "?", "extends", "Expression", ">", "exprs", ")", "{", "int", "size", "=", "Iterables", ".", "size", "(", "exprs", ")", ";", "checkArgument", "(", "size...
Checks that the given expressions are compatible with the given types.
[ "Checks", "that", "the", "given", "expressions", "are", "compatible", "with", "the", "given", "types", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L167-L182
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Expression.java
Expression.toStatement
public Statement toStatement() { return new Statement() { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); switch (resultType().getSize()) { case 0: throw new AssertionError("void expressions are not allowed"); case 1: adapter.pop(); break; case 2: adapter.pop2(); break; default: throw new AssertionError(); } } }; }
java
public Statement toStatement() { return new Statement() { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); switch (resultType().getSize()) { case 0: throw new AssertionError("void expressions are not allowed"); case 1: adapter.pop(); break; case 2: adapter.pop2(); break; default: throw new AssertionError(); } } }; }
[ "public", "Statement", "toStatement", "(", ")", "{", "return", "new", "Statement", "(", ")", "{", "@", "Override", "protected", "void", "doGen", "(", "CodeBuilder", "adapter", ")", "{", "Expression", ".", "this", ".", "gen", "(", "adapter", ")", ";", "sw...
Convert this expression to a statement, by executing it and throwing away the result. <p>This is useful for invoking non-void methods when we don't care about the result.
[ "Convert", "this", "expression", "to", "a", "statement", "by", "executing", "it", "and", "throwing", "away", "the", "result", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L277-L296
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Expression.java
Expression.checkedCast
public Expression checkedCast(final Type target) { checkArgument( target.getSort() == Type.OBJECT, "cast targets must be reference types. (%s)", target.getClassName()); checkArgument( resultType().getSort() == Type.OBJECT, "you may only cast from reference types. (%s)", resultType().getClassName()); if (BytecodeUtils.isDefinitelyAssignableFrom(target, resultType())) { return this; } return new Expression(target, features()) { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); // TODO(b/191662001) Remove this once we have fully switched the type // system over. Normally, we should just cast this result over, but in // the case of SoyString, there are temporarily two states (SanitizedContent == SoyString) // and (SanitizedContent != SoyString). This branch bails out to a runtime function that // effectively does the below but also optionally logs a warning. if (resultType().equals(BytecodeUtils.SOY_STRING_TYPE)) { MethodRef.RUNTIME_CHECK_SOY_STRING.invokeUnchecked(adapter); } else { adapter.checkCast(resultType()); } } }; }
java
public Expression checkedCast(final Type target) { checkArgument( target.getSort() == Type.OBJECT, "cast targets must be reference types. (%s)", target.getClassName()); checkArgument( resultType().getSort() == Type.OBJECT, "you may only cast from reference types. (%s)", resultType().getClassName()); if (BytecodeUtils.isDefinitelyAssignableFrom(target, resultType())) { return this; } return new Expression(target, features()) { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); // TODO(b/191662001) Remove this once we have fully switched the type // system over. Normally, we should just cast this result over, but in // the case of SoyString, there are temporarily two states (SanitizedContent == SoyString) // and (SanitizedContent != SoyString). This branch bails out to a runtime function that // effectively does the below but also optionally logs a warning. if (resultType().equals(BytecodeUtils.SOY_STRING_TYPE)) { MethodRef.RUNTIME_CHECK_SOY_STRING.invokeUnchecked(adapter); } else { adapter.checkCast(resultType()); } } }; }
[ "public", "Expression", "checkedCast", "(", "final", "Type", "target", ")", "{", "checkArgument", "(", "target", ".", "getSort", "(", ")", "==", "Type", ".", "OBJECT", ",", "\"cast targets must be reference types. (%s)\"", ",", "target", ".", "getClassName", "(", ...
Returns an expression that performs a checked cast from the current type to the target type. @throws IllegalArgumentException if either type is not a reference type.
[ "Returns", "an", "expression", "that", "performs", "a", "checked", "cast", "from", "the", "current", "type", "to", "the", "target", "type", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L341-L369
train
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Expression.java
Expression.labelStart
public Expression labelStart(final Label label) { return new Expression(resultType(), features) { @Override protected void doGen(CodeBuilder adapter) { adapter.mark(label); Expression.this.gen(adapter); } }; }
java
public Expression labelStart(final Label label) { return new Expression(resultType(), features) { @Override protected void doGen(CodeBuilder adapter) { adapter.mark(label); Expression.this.gen(adapter); } }; }
[ "public", "Expression", "labelStart", "(", "final", "Label", "label", ")", "{", "return", "new", "Expression", "(", "resultType", "(", ")", ",", "features", ")", "{", "@", "Override", "protected", "void", "doGen", "(", "CodeBuilder", "adapter", ")", "{", "...
Returns a new expression identical to this one but with the given label applied at the start of the expression.
[ "Returns", "a", "new", "expression", "identical", "to", "this", "one", "but", "with", "the", "given", "label", "applied", "at", "the", "start", "of", "the", "expression", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L400-L408
train
google/closure-templates
java/src/com/google/template/soy/soytree/CallBasicNode.java
CallBasicNode.setParamsToRuntimeCheck
public void setParamsToRuntimeCheck(Predicate<String> paramNames) { checkState(this.paramsToRuntimeTypeCheck == null); this.paramsToRuntimeTypeCheck = checkNotNull(paramNames); }
java
public void setParamsToRuntimeCheck(Predicate<String> paramNames) { checkState(this.paramsToRuntimeTypeCheck == null); this.paramsToRuntimeTypeCheck = checkNotNull(paramNames); }
[ "public", "void", "setParamsToRuntimeCheck", "(", "Predicate", "<", "String", ">", "paramNames", ")", "{", "checkState", "(", "this", ".", "paramsToRuntimeTypeCheck", "==", "null", ")", ";", "this", ".", "paramsToRuntimeTypeCheck", "=", "checkNotNull", "(", "param...
Sets the names of the params that require runtime type checking against callee's types. <p>This mechanism is used by the TOFU runtime only to save some work when calling templates.
[ "Sets", "the", "names", "of", "the", "params", "that", "require", "runtime", "type", "checking", "against", "callee", "s", "types", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/CallBasicNode.java#L131-L134
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.cleanHtml
public static SanitizedContent cleanHtml( SoyValue value, Collection<? extends OptionalSafeTag> optionalSafeTags) { value = normalizeNull(value); Dir valueDir = null; if (value instanceof SanitizedContent) { SanitizedContent sanitizedContent = (SanitizedContent) value; if (sanitizedContent.getContentKind() == SanitizedContent.ContentKind.HTML) { return (SanitizedContent) value; } valueDir = sanitizedContent.getContentDirection(); } return cleanHtml(value.coerceToString(), valueDir, optionalSafeTags); }
java
public static SanitizedContent cleanHtml( SoyValue value, Collection<? extends OptionalSafeTag> optionalSafeTags) { value = normalizeNull(value); Dir valueDir = null; if (value instanceof SanitizedContent) { SanitizedContent sanitizedContent = (SanitizedContent) value; if (sanitizedContent.getContentKind() == SanitizedContent.ContentKind.HTML) { return (SanitizedContent) value; } valueDir = sanitizedContent.getContentDirection(); } return cleanHtml(value.coerceToString(), valueDir, optionalSafeTags); }
[ "public", "static", "SanitizedContent", "cleanHtml", "(", "SoyValue", "value", ",", "Collection", "<", "?", "extends", "OptionalSafeTag", ">", "optionalSafeTags", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "Dir", "valueDir", "=", "null", ...
Normalizes the input HTML while preserving "safe" tags and the known directionality. @param optionalSafeTags to add to the basic whitelist of formatting safe tags @return the normalized input, in the form of {@link SanitizedContent} of {@link ContentKind#HTML}
[ "Normalizes", "the", "input", "HTML", "while", "preserving", "safe", "tags", "and", "the", "known", "directionality", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L99-L111
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.cleanHtml
public static SanitizedContent cleanHtml( String value, Collection<? extends OptionalSafeTag> optionalSafeTags) { return cleanHtml(value, null, optionalSafeTags); }
java
public static SanitizedContent cleanHtml( String value, Collection<? extends OptionalSafeTag> optionalSafeTags) { return cleanHtml(value, null, optionalSafeTags); }
[ "public", "static", "SanitizedContent", "cleanHtml", "(", "String", "value", ",", "Collection", "<", "?", "extends", "OptionalSafeTag", ">", "optionalSafeTags", ")", "{", "return", "cleanHtml", "(", "value", ",", "null", ",", "optionalSafeTags", ")", ";", "}" ]
Normalizes the input HTML while preserving "safe" tags. The content directionality is unknown. @param optionalSafeTags to add to the basic whitelist of formatting safe tags @return the normalized input, in the form of {@link SanitizedContent} of {@link ContentKind#HTML}
[ "Normalizes", "the", "input", "HTML", "while", "preserving", "safe", "tags", ".", "The", "content", "directionality", "is", "unknown", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L211-L214
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.cleanHtml
public static SanitizedContent cleanHtml( String value, Dir contentDir, Collection<? extends OptionalSafeTag> optionalSafeTags) { return UnsafeSanitizedContentOrdainer.ordainAsSafe( stripHtmlTags(value, TagWhitelist.FORMATTING.withOptionalSafeTags(optionalSafeTags), true), ContentKind.HTML, contentDir); }
java
public static SanitizedContent cleanHtml( String value, Dir contentDir, Collection<? extends OptionalSafeTag> optionalSafeTags) { return UnsafeSanitizedContentOrdainer.ordainAsSafe( stripHtmlTags(value, TagWhitelist.FORMATTING.withOptionalSafeTags(optionalSafeTags), true), ContentKind.HTML, contentDir); }
[ "public", "static", "SanitizedContent", "cleanHtml", "(", "String", "value", ",", "Dir", "contentDir", ",", "Collection", "<", "?", "extends", "OptionalSafeTag", ">", "optionalSafeTags", ")", "{", "return", "UnsafeSanitizedContentOrdainer", ".", "ordainAsSafe", "(", ...
Normalizes the input HTML of a given directionality while preserving "safe" tags. @param optionalSafeTags to add to the basic whitelist of formatting safe tags @return the normalized input, in the form of {@link SanitizedContent} of {@link ContentKind#HTML}
[ "Normalizes", "the", "input", "HTML", "of", "a", "given", "directionality", "while", "preserving", "safe", "tags", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L223-L229
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.normalizeHtml
public static String normalizeHtml(SoyValue value) { value = normalizeNull(value); return normalizeHtml(value.coerceToString()); }
java
public static String normalizeHtml(SoyValue value) { value = normalizeNull(value); return normalizeHtml(value.coerceToString()); }
[ "public", "static", "String", "normalizeHtml", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "normalizeHtml", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Normalizes HTML to HTML making sure quotes and other specials are entity encoded.
[ "Normalizes", "HTML", "to", "HTML", "making", "sure", "quotes", "and", "other", "specials", "are", "entity", "encoded", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L283-L286
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.normalizeHtmlNospace
public static String normalizeHtmlNospace(SoyValue value) { value = normalizeNull(value); return normalizeHtmlNospace(value.coerceToString()); }
java
public static String normalizeHtmlNospace(SoyValue value) { value = normalizeNull(value); return normalizeHtmlNospace(value.coerceToString()); }
[ "public", "static", "String", "normalizeHtmlNospace", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "normalizeHtmlNospace", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Normalizes HTML to HTML making sure quotes, spaces and other specials are entity encoded so that the result can be safely embedded in a valueless attribute.
[ "Normalizes", "HTML", "to", "HTML", "making", "sure", "quotes", "spaces", "and", "other", "specials", "are", "entity", "encoded", "so", "that", "the", "result", "can", "be", "safely", "embedded", "in", "a", "valueless", "attribute", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L302-L305
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.escapeHtmlAttribute
public static String escapeHtmlAttribute(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.HTML)) { // |escapeHtmlAttribute should only be used on attribute values that cannot have tags. return stripHtmlTags(value.coerceToString(), null, true); } return escapeHtmlAttribute(value.coerceToString()); }
java
public static String escapeHtmlAttribute(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.HTML)) { // |escapeHtmlAttribute should only be used on attribute values that cannot have tags. return stripHtmlTags(value.coerceToString(), null, true); } return escapeHtmlAttribute(value.coerceToString()); }
[ "public", "static", "String", "escapeHtmlAttribute", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "if", "(", "isSanitizedContentOfKind", "(", "value", ",", "SanitizedContent", ".", "ContentKind", ".", "HTML", ")", ...
Converts the input to HTML by entity escaping, stripping tags in sanitized content so the result can safely be embedded in an HTML attribute value.
[ "Converts", "the", "input", "to", "HTML", "by", "entity", "escaping", "stripping", "tags", "in", "sanitized", "content", "so", "the", "result", "can", "safely", "be", "embedded", "in", "an", "HTML", "attribute", "value", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L319-L326
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.escapeHtmlAttributeNospace
public static String escapeHtmlAttributeNospace(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.HTML)) { // |escapeHtmlAttributeNospace should only be used on attribute values that cannot have tags. return stripHtmlTags(value.coerceToString(), null, false); } return escapeHtmlAttributeNospace(value.coerceToString()); }
java
public static String escapeHtmlAttributeNospace(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.HTML)) { // |escapeHtmlAttributeNospace should only be used on attribute values that cannot have tags. return stripHtmlTags(value.coerceToString(), null, false); } return escapeHtmlAttributeNospace(value.coerceToString()); }
[ "public", "static", "String", "escapeHtmlAttributeNospace", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "if", "(", "isSanitizedContentOfKind", "(", "value", ",", "SanitizedContent", ".", "ContentKind", ".", "HTML", ...
Converts plain text to HTML by entity escaping, stripping tags in sanitized content so the result can safely be embedded in an unquoted HTML attribute value.
[ "Converts", "plain", "text", "to", "HTML", "by", "entity", "escaping", "stripping", "tags", "in", "sanitized", "content", "so", "the", "result", "can", "safely", "be", "embedded", "in", "an", "unquoted", "HTML", "attribute", "value", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L356-L363
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.escapeUri
public static String escapeUri(SoyValue value) { value = normalizeNull(value); return escapeUri(value.coerceToString()); }
java
public static String escapeUri(SoyValue value) { value = normalizeNull(value); return escapeUri(value.coerceToString()); }
[ "public", "static", "String", "escapeUri", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "escapeUri", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Converts the input to a piece of a URI by percent encoding the value as UTF-8 bytes.
[ "Converts", "the", "input", "to", "a", "piece", "of", "a", "URI", "by", "percent", "encoding", "the", "value", "as", "UTF", "-", "8", "bytes", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L503-L506
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterNormalizeMediaUri
public static String filterNormalizeMediaUri(String value) { if (EscapingConventions.FilterNormalizeMediaUri.INSTANCE .getValueFilter() .matcher(value) .find()) { return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.escape(value); } logger.log(Level.WARNING, "|filterNormalizeMediaUri received bad value ''{0}''", value); return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.getInnocuousOutput(); }
java
public static String filterNormalizeMediaUri(String value) { if (EscapingConventions.FilterNormalizeMediaUri.INSTANCE .getValueFilter() .matcher(value) .find()) { return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.escape(value); } logger.log(Level.WARNING, "|filterNormalizeMediaUri received bad value ''{0}''", value); return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.getInnocuousOutput(); }
[ "public", "static", "String", "filterNormalizeMediaUri", "(", "String", "value", ")", "{", "if", "(", "EscapingConventions", ".", "FilterNormalizeMediaUri", ".", "INSTANCE", ".", "getValueFilter", "(", ")", ".", "matcher", "(", "value", ")", ".", "find", "(", ...
Checks that a URI is safe to be an image source. <p>Does not return SanitizedContent as there isn't an appropriate type for this.
[ "Checks", "that", "a", "URI", "is", "safe", "to", "be", "an", "image", "source", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L582-L591
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterTrustedResourceUri
public static String filterTrustedResourceUri(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.TRUSTED_RESOURCE_URI)) { return value.coerceToString(); } logger.log(Level.WARNING, "|filterTrustedResourceUri received bad value ''{0}''", value); return "about:invalid#" + EscapingConventions.INNOCUOUS_OUTPUT; }
java
public static String filterTrustedResourceUri(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.TRUSTED_RESOURCE_URI)) { return value.coerceToString(); } logger.log(Level.WARNING, "|filterTrustedResourceUri received bad value ''{0}''", value); return "about:invalid#" + EscapingConventions.INNOCUOUS_OUTPUT; }
[ "public", "static", "String", "filterTrustedResourceUri", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "if", "(", "isSanitizedContentOfKind", "(", "value", ",", "SanitizedContent", ".", "ContentKind", ".", "TRUSTED_RES...
Makes sure the given input is an instance of either trustedResourceUrl or trustedString.
[ "Makes", "sure", "the", "given", "input", "is", "an", "instance", "of", "either", "trustedResourceUrl", "or", "trustedString", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L607-L614
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterImageDataUri
public static SanitizedContent filterImageDataUri(SoyValue value) { value = normalizeNull(value); return filterImageDataUri(value.coerceToString()); }
java
public static SanitizedContent filterImageDataUri(SoyValue value) { value = normalizeNull(value); return filterImageDataUri(value.coerceToString()); }
[ "public", "static", "SanitizedContent", "filterImageDataUri", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "filterImageDataUri", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Makes sure that the given input is a data URI corresponding to an image. <p>SanitizedContent kind does not apply -- the directive is also used to ensure no foreign resources are loaded.
[ "Makes", "sure", "that", "the", "given", "input", "is", "a", "data", "URI", "corresponding", "to", "an", "image", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L652-L655
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterSipUri
public static SanitizedContent filterSipUri(SoyValue value) { value = normalizeNull(value); return filterSipUri(value.coerceToString()); }
java
public static SanitizedContent filterSipUri(SoyValue value) { value = normalizeNull(value); return filterSipUri(value.coerceToString()); }
[ "public", "static", "SanitizedContent", "filterSipUri", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "filterSipUri", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Makes sure that the given input is a sip URI.
[ "Makes", "sure", "that", "the", "given", "input", "is", "a", "sip", "URI", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L670-L673
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterTelUri
public static SanitizedContent filterTelUri(SoyValue value) { value = normalizeNull(value); return filterTelUri(value.coerceToString()); }
java
public static SanitizedContent filterTelUri(SoyValue value) { value = normalizeNull(value); return filterTelUri(value.coerceToString()); }
[ "public", "static", "SanitizedContent", "filterTelUri", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "return", "filterTelUri", "(", "value", ".", "coerceToString", "(", ")", ")", ";", "}" ]
Makes sure that the given input is a tel URI.
[ "Makes", "sure", "that", "the", "given", "input", "is", "a", "tel", "URI", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L706-L709
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterHtmlAttributes
public static String filterHtmlAttributes(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.ATTRIBUTES)) { // We're guaranteed to be in a case where key=value pairs are expected. However, if it would // cause issues to directly abut this with more attributes, add a space. For example: // {$a}{$b} where $a is foo=bar and $b is boo=baz requires a space in between to be parsed // correctly, but not in the case where $a is foo="bar". // TODO: We should be able to get rid of this if the compiler can guarantee spaces between // adjacent print statements in attribute context at compile time. String content = value.coerceToString(); if (content.length() > 0) { if (shouldAppendSpace(content.charAt(content.length() - 1))) { content += ' '; } } return content; } return filterHtmlAttributes(value.coerceToString()); }
java
public static String filterHtmlAttributes(SoyValue value) { value = normalizeNull(value); if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.ATTRIBUTES)) { // We're guaranteed to be in a case where key=value pairs are expected. However, if it would // cause issues to directly abut this with more attributes, add a space. For example: // {$a}{$b} where $a is foo=bar and $b is boo=baz requires a space in between to be parsed // correctly, but not in the case where $a is foo="bar". // TODO: We should be able to get rid of this if the compiler can guarantee spaces between // adjacent print statements in attribute context at compile time. String content = value.coerceToString(); if (content.length() > 0) { if (shouldAppendSpace(content.charAt(content.length() - 1))) { content += ' '; } } return content; } return filterHtmlAttributes(value.coerceToString()); }
[ "public", "static", "String", "filterHtmlAttributes", "(", "SoyValue", "value", ")", "{", "value", "=", "normalizeNull", "(", "value", ")", ";", "if", "(", "isSanitizedContentOfKind", "(", "value", ",", "SanitizedContent", ".", "ContentKind", ".", "ATTRIBUTES", ...
Checks that the input is a valid HTML attribute name with normal keyword or textual content or known safe attribute content.
[ "Checks", "that", "the", "input", "is", "a", "valid", "HTML", "attribute", "name", "with", "normal", "keyword", "or", "textual", "content", "or", "known", "safe", "attribute", "content", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L727-L745
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.filterHtmlAttributes
public static String filterHtmlAttributes(String value) { if (EscapingConventions.FilterHtmlAttributes.INSTANCE.getValueFilter().matcher(value).find()) { return value; } logger.log(Level.WARNING, "|filterHtmlAttributes received bad value ''{0}''", value); return EscapingConventions.FilterHtmlAttributes.INSTANCE.getInnocuousOutput(); }
java
public static String filterHtmlAttributes(String value) { if (EscapingConventions.FilterHtmlAttributes.INSTANCE.getValueFilter().matcher(value).find()) { return value; } logger.log(Level.WARNING, "|filterHtmlAttributes received bad value ''{0}''", value); return EscapingConventions.FilterHtmlAttributes.INSTANCE.getInnocuousOutput(); }
[ "public", "static", "String", "filterHtmlAttributes", "(", "String", "value", ")", "{", "if", "(", "EscapingConventions", ".", "FilterHtmlAttributes", ".", "INSTANCE", ".", "getValueFilter", "(", ")", ".", "matcher", "(", "value", ")", ".", "find", "(", ")", ...
Checks that the input is a valid HTML attribute name with normal keyword or textual content.
[ "Checks", "that", "the", "input", "is", "a", "valid", "HTML", "attribute", "name", "with", "normal", "keyword", "or", "textual", "content", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L754-L760
train
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.isSanitizedContentOfKind
private static boolean isSanitizedContentOfKind( SoyValue value, SanitizedContent.ContentKind kind) { return value instanceof SanitizedContent && kind == ((SanitizedContent) value).getContentKind(); }
java
private static boolean isSanitizedContentOfKind( SoyValue value, SanitizedContent.ContentKind kind) { return value instanceof SanitizedContent && kind == ((SanitizedContent) value).getContentKind(); }
[ "private", "static", "boolean", "isSanitizedContentOfKind", "(", "SoyValue", "value", ",", "SanitizedContent", ".", "ContentKind", "kind", ")", "{", "return", "value", "instanceof", "SanitizedContent", "&&", "kind", "==", "(", "(", "SanitizedContent", ")", "value", ...
True iff the given value is sanitized content of the given kind.
[ "True", "iff", "the", "given", "value", "is", "sanitized", "content", "of", "the", "given", "kind", "." ]
cc61e1dff70ae97f24f417a57410081bc498bd56
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L877-L880
train