idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
30,400
public static boolean isEmptyCriteria ( final Criteria criteria ) { return isEmpty ( criteria . getAliases ( ) ) && isEmpty ( criteria . getDeviceTypes ( ) ) && isEmpty ( criteria . getCategories ( ) ) ; }
Helper method to check if all criteria are empty . Useful in FCM land where we use topics .
30,401
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 ; }
Receives the dashboard data for the given user
30,402
public List < ApplicationVariant > getVariantsWithWarnings ( ) { final List < String > warningIDs = flatPushMessageInformationDao . findVariantIDsWithWarnings ( ) ; if ( warningIDs . isEmpty ( ) ) { return Collections . emptyList ( ) ; } return wrapApplicationVariant ( pushApplicationDao . findByVariantIds ( warningIDs ) ) ; }
Loads all the Variant objects where we did notice some failures on sending for the given user
30,403
@ 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 info about submitted push messages for the given Push Application
30,404
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 ; } }
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 .
30,405
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 ; } }
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 .
30,406
@ Produces ( MediaType . APPLICATION_JSON ) public Response listAllWindowsVariationsForPushApp ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { final PushApplication application = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; return Response . ok ( getVariants ( application ) ) . build ( ) ; }
List Windows Variants for Push Application
30,407
@ 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 ) { try { validateModelClass ( updatedWindowsVariant ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Windows Variant '{}'" , windowsVariant . getVariantID ( ) ) ; logger . debug ( "Details: {}" , cve ) ; Response . ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } 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 ( ) ; }
Update Windows Variant
30,408
protected void sendNonTransacted ( Destination destination , Serializable message ) { send ( destination , message , null , null , false ) ; }
Sends message to the destination in non - transactional manner .
30,409
protected void sendTransacted ( Destination destination , Serializable message ) { send ( destination , message , null , null , true ) ; }
Sends message to the destination in transactional manner .
30,410
protected void sendNonTransacted ( Destination destination , Serializable message , String propertyName , String propertValue ) { send ( destination , message , propertyName , propertValue , false ) ; }
Sends message to destination with given JMS message property name and value in non - transactional manner .
30,411
protected void sendTransacted ( Destination destination , Serializable message , String propertyName , String propertValue ) { send ( destination , message , propertyName , propertValue , true ) ; }
Sends message to destination with given JMS message property name and value in transactional manner .
30,412
public void disconnectOnChange ( 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 ) ; } }
Receives iOS variant change event to remove client from the cache and also tear down the connection .
30,413
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 ) ; }
Finder for send used for Android and iOS clients
30,414
@ 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 Installation of specified Variant
30,415
@ 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 ( ) ; }
Update Installation of specified Variant
30,416
@ Path ( "/{variantId}/installations/" ) @ Produces ( MediaType . APPLICATION_JSON ) public Response exportInstallations ( @ PathParam ( "variantId" ) String variantId ) { return Response . ok ( getSearch ( ) . findAllInstallationsByVariantForDeveloper ( variantId , 0 , Integer . MAX_VALUE , null ) . getResultList ( ) ) . build ( ) ; }
Endpoint for exporting as JSON file device installations for a given variant . Only Keycloak authenticated can access it
30,417
private void processFCM ( AndroidVariant androidVariant , List < String > pushTargets , Message fcmMessage , ConfigurableFCMSender sender ) throws IOException { if ( pushTargets . get ( 0 ) . startsWith ( Constants . TOPIC_PREFIX ) ) { 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 ) ; cleanupInvalidRegistrationIDsForVariant ( androidVariant . getVariantID ( ) , multicastResult , pushTargets ) ; } }
Process the HTTP POST to the FCM infrastructure for the given list of registrationIDs .
30,418
@ 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 ( ) ; }
Create Push Application
30,419
@ 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 ( ) ; }
List Push Applications
30,420
@ 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 Push Application .
30,421
@ 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 ) { try { validateModelClass ( updatedPushApp ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Push Application '{}'" , pushApplicationID ) ; logger . debug ( "Details: {}" , cve ) ; ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } 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 ( ) ; }
Update Push Application
30,422
@ Path ( "/{pushAppID}/reset" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response resetMasterSecret ( @ PathParam ( "pushAppID" ) String pushApplicationID ) { PushApplication pushApp = getSearch ( ) . findByPushApplicationIDForDeveloper ( pushApplicationID ) ; if ( pushApp != null ) { 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 ( ) ; }
Reset MasterSecret for Push Application
30,423
@ 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 Push Application
30,424
@ 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 ( ) ; }
Count Push Applications
30,425
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 ; }
Validates that configuration is correct with regards to push networks limitations or implementation etc .
30,426
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 .
30,427
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\"]" ; } }
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 .
30,428
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 ) ; 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\"]" ; } }
Returns a minimized JSON representation of the payload . This does not include potentially large objects like alias or category from the given criteria .
30,429
protected void validateModelClass ( Object model ) { final Set < ConstraintViolation < Object > > violations = validator . validate ( model ) ; if ( ! violations . isEmpty ( ) ) { throw new ConstraintViolationException ( new HashSet < > ( violations ) ) ; } }
Generic validator used to identify constraint violations of the given model class .
30,430
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 ) ; }
Helper function to create a 400 Bad Request response containing a JSON map giving details about the violations
30,431
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 ) ; } }
Checks that the end context of a block is compatible with its start context .
30,432
static void inferStrictRenderUnitNode ( RenderUnitNode node , Inferences inferences , ErrorReporter errorReporter ) { InferenceEngine inferenceEngine = new InferenceEngine ( inferences , errorReporter ) ; Context endContext = inferenceEngine . inferChildren ( node , Context . getStartContextForContentKind ( node . getContentKind ( ) ) ) ; checkBlockEndContext ( node , endContext ) ; }
Applies strict contextual autoescaping to the given node s children .
30,433
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 ; }
Validates that the provided format matches a supported format and returns the value if not this throws an exception .
30,434
private ProtoClass clazz ( ) { ProtoClass localClazz = clazz ; if ( localClazz == null ) { localClazz = classCache . getUnchecked ( proto . getDescriptorForType ( ) ) ; clazz = localClazz ; } return localClazz ; }
it if we can
30,435
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 ) ; }
Gets a value for the field for the underlying proto object . Not intended for general use .
30,436
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 ( ) ; }
Returns the set of fields indexed by soy accessor name for the given type .
30,437
private Optional < SoyType > soyTypeForProtoOrEnum ( Class < ? > type , Method method ) { 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 ) ; }
Attempts to discover the SoyType for a proto or proto enum reporting an error if unable to .
30,438
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 ; }
Returns true if the type is the given kind or contains the given kind .
30,439
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 ) ; }
Returns the Java name for a proto field .
30,440
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 ) { result . append ( ( char ) ( ch + ( 'a' - 'A' ) ) ) ; } else { result . append ( ch ) ; } capitializeNextLetter = false ; } else if ( '0' <= ch && ch <= '9' ) { result . append ( ch ) ; capitializeNextLetter = true ; } else { capitializeNextLetter = true ; } } return result . toString ( ) ; }
Converts underscore field names to camel case while preserving camel case field names .
30,441
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 ; }
Used by the other overload descends recursively into messages .
30,442
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 ; }
Checks whether any generated classes conflict with the given name .
30,443
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" ) ; } }
Gets a IntegerData instance for the given value .
30,444
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 ; }
Generates the Python expression for a given call .
30,445
protected PyExpr visitCallBasicNode ( CallBasicNode node ) { String calleeName = node . getCalleeName ( ) ; String calleeExprText ; TemplateNode template = getTemplateIfInSameFile ( node ) ; if ( template != null ) { calleeExprText = getLocalTemplateName ( template ) ; } else { int secondToLastDotIndex = calleeName . lastIndexOf ( '.' , calleeName . lastIndexOf ( '.' ) - 1 ) ; calleeExprText = calleeName . substring ( secondToLastDotIndex + 1 ) ; } String callExprText = calleeExprText + "(" + genObjToPass ( node ) + ", ijData)" ; return escapeCall ( callExprText , node . getEscapingDirectives ( ) ) ; }
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 .
30,446
protected PyExpr visitCallDelegateNode ( CallDelegateNode node ) { ExprRootNode variantSoyExpr = node . getDelCalleeVariantExpr ( ) ; PyExpr variantPyExpr ; if ( variantSoyExpr == null ) { variantPyExpr = new PyStringExpr ( "''" ) ; } else { 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 ( ) ) ; }
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 .
30,447
public String genObjToPass ( CallNode callNode ) { TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarStack , pluginValueFactory , errorReporter ) ; String dataToPass ; if ( callNode . isPassingAllData ( ) ) { dataToPass = "data" ; } else if ( callNode . isPassingData ( ) ) { dataToPass = translator . exec ( callNode . getDataExpr ( ) ) . getText ( ) ; } else { dataToPass = "{}" ; } 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 { String paramExpr = "param" + cpcn . getId ( ) ; valuePyExpr = new PyListExpr ( paramExpr , Integer . MAX_VALUE ) ; } 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 ) ; if ( callNode . isPassingData ( ) ) { if ( callNode . numChildren ( ) > 0 ) { dataToPass = "dict(" + dataToPass + ")" ; dataToPass = "runtime.merge_into_dict(" + dataToPass + ", " + additionalParamsExpr . getText ( ) + ")" ; } if ( ! defaultParams . isEmpty ( ) ) { PyExpr defaultParamsExpr = PyExprUtils . convertMapToPyExpr ( defaultParams ) ; dataToPass = "runtime.merge_into_dict(" + defaultParamsExpr . getText ( ) + ", " + dataToPass + ")" ; } return dataToPass ; } else { return additionalParamsExpr . getText ( ) ; } }
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 .
30,448
private PyExpr escapeCall ( String callExpr , ImmutableList < SoyPrintDirective > directives ) { PyExpr escapedExpr = new PyExpr ( callExpr , Integer . MAX_VALUE ) ; if ( directives . isEmpty ( ) ) { return escapedExpr ; } 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 ; }
Escaping directives might apply to the output of the call node so wrap the output with all required directives .
30,449
static String getLocalTemplateName ( TemplateNode node ) { String templateName = node . getPartialTemplateName ( ) . substring ( 1 ) ; if ( node . getVisibility ( ) == Visibility . PRIVATE ) { return "__" + templateName ; } return templateName ; }
Returns the python name for the template . Suitable for calling within the same module .
30,450
void checkConformance ( ) { resetErrorReporter ( ) ; parse ( passManagerBuilder ( ) . disableAllTypeChecking ( ) . addPassContinuationRule ( SoyConformancePass . class , PassContinuationRule . STOP_AFTER_PASS ) ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; }
A simple tool to enforce conformance and only conformance .
30,451
public void extractAndWriteMsgs ( SoyMsgBundleHandler msgBundleHandler , OutputFileOptions options , ByteSink output ) throws IOException { resetErrorReporter ( ) ; SoyMsgBundle bundle = doExtractMsgs ( ) ; msgBundleHandler . writeExtractedMsgs ( bundle , options , output , errorReporter ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; }
Extracts all messages from this Soy file set and writes the messages to an output sink .
30,452
private SoyMsgBundle doExtractMsgs ( ) { SoyFileSetNode soyTree = parse ( passManagerBuilder ( ) . allowUnknownGlobals ( ) . allowV1Expression ( ) . setTypeRegistry ( SoyTypeRegistry . DEFAULT_UNKNOWN ) . setPluginResolver ( new PluginResolver ( PluginResolver . Mode . ALLOW_UNDEFINED , printDirectives , soyFunctionMap , soySourceFunctionMap , errorReporter ) ) . disableAllTypeChecking ( ) , SoyTypeRegistry . DEFAULT_UNKNOWN ) . fileSet ( ) ; throwIfErrorsPresent ( ) ; SoyMsgBundle bundle = new ExtractMsgsVisitor ( ) . exec ( soyTree ) ; throwIfErrorsPresent ( ) ; return bundle ; }
Performs the parsing and extraction logic .
30,453
private ServerCompilationPrimitives compileForServerRendering ( ) { ParseResult result = parse ( ) ; throwIfErrorsPresent ( ) ; SoyFileSetNode soyTree = result . fileSet ( ) ; TemplateRegistry registry = result . registry ( ) ; if ( cache == null ) { new ClearSoyDocStringsVisitor ( ) . exec ( soyTree ) ; } throwIfErrorsPresent ( ) ; return new ServerCompilationPrimitives ( registry , soyTree ) ; }
Runs common compiler logic shared by tofu and jbcsrc backends .
30,454
public List < String > compileToIncrementalDomSrc ( SoyIncrementalDomSrcOptions jsSrcOptions ) { resetErrorReporter ( ) ; 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 ; }
Compiles this Soy file set into iDOM source code files and returns these JS files as a list of strings one per file .
30,455
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 ( ) ; }
Compiles this Soy file set into Python source code files and writes these Python files to disk .
30,456
ParseResult compileMinimallyForHeaders ( ) { resetErrorReporter ( ) ; ParseResult result = parse ( passManagerBuilder ( ) . addPassContinuationRule ( ResolveExpressionTypesPass . class , PassContinuationRule . STOP_AFTER_PASS ) . allowV1Expression ( ) , typeRegistry ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; return result ; }
Performs the minimal amount of work needed to calculate TemplateMetadata objects for header compilation .
30,457
private void reportWarnings ( ) { ImmutableList < SoyError > warnings = errorReporter . getWarnings ( ) ; if ( warnings . isEmpty ( ) ) { return ; } 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 ) ; } }
Reports warnings ot the user configured warning sink . Should be called at the end of successful compiles .
30,458
@ SuppressWarnings ( "unchecked" ) public synchronized < T > T intern ( T value ) { Preconditions . checkNotNull ( value ) ; 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 ) { 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 ++ ; } }
Returns either the input or an instance that equals it that was previously passed to this method .
30,459
@ GuardedBy ( "this" ) private void rehashIfNeeded ( ) { int currentSize = table . length ; if ( currentSize - count >= currentSize / ( MAX_EXPECTED_COLLISION_COUNT + 1 ) ) { return ; } Object [ ] oldTable = table ; int newSize = currentSize + currentSize / GROWTH_DENOMINATOR ; table = new Object [ newSize ] ; count = 0 ; for ( Object element : oldTable ) { if ( element != null ) { intern ( element ) ; } } }
Doubles the table size .
30,460
private Statement handleBasicTranslation ( List < SoyPrintDirective > escapingDirectives , Expression soyMsgParts ) { SoyExpression text = SoyExpression . forString ( soyMsgParts . invoke ( MethodRef . LIST_GET , constant ( 0 ) ) . checkedCast ( SoyMsgRawTextPart . class ) . invoke ( MethodRef . SOY_MSG_RAW_TEXT_PART_GET_RAW_TEXT ) ) ; for ( SoyPrintDirective directive : escapingDirectives ) { text = parameterLookup . getRenderContext ( ) . applyPrintDirective ( directive , text ) ; } return appendableExpression . appendString ( text . coerceToString ( ) ) . toStatement ( ) ; }
Handles a translation consisting of a single raw text node .
30,461
private Statement handleTranslationWithPlaceholders ( MsgNode msg , ImmutableList < SoyPrintDirective > escapingDirectives , Expression soyMsgParts , Expression locale , MsgPartsAndIds partsAndId ) { Map < String , Function < Expression , Statement > > placeholderNameToPutStatement = new LinkedHashMap < > ( ) ; putPlaceholdersIntoMap ( msg , partsAndId . parts , placeholderNameToPutStatement ) ; 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 , 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 , variables . getCurrentRenderee ( ) . putInstanceField ( thisVar , BytecodeUtils . constantNull ( ConstructorRef . MSG_RENDERER . instanceClass ( ) . type ( ) ) ) ) ; }
Handles a complex message with placeholders .
30,462
private Function < Expression , Statement > addNodeToPlaceholderMap ( String mapKey , StandaloneNode node ) { return putToMapFunction ( mapKey , placeholderCompiler . compileToSoyValueProvider ( mapKey , node , ExtraCodeCompiler . NO_OP , ExtraCodeCompiler . NO_OP ) ) ; }
Returns a statement that adds the content rendered by the call to the map .
30,463
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 ) { 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 ) ; }
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 .
30,464
static JsExpr wrapWithFunction ( String functionExprText , JsExpr jsExpr ) { Preconditions . checkNotNull ( functionExprText ) ; return new JsExpr ( functionExprText + "(" + jsExpr . getText ( ) + ")" , Integer . MAX_VALUE ) ; }
Wraps an expression in a function call .
30,465
@ SuppressWarnings ( "unchecked" ) private int mergeRange ( ParentSoyNode < ? > parent , int start , int lastNonEmptyRawTextNode , int end ) { checkArgument ( start < end ) ; if ( start == - 1 || end == start + 1 ) { return 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 ; }
RawTextNodes and if we can remove a RawTextNode we can also add one .
30,466
public void writeEntry ( String path , ByteSource contents ) throws IOException { stream . putNextEntry ( new ZipEntry ( path ) ) ; contents . copyTo ( stream ) ; stream . closeEntry ( ) ; }
Writes a single entry to the jar .
30,467
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 ; }
Returns a simple jar manifest .
30,468
private void addTypeSubstitutions ( Map < Wrapper < ExprNode > , SoyType > substitutionsToAdd ) { for ( Map . Entry < Wrapper < ExprNode > , SoyType > entry : substitutionsToAdd . entrySet ( ) ) { ExprNode expr = entry . getKey ( ) . get ( ) ; 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 ( ! entry . getValue ( ) . equals ( previousType ) ) { substitutions = new TypeSubstitution ( substitutions , expr , entry . getValue ( ) ) ; } } }
active substitutions .
30,469
private SoyType getElementType ( SoyType collectionType , ForNonemptyNode node ) { Preconditions . checkNotNull ( collectionType ) ; switch ( collectionType . getKind ( ) ) { case UNKNOWN : 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 : { 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 ( ) ) ; return ErrorType . getInstance ( ) ; } }
Given a collection type compute the element type .
30,470
public SoySauceBuilder withPluginInstances ( Map < String , Supplier < Object > > pluginInstances ) { this . userPluginInstances = ImmutableMap . copyOf ( pluginInstances ) ; return this ; }
Sets the plugin instance factories to be used when constructing the SoySauce .
30,471
SoySauceBuilder withFunctions ( Map < String , ? extends SoyFunction > userFunctions ) { this . userFunctions = ImmutableMap . copyOf ( userFunctions ) ; return this ; }
Sets the user functions .
30,472
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 .
30,473
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 , ImmutableMap . < String , SoyPrintDirective > builder ( ) . putAll ( InternalPlugins . internalDirectiveMap ( scopedData ) ) . putAll ( userDirectives ) . build ( ) , userPluginInstances ) ; }
Creates a SoySauce .
30,474
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 ) ; } }
Walks all resources with the META_INF_DELTEMPLATE_PATH and collects the deltemplates .
30,475
public boolean exec ( TemplateNode template ) { boolean hasOptional = false ; for ( TemplateParam param : template . getParams ( ) ) { if ( param . isRequired ( ) ) { return false ; } else { hasOptional = true ; } } if ( hasOptional ) { return true ; } return new AbstractNodeVisitor < Node , Boolean > ( ) { boolean shouldEnsureDataIsDefined ; public Boolean exec ( Node node ) { visit ( node ) ; return shouldEnsureDataIsDefined ; } public void visit ( Node node ) { if ( node instanceof VarRefNode ) { VarRefNode varRefNode = ( VarRefNode ) node ; VarDefn var = varRefNode . getDefnDecl ( ) ; if ( varRefNode . isPossibleHeaderVar ( ) && var . kind ( ) != VarDefn . Kind . STATE && ( var . kind ( ) != VarDefn . Kind . PARAM || ! ( ( TemplateParam ) var ) . isInjected ( ) ) ) { 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 ) ; }
Runs this pass on the given template .
30,476
static void checkId ( String id ) { if ( ! ID . matcher ( id ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "not a valid js identifier: %s" , id ) ) ; } }
Validates that the given string is a valid javascript identifier .
30,477
Iterable < ClassData > compile ( ) { List < ClassData > classes = new ArrayList < > ( ) ; if ( templateNode . getVisibility ( ) != Visibility . PRIVATE ) { 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 ; }
Returns the list of classes needed to implement this template .
30,478
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 ( ) { protected void doGen ( CodeBuilder ga ) { ga . mark ( start ) ; 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 ) ; }
Generate a public constructor that assigns our final field and checks for missing required params .
30,479
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 ) ; if ( Flags . DEBUG ) { int i = 0 ; for ( Expression expr : exprs ) { expr . checkAssignableTo ( types . get ( i ) , "Parameter %s" , i ) ; i ++ ; } } }
Checks that the given expressions are compatible with the given types .
30,480
public Statement toStatement ( ) { return new Statement ( ) { 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 ( ) ; } } } ; }
Convert this expression to a statement by executing it and throwing away the result .
30,481
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 ( ) ) { protected void doGen ( CodeBuilder adapter ) { Expression . this . gen ( adapter ) ; if ( resultType ( ) . equals ( BytecodeUtils . SOY_STRING_TYPE ) ) { MethodRef . RUNTIME_CHECK_SOY_STRING . invokeUnchecked ( adapter ) ; } else { adapter . checkCast ( resultType ( ) ) ; } } } ; }
Returns an expression that performs a checked cast from the current type to the target type .
30,482
public Expression labelStart ( final Label label ) { return new Expression ( resultType ( ) , features ) { protected void doGen ( CodeBuilder adapter ) { adapter . mark ( label ) ; Expression . this . gen ( adapter ) ; } } ; }
Returns a new expression identical to this one but with the given label applied at the start of the expression .
30,483
public void setParamsToRuntimeCheck ( Predicate < String > paramNames ) { checkState ( this . paramsToRuntimeTypeCheck == null ) ; this . paramsToRuntimeTypeCheck = checkNotNull ( paramNames ) ; }
Sets the names of the params that require runtime type checking against callee s types .
30,484
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 ) ; }
Normalizes the input HTML while preserving safe tags and the known directionality .
30,485
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 .
30,486
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 ) ; }
Normalizes the input HTML of a given directionality while preserving safe tags .
30,487
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 .
30,488
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 .
30,489
public static String escapeHtmlAttribute ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . HTML ) ) { return stripHtmlTags ( value . coerceToString ( ) , null , true ) ; } return escapeHtmlAttribute ( value . coerceToString ( ) ) ; }
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 .
30,490
public static String escapeHtmlAttributeNospace ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . HTML ) ) { return stripHtmlTags ( value . coerceToString ( ) , null , false ) ; } return escapeHtmlAttributeNospace ( value . coerceToString ( ) ) ; }
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 .
30,491
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 .
30,492
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 ( ) ; }
Checks that a URI is safe to be an image source .
30,493
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 ; }
Makes sure the given input is an instance of either trustedResourceUrl or trustedString .
30,494
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 .
30,495
public static SanitizedContent filterSipUri ( SoyValue value ) { value = normalizeNull ( value ) ; return filterSipUri ( value . coerceToString ( ) ) ; }
Makes sure that the given input is a sip URI .
30,496
public static SanitizedContent filterTelUri ( SoyValue value ) { value = normalizeNull ( value ) ; return filterTelUri ( value . coerceToString ( ) ) ; }
Makes sure that the given input is a tel URI .
30,497
public static String filterHtmlAttributes ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . ATTRIBUTES ) ) { String content = value . coerceToString ( ) ; if ( content . length ( ) > 0 ) { if ( shouldAppendSpace ( content . charAt ( content . length ( ) - 1 ) ) ) { content += ' ' ; } } return content ; } return filterHtmlAttributes ( value . coerceToString ( ) ) ; }
Checks that the input is a valid HTML attribute name with normal keyword or textual content or known safe attribute content .
30,498
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 ( ) ; }
Checks that the input is a valid HTML attribute name with normal keyword or textual content .
30,499
private static boolean isSanitizedContentOfKind ( SoyValue value , SanitizedContent . ContentKind kind ) { return value instanceof SanitizedContent && kind == ( ( SanitizedContent ) value ) . getContentKind ( ) ; }
True iff the given value is sanitized content of the given kind .