idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,300
public RequestToken login ( BaasHandler < BaasUser > handler ) { return login ( null , RequestOptions . DEFAULT , handler ) ; }
Asynchronously logins this user . The handler will be invoked upon completion of the request .
2,301
public RequestToken login ( String registrationId , BaasHandler < BaasUser > handler ) { return login ( registrationId , RequestOptions . DEFAULT , handler ) ; }
Asynchronously logins this user with password and registrationId obtained through gcm . The handler will be invoked upon completion of the request .
2,302
public RequestToken login ( String regitrationId , int flags , BaasHandler < BaasUser > handler ) { BaasBox box = BaasBox . getDefault ( ) ; if ( password == null ) throw new IllegalStateException ( "password cannot be null" ) ; NetworkTask < BaasUser > task = new LoginRequest ( box , this , regitrationId , flags , handler ) ; return box . submitAsync ( task ) ; }
Asynchronously logins the user with password and registrationId obtained through gcm . The handler will be invoked upon completion of the request . The request is executed at the gien priority .
2,303
public BaasResult < BaasUser > loginSync ( String registrationId ) { BaasBox box = BaasBox . getDefault ( ) ; if ( password == null ) throw new IllegalStateException ( "password cannot be null" ) ; NetworkTask < BaasUser > task = new LoginRequest ( box , this , registrationId , RequestOptions . DEFAULT , null ) ; return box . submitSync ( task ) ; }
Synchronously logins the user with password and registrationId obtained through gcm .
2,304
public BaasResult < Void > logoutSync ( String registration ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; LogoutRequest request = new LogoutRequest ( box , this , registration , RequestOptions . DEFAULT , null ) ; return box . submitSync ( request ) ; }
Synchronously logouts current user from the server .
2,305
public RequestToken save ( int flags , BaasHandler < BaasUser > handler ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; SaveUser task = new SaveUser ( box , this , flags , handler ) ; return box . submitAsync ( task ) ; }
Asynchronously saves the updates made to the current user .
2,306
public BaasResult < BaasUser > saveSync ( ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; SaveUser task = new SaveUser ( box , this , RequestOptions . DEFAULT , null ) ; return box . submitSync ( task ) ; }
Synchronously saves the updates made to the current user .
2,307
public RequestToken signup ( int flags , BaasHandler < BaasUser > handler ) { return signupWithStrategy ( flags , DefaultSignupStrategy . INSTANCE , handler ) ; }
Asynchronously signups this user to baasbox using provided password and priority
2,308
public RequestToken unfollow ( int flags , BaasHandler < BaasUser > handler ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; Follow follow = new Follow ( box , false , this , flags , handler ) ; return box . submitAsync ( follow ) ; }
Asynchronously requests to unfollow the user
2,309
public int get ( int index ) { if ( d_bitsPerElem == 0 ) return 0 ; int startIdx = ( index * d_bitsPerElem ) / INT_SIZE ; int startBit = ( index * d_bitsPerElem ) % INT_SIZE ; int result = ( d_data [ startIdx ] >>> startBit ) & MASK [ d_bitsPerElem ] ; if ( ( startBit + d_bitsPerElem ) > INT_SIZE ) { int done = INT_SIZE - startBit ; result |= ( d_data [ startIdx + 1 ] & MASK [ d_bitsPerElem - done ] ) << done ; } return result ; }
Get the integer at the given index .
2,310
public GetServiceStatusResult withMessages ( Message ... values ) { List < Message > list = getMessages ( ) ; for ( Message value : values ) { list . add ( value ) ; } return this ; }
Add values for Messages return this .
2,311
private void appendValue ( Object value ) { if ( value instanceof Boolean ) { closeTag ( ) ; append ( value . toString ( ) ) ; } else if ( value instanceof Number ) { closeTag ( ) ; append ( value . toString ( ) ) ; } else if ( value instanceof String ) { closeTag ( ) ; escape ( ( String ) value ) ; } else if ( value instanceof MwsObject ) { ( ( MwsObject ) value ) . writeFragmentTo ( this ) ; } else if ( value instanceof Node ) { closeTag ( ) ; append ( MwsUtl . toXmlString ( ( Node ) value ) ) ; } else if ( value instanceof Enum ) { closeTag ( ) ; append ( ( ( Enum < ? > ) value ) . toString ( ) ) ; } else if ( value instanceof XMLGregorianCalendar ) { closeTag ( ) ; append ( ( ( XMLGregorianCalendar ) value ) . toXMLFormat ( ) ) ; } else { throw new IllegalArgumentException ( ) ; } }
Append a value to output .
2,312
protected void append ( String v ) { try { writer . write ( v ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Append a string to the output .
2,313
protected void append ( String v , int start , int end ) { try { writer . write ( v , start , end - start ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Append range of a string to the output .
2,314
private void addRequiredParametersToRequest ( HttpPost request ) { parameters . put ( "Action" , operationName ) ; parameters . put ( "Version" , serviceEndpoint . version ) ; parameters . put ( "Timestamp" , MwsUtl . getFormattedTimestamp ( ) ) ; parameters . put ( "AWSAccessKeyId" , connection . getAwsAccessKeyId ( ) ) ; String signature = MwsUtl . signParameters ( serviceEndpoint . uri , connection . getSignatureVersion ( ) , connection . getSignatureMethod ( ) , parameters , connection . getAwsSecretKeyId ( ) ) ; parameters . put ( "Signature" , signature ) ; List < NameValuePair > parameterList = new ArrayList < NameValuePair > ( ) ; for ( Entry < String , String > entry : parameters . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( ! ( key == null || key . equals ( "" ) || value == null || value . equals ( "" ) ) ) { parameterList . add ( new BasicNameValuePair ( key , value ) ) ; } } try { request . setEntity ( new UrlEncodedFormEntity ( parameterList , "UTF-8" ) ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Add authentication related and version parameter and set request body with all of the parameters
2,315
private String getResponseBody ( HttpResponse postResponse ) { InputStream input = null ; try { input = postResponse . getEntity ( ) . getContent ( ) ; Reader reader = new InputStreamReader ( input , MwsUtl . DEFAULT_ENCODING ) ; StringBuilder b = new StringBuilder ( ) ; char [ ] c = new char [ 1024 ] ; int len ; while ( 0 < ( len = reader . read ( c ) ) ) { b . append ( c , 0 , len ) ; } return b . toString ( ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } finally { MwsUtl . close ( input ) ; } }
Read stream into string
2,316
private MwsResponseHeaderMetadata getResponseHeaderMetadata ( HttpResponse response ) { Header requestIdHeader = response . getFirstHeader ( "x-mws-request-id" ) ; String requestId = requestIdHeader == null ? null : requestIdHeader . getValue ( ) ; Header timestampHeader = response . getFirstHeader ( "x-mws-timestamp" ) ; String timestamp = timestampHeader == null ? null : timestampHeader . getValue ( ) ; Header contextHeader = response . getFirstHeader ( "x-mws-response-context" ) ; String contextString = contextHeader == null ? "" : contextHeader . getValue ( ) ; List < String > context = Collections . unmodifiableList ( Arrays . asList ( contextString . split ( "," ) ) ) ; Double quotaMax ; try { Header quotaMaxHeader = response . getFirstHeader ( "x-mws-quota-max" ) ; quotaMax = quotaMaxHeader == null ? null : Double . valueOf ( quotaMaxHeader . getValue ( ) ) ; } catch ( NumberFormatException ex ) { quotaMax = null ; } Double quotaRemaining ; try { Header quotaRemainingHeader = response . getFirstHeader ( "x-mws-quota-remaining" ) ; quotaRemaining = quotaRemainingHeader == null ? null : Double . valueOf ( quotaRemainingHeader . getValue ( ) ) ; } catch ( NumberFormatException ex ) { quotaRemaining = null ; } Date quotaResetDate ; try { Header quotaResetHeader = response . getFirstHeader ( "x-mws-quota-resetsOn" ) ; quotaResetDate = quotaResetHeader == null ? null : MwsUtl . parseTimestamp ( quotaResetHeader . getValue ( ) ) ; } catch ( java . text . ParseException ex ) { quotaResetDate = null ; } return new MwsResponseHeaderMetadata ( requestId , context , timestamp , quotaMax , quotaRemaining , quotaResetDate ) ; }
Get the metadata from the response headers .
2,317
private boolean pauseIfRetryNeeded ( int retries ) { if ( retries >= connection . getMaxErrorRetry ( ) ) { return false ; } long delay = ( long ) ( Math . random ( ) * Math . pow ( 4 , retries ) * 125 ) ; try { Thread . sleep ( delay ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } return true ; }
Random exponential back - off sleep on failed request .
2,318
private HttpPost createRequest ( ) { HttpPost request = new HttpPost ( serviceEndpoint . uri ) ; try { request . addHeader ( "Content-Type" , "application/x-www-form-urlencoded; charset=utf-8" ) ; request . addHeader ( "X-Amazon-User-Agent" , connection . getUserAgent ( ) ) ; for ( Map . Entry < String , String > header : connection . getRequestHeaders ( ) . entrySet ( ) ) { request . addHeader ( header . getKey ( ) , header . getValue ( ) ) ; } addRequiredParametersToRequest ( request ) ; } catch ( Exception e ) { request . releaseConnection ( ) ; throw MwsUtl . wrap ( e ) ; } return request ; }
Create a HttpPost request for this call and add required headers and parameters to it .
2,319
private HttpResponse executeRequest ( HttpPost request ) throws Exception { try { HttpClient httpClient = connection . getHttpClient ( ) ; HttpContext httpContext = connection . getHttpContext ( ) ; HttpResponse response = httpClient . execute ( request , httpContext ) ; return response ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Execute a request on this calls connection and context .
2,320
public MwsResponse execute ( ) { HttpPost request = createRequest ( ) ; try { HttpResponse hr = executeRequest ( request ) ; StatusLine statusLine = hr . getStatusLine ( ) ; int status = statusLine . getStatusCode ( ) ; String message = statusLine . getReasonPhrase ( ) ; rhmd = getResponseHeaderMetadata ( hr ) ; String body = getResponseBody ( hr ) ; MwsResponse response = new MwsResponse ( status , message , rhmd , body ) ; return response ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } finally { request . releaseConnection ( ) ; } }
Perform a synchronous call with no retry or error handling .
2,321
private static String calculateStringToSignV0 ( Map < String , String > parameters ) { StringBuilder data = new StringBuilder ( ) ; data . append ( parameters . get ( "Action" ) ) . append ( parameters . get ( "Timestamp" ) ) ; return data . toString ( ) ; }
Calculate String to Sign for SignatureVersion 0
2,322
private static String calculateStringToSignV1 ( Map < String , String > parameters ) { StringBuilder data = new StringBuilder ( ) ; Map < String , String > sorted = new TreeMap < String , String > ( String . CASE_INSENSITIVE_ORDER ) ; sorted . putAll ( parameters ) ; Iterator < Entry < String , String > > pairs = sorted . entrySet ( ) . iterator ( ) ; while ( pairs . hasNext ( ) ) { Map . Entry < String , String > pair = pairs . next ( ) ; data . append ( pair . getKey ( ) ) ; data . append ( pair . getValue ( ) ) ; } return data . toString ( ) ; }
Calculate String to Sign for SignatureVersion 1
2,323
static String calculateStringToSignV2 ( URI serviceUri , Map < String , String > parameters ) { StringBuilder data = new StringBuilder ( ) ; data . append ( "POST" ) ; data . append ( "\n" ) ; data . append ( serviceUri . getHost ( ) . toLowerCase ( ) ) ; if ( ! usesStandardPort ( serviceUri ) ) { data . append ( ":" ) ; data . append ( serviceUri . getPort ( ) ) ; } data . append ( "\n" ) ; String uri = serviceUri . getPath ( ) ; data . append ( MwsUtl . urlEncode ( uri , true ) ) ; data . append ( "\n" ) ; Map < String , String > sorted = new TreeMap < String , String > ( ) ; sorted . putAll ( parameters ) ; Iterator < Map . Entry < String , String > > pairs = sorted . entrySet ( ) . iterator ( ) ; while ( pairs . hasNext ( ) ) { Map . Entry < String , String > pair = pairs . next ( ) ; String key = pair . getKey ( ) ; data . append ( MwsUtl . urlEncode ( key , false ) ) ; data . append ( "=" ) ; String value = pair . getValue ( ) ; data . append ( MwsUtl . urlEncode ( value , false ) ) ; if ( pairs . hasNext ( ) ) { data . append ( "&" ) ; } } return data . toString ( ) ; }
Calculate String to Sign for SignatureVersion 2
2,324
private static String cleanWS ( String s ) { s = replaceAll ( s , OuterWhiteSpacesPtn , "" ) ; s = replaceAll ( s , WhiteSpacesPtn , " " ) ; return s ; }
Clean white space . Remove leading and trailing and replace internal runs with a single space character .
2,325
protected static String urlEncode ( String value , boolean path ) { try { value = URLEncoder . encode ( value , DEFAULT_ENCODING ) ; } catch ( Exception e ) { throw wrap ( e ) ; } value = replaceAll ( value , plusPtn , "%20" ) ; value = replaceAll ( value , asteriskPtn , "%2A" ) ; value = replaceAll ( value , pct7EPtn , "~" ) ; if ( path ) { value = replaceAll ( value , pct2FPtn , "/" ) ; } return value ; }
URL encode a value .
2,326
static String getFormattedTimestamp ( ) { DateFormat df = dateFormatPool . getAndSet ( null ) ; if ( df == null ) { df = createISODateFormat ( ) ; } String timestamp = df . format ( new Date ( ) ) ; dateFormatPool . set ( df ) ; return timestamp ; }
Get a ISO 8601 formatted timestamp of now .
2,327
static Date parseTimestamp ( String timestamp ) throws ParseException { DateFormat df = dateFormatPool . getAndSet ( null ) ; if ( df == null ) { df = createISODateFormat ( ) ; } Date date = df . parse ( timestamp ) ; dateFormatPool . set ( df ) ; return date ; }
Parse an ISO 8601 formatted timestamp
2,328
static < T > T newInstance ( Class < T > cls ) { try { return cls . newInstance ( ) ; } catch ( Exception e ) { throw wrap ( e ) ; } }
Create a new instance of a class wrap exceptions .
2,329
static String toXmlString ( Node node ) { try { Transformer transformer = getTF ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "no" ) ; StringWriter sw = new StringWriter ( ) ; StreamResult result = new StreamResult ( sw ) ; DOMSource source = new DOMSource ( node ) ; transformer . transform ( source , result ) ; return sw . toString ( ) ; } catch ( Exception e ) { throw wrap ( e ) ; } }
Get xml string for contents of node .
2,330
public static void close ( Closeable a ) { try { if ( a != null ) { a . close ( ) ; } } catch ( Exception e ) { throw wrap ( e ) ; } }
Close a Closeable if it is not null .
2,331
public static String escapeAppVersion ( String s ) { s = cleanWS ( s ) ; s = replaceAll ( s , BackSlashPtn , EscBackSlash ) ; s = replaceAll ( s , LParenPtn , EscLParen ) ; return s ; }
Escape an application version string .
2,332
public static TransformerFactory getTF ( ) { TransformerFactory tf = threadTF . get ( ) ; if ( tf == null ) { tf = TransformerFactory . newInstance ( ) ; threadTF . set ( tf ) ; } return tf ; }
Get a thread local transformer factory .
2,333
public static RuntimeException wrap ( Throwable e ) { if ( e instanceof RuntimeException ) { return ( RuntimeException ) e ; } return new RuntimeException ( e ) ; }
Wrap Checked exceptions in runtime exception .
2,334
synchronized void freeze ( ) { if ( frozen ) { return ; } if ( userAgent == null ) { setDefaultUserAgent ( ) ; } serviceMap = new HashMap < String , ServiceEndpoint > ( ) ; if ( log . isDebugEnabled ( ) ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "Creating MwsConnection {" ) ; buf . append ( "applicationName:" ) ; buf . append ( applicationName ) ; buf . append ( ",applicationVersion:" ) ; buf . append ( applicationVersion ) ; buf . append ( ",awsAccessKeyId:" ) ; buf . append ( awsAccessKeyId ) ; buf . append ( ",uri:" ) ; buf . append ( endpoint . toString ( ) ) ; buf . append ( ",userAgent:" ) ; buf . append ( userAgent ) ; buf . append ( ",connectionTimeout:" ) ; buf . append ( connectionTimeout ) ; if ( proxyHost != null && proxyPort != 0 ) { buf . append ( ",proxyUsername:" ) ; buf . append ( proxyUsername ) ; buf . append ( ",proxyHost:" ) ; buf . append ( proxyHost ) ; buf . append ( ",proxyPort:" ) ; buf . append ( proxyPort ) ; } buf . append ( "}" ) ; log . debug ( buf ) ; } BasicHttpParams httpParams = new BasicHttpParams ( ) ; httpParams . setParameter ( CoreProtocolPNames . USER_AGENT , userAgent ) ; HttpConnectionParams . setConnectionTimeout ( httpParams , connectionTimeout ) ; HttpConnectionParams . setSoTimeout ( httpParams , socketTimeout ) ; HttpConnectionParams . setStaleCheckingEnabled ( httpParams , true ) ; HttpConnectionParams . setTcpNoDelay ( httpParams , true ) ; connectionManager = getConnectionManager ( ) ; httpClient = new DefaultHttpClient ( connectionManager , httpParams ) ; httpContext = new BasicHttpContext ( ) ; if ( proxyHost != null && proxyPort != 0 ) { String scheme = MwsUtl . usesHttps ( endpoint ) ? "https" : "http" ; HttpHost hostConfiguration = new HttpHost ( proxyHost , proxyPort , scheme ) ; httpClient . getParams ( ) . setParameter ( ConnRoutePNames . DEFAULT_PROXY , hostConfiguration ) ; if ( proxyUsername != null && proxyPassword != null ) { Credentials credentials = new UsernamePasswordCredentials ( proxyUsername , proxyPassword ) ; CredentialsProvider cprovider = new BasicCredentialsProvider ( ) ; cprovider . setCredentials ( new AuthScope ( proxyHost , proxyPort ) , credentials ) ; httpContext . setAttribute ( ClientContext . CREDS_PROVIDER , cprovider ) ; } } headers = Collections . unmodifiableMap ( headers ) ; frozen = true ; }
Initialize the connection .
2,335
private ExecutorService getSharedES ( ) { synchronized ( this . getClass ( ) ) { if ( sharedES != null ) { return sharedES ; } sharedES = new ThreadPoolExecutor ( maxAsyncThreads / 10 , maxAsyncThreads , 60L , TimeUnit . SECONDS , new ArrayBlockingQueue < Runnable > ( maxAsyncQueueSize ) , new ThreadFactory ( ) { private final AtomicInteger threadNumber = new AtomicInteger ( 1 ) ; public Thread newThread ( Runnable task ) { Thread thread = new Thread ( task , "MWSClient-" + threadNumber . getAndIncrement ( ) ) ; thread . setDaemon ( true ) ; thread . setPriority ( Thread . NORM_PRIORITY ) ; return thread ; } } , new RejectedExecutionHandler ( ) { public void rejectedExecution ( Runnable task , ThreadPoolExecutor executor ) { if ( ! executor . isShutdown ( ) ) { log . warn ( "MWSClient async queue full, running on calling thread." ) ; task . run ( ) ; } else { throw new RejectedExecutionException ( ) ; } } } ) ; return sharedES ; } }
Get the shared executor service that is used by async calls if no executor is supplied .
2,336
private void setDefaultUserAgent ( ) { setUserAgent ( MwsUtl . escapeAppName ( applicationName ) , MwsUtl . escapeAppVersion ( applicationVersion ) , MwsUtl . escapeAttributeValue ( "Java/" + System . getProperty ( "java.version" ) + "/" + System . getProperty ( "java.class.version" ) + "/" + System . getProperty ( "java.vendor" ) ) , MwsUtl . escapeAttributeName ( "Platform" ) , MwsUtl . escapeAttributeValue ( "" + System . getProperty ( "os.name" ) + "/" + System . getProperty ( "os.arch" ) + "/" + System . getProperty ( "os.version" ) ) , MwsUtl . escapeAttributeName ( "MWSClientVersion" ) , MwsUtl . escapeAttributeValue ( libraryVersion ) ) ; }
Set the default user agent string . Called when connection first opened if user agent is not set explicitly .
2,337
ServiceEndpoint getServiceEndpoint ( String servicePath ) { synchronized ( serviceMap ) { ServiceEndpoint sep = serviceMap . get ( servicePath ) ; if ( sep == null ) { sep = new ServiceEndpoint ( endpoint , servicePath ) ; serviceMap . put ( servicePath , sep ) ; } return sep ; } }
Get a MwsServiceUri for the servicePath .
2,338
@ SuppressWarnings ( "unchecked" ) public < T extends MwsObject > T call ( MwsRequestType type , MwsObject requestData ) { MwsReader responseReader = null ; try { String servicePath = type . getServicePath ( ) ; String operationName = type . getOperationName ( ) ; MwsCall mc = newCall ( servicePath , operationName ) ; requestData . writeFragmentTo ( mc ) ; responseReader = mc . invoke ( ) ; MwsResponseHeaderMetadata rhmd = mc . getResponseHeaderMetadata ( ) ; MwsObject response = MwsUtl . newInstance ( type . getResponseClass ( ) ) ; type . setRHMD ( response , rhmd ) ; response . readFragmentFrom ( responseReader ) ; return ( T ) response ; } catch ( Exception e ) { throw type . wrapException ( e ) ; } finally { MwsUtl . close ( responseReader ) ; } }
Call an operation and return the response data .
2,339
public < T extends MwsObject > Future < T > callAsync ( final MwsRequestType type , final MwsObject requestData ) { return getExecutorService ( ) . submit ( new Callable < T > ( ) { public T call ( ) { return MwsConnection . this . call ( type , requestData ) ; } } ) ; }
Call a request async return a future on the response data .
2,340
public synchronized void setEndpoint ( URI endpoint ) { checkUpdatable ( ) ; int port = endpoint . getPort ( ) ; if ( port == 80 || port == 443 ) { if ( MwsUtl . usesStandardPort ( endpoint ) ) { try { endpoint = new URI ( endpoint . getScheme ( ) , endpoint . getHost ( ) , endpoint . getPath ( ) , endpoint . getFragment ( ) ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } } this . endpoint = endpoint ; }
Sets service endpoint property .
2,341
public synchronized void setUserAgent ( String applicationName , String applicationVersion , String programmingLanguage , String ... additionalNameValuePairs ) { checkUpdatable ( ) ; StringBuilder b = new StringBuilder ( ) ; b . append ( applicationName ) ; b . append ( "/" ) ; b . append ( applicationVersion ) ; b . append ( " (Language=" ) ; b . append ( programmingLanguage ) ; int i = 0 ; while ( i < additionalNameValuePairs . length ) { String name = additionalNameValuePairs [ i ] ; String value = additionalNameValuePairs [ i + 1 ] ; b . append ( "; " ) ; b . append ( name ) ; b . append ( "=" ) ; b . append ( value ) ; i += 2 ; } b . append ( ")" ) ; this . userAgent = b . toString ( ) ; }
Sets UserAgent property
2,342
public GetOrderRequest withAmazonOrderId ( String ... values ) { List < String > list = getAmazonOrderId ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for AmazonOrderId return this .
2,343
public Order withPaymentExecutionDetail ( PaymentExecutionDetailItem ... values ) { List < PaymentExecutionDetailItem > list = getPaymentExecutionDetail ( ) ; for ( PaymentExecutionDetailItem value : values ) { list . add ( value ) ; } return this ; }
Add values for PaymentExecutionDetail return this .
2,344
public void setServiceURL ( String serviceUrl ) { try { URI fullURI = URI . create ( serviceUrl ) ; URI partialURI = new URI ( fullURI . getScheme ( ) , null , fullURI . getHost ( ) , fullURI . getPort ( ) , null , null , null ) ; cc . setEndpoint ( partialURI ) ; String path = fullURI . getPath ( ) ; if ( path != null ) { path = path . substring ( path . startsWith ( "/" ) ? 1 : 0 ) ; path = path . substring ( 0 , path . length ( ) - ( path . endsWith ( "/" ) ? 1 : 0 ) ) ; } if ( path == null || path . isEmpty ( ) ) { this . servicePath = DEFAULT_SERVICE_PATH ; } else { this . servicePath = path ; } } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Set the service URL to make requests against .
2,345
protected void append ( String value ) { try { writer . write ( value ) ; } catch ( Exception e ) { throw MwsUtl . wrap ( e ) ; } }
Append string to the output .
2,346
public OrderItem withPromotionIds ( String ... values ) { List < String > list = getPromotionIds ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for PromotionIds return this .
2,347
private String getElementText ( Element element ) { Node node = element . getFirstChild ( ) ; if ( node == null || node . getNodeType ( ) != Node . TEXT_NODE ) { return null ; } return node . getNodeValue ( ) . trim ( ) ; }
Read begin tag text end tag .
2,348
@ SuppressWarnings ( "unchecked" ) private < T > T parseElement ( Element element , Class < T > cls ) { T value ; if ( element == null ) { value = null ; } else if ( MwsObject . class . isAssignableFrom ( cls ) ) { value = MwsUtl . newInstance ( cls ) ; Element holdElement = currentElement ; Node holdChild = currentChild ; setCurrentElement ( element ) ; ( ( MwsObject ) value ) . readFragmentFrom ( this ) ; currentElement = holdElement ; currentChild = holdChild ; } else if ( cls == Object . class ) { value = ( T ) element ; } else { String v = getElementText ( element ) ; value = parseString ( v , cls ) ; } return value ; }
Read an element into a new instance of a class .
2,349
@ SuppressWarnings ( "unchecked" ) private < T > T parseString ( String v , Class < T > cls ) { Object value ; if ( v == null || v . length ( ) == 0 ) { value = null ; } else if ( cls == String . class ) { value = v ; } else if ( cls == Boolean . class || cls == boolean . class ) { if ( v . equalsIgnoreCase ( "true" ) ) { value = Boolean . TRUE ; } else if ( v . equalsIgnoreCase ( "false" ) ) { value = Boolean . FALSE ; } else { throw new IllegalStateException ( "Expected true/false, found text '" + v + "'." ) ; } } else if ( cls == Integer . class || cls == int . class ) { value = Integer . valueOf ( v ) ; } else if ( cls == Long . class || cls == long . class ) { value = Long . valueOf ( v ) ; } else if ( cls == Float . class || cls == float . class ) { value = Float . valueOf ( v ) ; } else if ( cls == Double . class || cls == double . class ) { value = Double . valueOf ( v ) ; } else if ( cls == BigDecimal . class ) { value = new BigDecimal ( v ) ; } else if ( XMLGregorianCalendar . class == cls ) { value = MwsUtl . getDTF ( ) . newXMLGregorianCalendar ( v ) ; } else if ( Enum . class . isAssignableFrom ( cls ) ) { value = MwsUtl . getEnumValue ( cls , v ) ; } else { throw new IllegalArgumentException ( String . format ( "Unable to parse String %s to Class %s" , v , cls ) ) ; } return ( T ) value ; }
Parse a string to a value of the given class .
2,350
public ListOrdersRequest withOrderStatus ( String ... values ) { List < String > list = getOrderStatus ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for OrderStatus return this .
2,351
public ListOrdersRequest withMarketplaceId ( String ... values ) { List < String > list = getMarketplaceId ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for MarketplaceId return this .
2,352
public ListOrdersRequest withFulfillmentChannel ( String ... values ) { List < String > list = getFulfillmentChannel ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for FulfillmentChannel return this .
2,353
public ListOrdersRequest withPaymentMethod ( String ... values ) { List < String > list = getPaymentMethod ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for PaymentMethod return this .
2,354
public ListOrdersRequest withTFMShipmentStatus ( String ... values ) { List < String > list = getTFMShipmentStatus ( ) ; for ( String value : values ) { list . add ( value ) ; } return this ; }
Add values for TFMShipmentStatus return this .
2,355
public ListOrdersResult withOrders ( Order ... values ) { List < Order > list = getOrders ( ) ; for ( Order value : values ) { list . add ( value ) ; } return this ; }
Add values for Orders return this .
2,356
public ListOrderItemsResult withOrderItems ( OrderItem ... values ) { List < OrderItem > list = getOrderItems ( ) ; for ( OrderItem value : values ) { list . add ( value ) ; } return this ; }
Add values for OrderItems return this .
2,357
public static void unload ( ) { if ( elements != null ) { for ( Element style : elements ) { style . removeFromParent ( ) ; } elements . clear ( ) ; } }
Unload the current loaded theme .
2,358
public boolean hasSameDefaultVariant ( VariantSet obj ) { return ( this . defaultVariant == null && obj . defaultVariant == null ) || ( this . defaultVariant != null && this . defaultVariant . equals ( obj . defaultVariant ) ) ; }
Returns true of the variantSet passed in parameter has the same default value
2,359
protected String getTempFilePath ( GeneratorContext context , CacheMode cacheMode ) { return getTempDirectory ( ) + cacheMode + URL_SEPARATOR + getResourceCacheKey ( context . getPath ( ) , context ) ; }
Returns the file path of the temporary resource
2,360
protected String getResourceCacheKey ( String path , GeneratorContext context ) { StringBuilder strbCacheKey = new StringBuilder ( path ) ; if ( StringUtils . isNotEmpty ( context . getBracketsParam ( ) ) ) { strbCacheKey . append ( "_" ) . append ( context . getBracketsParam ( ) ) ; } if ( StringUtils . isNotEmpty ( context . getParenthesesParam ( ) ) ) { strbCacheKey . append ( "_" ) . append ( context . getParenthesesParam ( ) ) ; } String cacheKey = strbCacheKey . toString ( ) ; Locale locale = context . getLocale ( ) ; if ( locale != null ) { cacheKey = LocaleUtils . toBundleName ( strbCacheKey . toString ( ) , locale ) ; } cacheKey = cacheKey . replaceAll ( "[^\\w\\.\\-]" , "_" ) ; return cacheKey ; }
Returns the cache key for linked resources map
2,361
protected boolean checkResourcesModified ( GeneratorContext context , List < FilePathMapping > fMappings ) { boolean resourceModified = false ; for ( Iterator < FilePathMapping > iter = fMappings . iterator ( ) ; iter . hasNext ( ) && ! resourceModified ; ) { FilePathMapping fMapping = iter . next ( ) ; resourceModified = fMapping . getLastModified ( ) != rsHandler . getLastModified ( fMapping . getPath ( ) ) ; } return resourceModified ; }
Checks if the resources have been modified
2,362
protected Reader retrieveFromCache ( String path , GeneratorContext context , CacheMode cacheMode ) { Reader rd = null ; String filePath = getTempFilePath ( context , cacheMode ) ; FileInputStream fis = null ; File file = new File ( filePath ) ; if ( file . exists ( ) ) { try { fis = new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { throw new BundlingProcessException ( "An error occured while creating temporary resource for " + filePath , e ) ; } FileChannel inchannel = fis . getChannel ( ) ; rd = Channels . newReader ( inchannel , context . getConfig ( ) . getResourceCharset ( ) . newDecoder ( ) , - 1 ) ; context . setRetrievedFromCache ( true ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( getName ( ) + " resource '" + path + "' retrieved from cache" ) ; } } return rd ; }
Retrieves the resource from cache if it exists
2,363
protected Reader createTempResource ( GeneratorContext context , CacheMode cacheMode , Reader rd ) { String filePath = getTempFilePath ( context , cacheMode ) ; Writer wr = null ; FileOutputStream fos = null ; try { File f = new File ( filePath ) ; if ( ! f . getParentFile ( ) . exists ( ) ) { f . getParentFile ( ) . mkdirs ( ) ; } String content = IOUtils . toString ( rd ) ; fos = new FileOutputStream ( f ) ; FileChannel channel = fos . getChannel ( ) ; wr = Channels . newWriter ( channel , config . getResourceCharset ( ) . newEncoder ( ) , - 1 ) ; wr . write ( content ) ; rd = new StringReader ( content ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to create temporary resource for '" + context . getPath ( ) + "'" , e ) ; } finally { IOUtils . close ( wr ) ; IOUtils . close ( fos ) ; } return rd ; }
Creates the temporary resource
2,364
protected void resetCache ( ) { cacheProperties . clear ( ) ; linkedResourceMap . clear ( ) ; cacheProperties . put ( JawrConfig . JAWR_CHARSET_NAME , config . getResourceCharset ( ) . name ( ) ) ; }
Resets the cache
2,365
protected boolean isCacheValid ( ) { return StringUtils . equals ( cacheProperties . getProperty ( JawrConfig . JAWR_CHARSET_NAME ) , config . getResourceCharset ( ) . name ( ) ) ; }
Returns true if the cache is valid
2,366
protected synchronized void serializeCacheMapping ( ) { for ( Map . Entry < String , List < FilePathMapping > > entry : linkedResourceMap . entrySet ( ) ) { StringBuilder strb = new StringBuilder ( ) ; Iterator < FilePathMapping > iter = entry . getValue ( ) . iterator ( ) ; if ( iter . hasNext ( ) ) { for ( ; iter . hasNext ( ) ; ) { FilePathMapping fMapping = iter . next ( ) ; strb . append ( fMapping . getPath ( ) ) . append ( MAPPING_TIMESTAMP_SEPARATOR ) . append ( fMapping . getLastModified ( ) ) ; if ( iter . hasNext ( ) ) { strb . append ( SEMICOLON ) ; } } cacheProperties . put ( JAWR_MAPPING_PREFIX + entry . getKey ( ) , strb . toString ( ) ) ; } } File f = new File ( getCacheFilePath ( ) ) ; if ( ! f . getParentFile ( ) . exists ( ) ) { f . getParentFile ( ) . mkdirs ( ) ; } FileWriter fw = null ; try { fw = new FileWriter ( f ) ; cacheProperties . store ( fw , "Cache properties of " + getName ( ) + " generator" ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to save cache file mapping " , e ) ; } finally { IOUtils . close ( fw ) ; } }
Serialize the cache file mapping
2,367
protected void loadCacheMapping ( ) { File f = new File ( getCacheFilePath ( ) ) ; if ( f . exists ( ) ) { try ( InputStream is = new FileInputStream ( f ) ; BufferedReader rd = new BufferedReader ( new FileReader ( f ) ) ) { cacheProperties . load ( is ) ; for ( Enumeration < ? > properyNames = cacheProperties . propertyNames ( ) ; properyNames . hasMoreElements ( ) ; ) { String propName = ( String ) properyNames . nextElement ( ) ; if ( propName . startsWith ( JAWR_MAPPING_PREFIX ) ) { String value = cacheProperties . getProperty ( propName ) ; String resourceMapping = propName . substring ( JAWR_MAPPING_PREFIX . length ( ) ) ; String [ ] mappings = value . split ( SEMICOLON ) ; List < FilePathMapping > fMappings = new CopyOnWriteArrayList < > ( ) ; boolean mappingModified = true ; for ( String fmapping : mappings ) { String [ ] mapping = fmapping . split ( MAPPING_TIMESTAMP_SEPARATOR ) ; long lastModified = Long . parseLong ( mapping [ 1 ] ) ; String filePath = mapping [ 0 ] ; if ( rsHandler . getLastModified ( filePath ) != lastModified ) { mappingModified = false ; break ; } FilePathMapping fmap = new FilePathMapping ( filePath , lastModified ) ; fMappings . add ( fmap ) ; } if ( mappingModified ) { linkedResourceMap . put ( resourceMapping , fMappings ) ; } } } } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to initialize " + getName ( ) + " Generator cache" , e ) ; } } }
Loads the less file mapping
2,368
private AbstractChainedGlobalProcessor < T > addOrCreateChain ( AbstractChainedGlobalProcessor < T > chain , String key ) { AbstractChainedGlobalProcessor < T > toAdd ; if ( customPostprocessors . get ( key ) == null ) { toAdd = buildProcessorByKey ( key ) ; } else { toAdd = ( AbstractChainedGlobalProcessor < T > ) customPostprocessors . get ( key ) ; } if ( toAdd instanceof BundlingProcessLifeCycleListener && ! listeners . contains ( toAdd ) ) { listeners . add ( ( BundlingProcessLifeCycleListener ) toAdd ) ; } AbstractChainedGlobalProcessor < T > newChainResult = null ; if ( chain == null ) { newChainResult = toAdd ; } else { chain . addNextProcessor ( toAdd ) ; newChainResult = chain ; } return newChainResult ; }
Creates an AbstractChainedGlobalProcessor . If the supplied chain is null the new chain is returned . Otherwise it is added to the existing chain .
2,369
public static void initApplication ( Application app ) { MarkupFactory factory = new MarkupFactory ( ) { public MarkupParser newMarkupParser ( final MarkupResourceStream resource ) { MarkupParser parser = new MarkupParser ( new XmlPullParser ( ) , resource ) ; parser . add ( new JawrWicketLinkTagHandler ( ) ) ; return parser ; } } ; app . getMarkupSettings ( ) . setMarkupFactory ( factory ) ; app . getPageSettings ( ) . addComponentResolver ( new JawrWicketLinkResolver ( ) ) ; }
Initialize the wicket application
2,370
private StringBuffer buildFormJavascript ( ValidatorResources validatorResources , String formName , Locale locale , String messageNS , boolean stopOnErrors ) { Form form = validatorResources . getForm ( locale , formName ) ; return createDynamicJavascript ( validatorResources , form , messageNS , stopOnErrors ) ; }
Creates a validator for a specific form .
2,371
protected String getJavascriptBegin ( String jsFormName , String methods ) { StringBuffer sb = new StringBuffer ( ) ; String name = jsFormName . replace ( '/' , '_' ) ; name = jsFormName . substring ( 0 , 1 ) . toUpperCase ( ) + jsFormName . substring ( 1 , jsFormName . length ( ) ) ; sb . append ( "\n var bCancel = false; \n\n" ) ; sb . append ( " function validate" + name + "(form) { \n" ) ; sb . append ( " if (bCancel) { \n" ) ; sb . append ( " return true; \n" ) ; sb . append ( " } else { \n" ) ; if ( ( methods == null ) || ( methods . length ( ) == 0 ) ) { sb . append ( " return true; \n" ) ; } else { sb . append ( " var formValidationResult; \n" ) ; sb . append ( " formValidationResult = " + methods + "; \n" ) ; if ( methods . indexOf ( "&&" ) >= 0 ) { sb . append ( " return (formValidationResult); \n" ) ; } else { sb . append ( " return (formValidationResult == 1); \n" ) ; } } sb . append ( " } \n" ) ; sb . append ( " } \n\n" ) ; return sb . toString ( ) ; }
Returns the opening script element and some initial javascript .
2,372
public void change ( ) { float newChange = ( random . nextFloat ( ) * 4 ) - 2 ; newChange = Math . round ( newChange * 100.0F ) / 100.0F ; if ( last . floatValue ( ) + newChange < 9 ) { newChange = - newChange ; } change = new BigDecimal ( newChange ) ; change = change . setScale ( 2 , BigDecimal . ROUND_UP ) ; last = last . add ( change ) ; if ( last . compareTo ( max ) > 0 ) { max = last ; } if ( last . compareTo ( min ) < 0 ) { min = last ; } time = new Date ( ) ; }
Alter the stock price
2,373
public static void initJMXBean ( JawrApplicationConfigManager appConfigMgr , ServletContext servletContext , String resourceType , String mBeanPrefix ) { try { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; if ( mbs != null ) { ObjectName jawrConfigMgrObjName = JmxUtils . getMBeanObjectName ( servletContext , resourceType , mBeanPrefix ) ; ObjectName appJawrMgrObjectName = JmxUtils . getAppJawrConfigMBeanObjectName ( servletContext , mBeanPrefix ) ; if ( ! mbs . isRegistered ( appJawrMgrObjectName ) ) { mbs . registerMBean ( appConfigMgr , appJawrMgrObjectName ) ; } if ( mbs . isRegistered ( jawrConfigMgrObjName ) ) { LOGGER . warn ( "The MBean '" + jawrConfigMgrObjName . getCanonicalName ( ) + "' already exists. It will be unregisterd and registered with the new JawrConfigManagerMBean." ) ; mbs . unregisterMBean ( jawrConfigMgrObjName ) ; } JawrConfigManagerMBean configMgr = appConfigMgr . getConfigMgr ( resourceType ) ; mbs . registerMBean ( configMgr , jawrConfigMgrObjName ) ; } } catch ( InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | InstanceNotFoundException e ) { LOGGER . error ( "Unable to instanciate the Jawr MBean for resource type '" + resourceType + "'" , e ) ; } }
Initialize the JMX Bean
2,374
public static void unregisterJMXBean ( ServletContext servletContext , String resourceType , String mBeanPrefix ) { try { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; if ( mbs != null ) { ObjectName jawrConfigMgrObjName = JmxUtils . getMBeanObjectName ( servletContext , resourceType , mBeanPrefix ) ; ObjectName appJawrMgrObjectName = JmxUtils . getAppJawrConfigMBeanObjectName ( servletContext , mBeanPrefix ) ; if ( mbs . isRegistered ( appJawrMgrObjectName ) ) { mbs . unregisterMBean ( appJawrMgrObjectName ) ; } if ( mbs . isRegistered ( jawrConfigMgrObjName ) ) { mbs . unregisterMBean ( jawrConfigMgrObjName ) ; } } } catch ( InstanceNotFoundException | MBeanRegistrationException e ) { LOGGER . error ( "Unable to unregister the Jawr MBean for resource type '" + resourceType + "'" , e ) ; } }
Unregister the JMX Bean
2,375
public static ObjectName getAppJawrConfigMBeanObjectName ( ServletContext servletContext , String mBeanPrefix ) { return getMBeanObjectName ( getContextPath ( servletContext ) , JAWR_APP_CONFIG_MANAGER_TYPE , mBeanPrefix , null ) ; }
Returns the object name for the Jawr Application configuration Manager MBean
2,376
private static ObjectName getMBeanObjectName ( final String contextPath , final String objectType , final String mBeanPrefix , final String resourceType ) { String curCtxPath = contextPath ; if ( StringUtils . isEmpty ( curCtxPath ) ) { curCtxPath = ServletContextUtils . getContextPath ( null ) ; } if ( curCtxPath . charAt ( 0 ) == ( '/' ) ) { curCtxPath = curCtxPath . substring ( 1 ) ; } String prefix = mBeanPrefix ; if ( prefix == null ) { prefix = DEFAULT_PREFIX ; } StringBuilder objectNameStr = new StringBuilder ( "net.jawr.web.jmx:type=" + objectType + ",prefix=" + prefix + ",webappContext=" + curCtxPath ) ; if ( resourceType != null ) { objectNameStr . append ( ",name=" ) . append ( resourceType ) . append ( "MBean" ) ; } return getObjectName ( objectNameStr . toString ( ) ) ; }
Returns the object name for the Jawr MBean
2,377
private static ObjectName getObjectName ( String name ) { ObjectName mBeanName = null ; try { mBeanName = new ObjectName ( name ) ; } catch ( MalformedObjectNameException | NullPointerException e ) { throw new JmxConfigException ( e ) ; } return mBeanName ; }
Create an object name from the name passed in parameter
2,378
private void write ( int c ) throws IOException { if ( ! firstCharacterWritten ) { if ( c != '\n' ) { out . write ( c ) ; firstCharacterWritten = true ; } } else { out . write ( c ) ; } }
Writes the character on the output stream
2,379
public ResourceBundlesHandler buildResourceBundlesHandler ( ) throws DuplicateBundlePathException , BundleDependencyException { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "Building resources handler... " ) ; } if ( null == jawrConfig ) { throw new IllegalStateException ( "Must set the JawrConfig for this factory before invoking buildResourceBundlesHandler(). " ) ; } if ( null == resourceReaderHandler ) { throw new IllegalStateException ( "Must set the resourceHandler for this factory before invoking buildResourceBundlesHandler(). " ) ; } if ( useSingleResourceFactory && null == singleFileBundleName ) { throw new IllegalStateException ( "Must set the singleFileBundleName when useSingleResourceFactory is set to true. Please check the documentation. " ) ; } initCustomPostProcessors ( ) ; List < JoinableResourceBundle > resourceBundles = new ArrayList < > ( ) ; if ( isProcessingBundleFromCacheMapping ( ) ) { initResourceBundlesFromFullMapping ( resourceBundles ) ; } else { initResourceBundles ( resourceBundles ) ; } ResourceBundlePostProcessor processor = null ; if ( null == this . globalPostProcessorKeys ) { processor = this . chainFactory . buildDefaultProcessorChain ( ) ; } else { processor = this . chainFactory . buildPostProcessorChain ( globalPostProcessorKeys ) ; } ResourceBundlePostProcessor unitProcessor = null ; if ( null == this . unitPostProcessorKeys ) { unitProcessor = this . chainFactory . buildDefaultUnitProcessorChain ( ) ; } else { unitProcessor = this . chainFactory . buildPostProcessorChain ( unitPostProcessorKeys ) ; } ResourceBundlePostProcessor compositeBundleProcessor = null ; if ( null == this . globalCompositePostProcessorKeys ) { compositeBundleProcessor = this . chainFactory . buildDefaultCompositeProcessorChain ( ) ; } else { compositeBundleProcessor = this . chainFactory . buildPostProcessorChain ( globalCompositePostProcessorKeys ) ; } ResourceBundlePostProcessor compositeUnitProcessor = null ; if ( null == this . unitCompositePostProcessorKeys ) { compositeUnitProcessor = this . chainFactory . buildDefaultUnitCompositeProcessorChain ( ) ; } else { compositeUnitProcessor = this . chainFactory . buildPostProcessorChain ( unitCompositePostProcessorKeys ) ; } if ( null != customGlobalPreprocessors ) resourceTypePreprocessorChainFactory . setCustomGlobalProcessors ( customGlobalPreprocessors ) ; GlobalProcessor < GlobalPreprocessingContext > resourceTypePreprocessor = null ; if ( null == this . resourceTypePreprocessorKeys ) resourceTypePreprocessor = this . resourceTypePreprocessorChainFactory . buildDefaultProcessorChain ( ) ; else resourceTypePreprocessor = this . resourceTypePreprocessorChainFactory . buildProcessorChain ( resourceTypePreprocessorKeys ) ; if ( null != customGlobalPostprocessors ) resourceTypePostprocessorChainFactory . setCustomGlobalProcessors ( customGlobalPostprocessors ) ; GlobalProcessor < GlobalPostProcessingContext > resourceTypePostprocessor = null ; if ( null == this . resourceTypePostprocessorKeys ) resourceTypePostprocessor = this . resourceTypePostprocessorChainFactory . buildDefaultProcessorChain ( ) ; else resourceTypePostprocessor = this . resourceTypePostprocessorChainFactory . buildProcessorChain ( resourceTypePostprocessorKeys ) ; ResourceBundlesHandler collector = new ResourceBundlesHandlerImpl ( resourceBundles , resourceReaderHandler , resourceBundleHandler , jawrConfig , processor , unitProcessor , compositeBundleProcessor , compositeUnitProcessor , resourceTypePreprocessor , resourceTypePostprocessor ) ; collector . setBundlingProcessLifeCycleListeners ( getBundlingProcessLifeCycleListeners ( ) ) ; if ( useCacheManager && ! jawrConfig . isDebugModeOn ( ) ) collector = new CachedResourceBundlesHandler ( collector ) ; collector . initAllBundles ( ) ; return collector ; }
Build a ResourceBundlesHandler . Must be invoked after setting at least the ResourceHandler .
2,380
protected boolean isProcessingBundleFromCacheMapping ( ) { boolean processBundleFromCacheMapping = false ; if ( jawrConfig . getUseBundleMapping ( ) && resourceBundleHandler . isExistingMappingFile ( ) ) { Properties cachedMappingProperties = resourceBundleHandler . getJawrBundleMapping ( ) ; String storedHashcode = cachedMappingProperties . getProperty ( JawrConstant . JAWR_CONFIG_HASHCODE ) ; String currentHashcode = null ; try { currentHashcode = CheckSumUtils . getMD5Checksum ( jawrConfig . getConfigProperties ( ) . toString ( ) ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to calculate checksum for current Jawr config" ) ; } if ( currentHashcode . equals ( storedHashcode ) ) { processBundleFromCacheMapping = true ; } } return processBundleFromCacheMapping ; }
Returns true if the bundle should be processed using cache mapping information
2,381
protected List < BundlingProcessLifeCycleListener > getBundlingProcessLifeCycleListeners ( ) { List < BundlingProcessLifeCycleListener > lifeCycleListeners = new ArrayList < > ( ) ; List < BundlingProcessLifeCycleListener > generatorLifeCycleListeners = jawrConfig . getGeneratorRegistry ( ) . getBundlingProcessLifeCycleListeners ( ) ; lifeCycleListeners . addAll ( generatorLifeCycleListeners ) ; lifeCycleListeners . addAll ( this . resourceTypePreprocessorChainFactory . getBundlingProcessLifeCycleListeners ( ) ) ; lifeCycleListeners . addAll ( this . chainFactory . getBundlingProcessLifeCycleListeners ( ) ) ; lifeCycleListeners . addAll ( this . resourceTypePostprocessorChainFactory . getBundlingProcessLifeCycleListeners ( ) ) ; return lifeCycleListeners ; }
Returns the life cycle listeners
2,382
private void initResourceBundlesFromFullMapping ( List < JoinableResourceBundle > resourceBundles ) { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "Building bundles from the full bundle mapping. Only modified bundles will be processed." ) ; } Properties mappingProperties = resourceBundleHandler . getJawrBundleMapping ( ) ; FullMappingPropertiesBasedBundlesHandlerFactory factory = new FullMappingPropertiesBasedBundlesHandlerFactory ( resourceType , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) , chainFactory ) ; resourceBundles . addAll ( factory . getResourceBundles ( mappingProperties ) ) ; }
Initialize the resource bundles from the mapping file
2,383
private void initResourceBundles ( List < JoinableResourceBundle > resourceBundles ) throws DuplicateBundlePathException , BundleDependencyException { bundleDefinitionsWithDependencies = new HashSet < > ( ) ; if ( null != bundleDefinitions ) { if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Adding custom bundle definitions. " ) ; for ( ResourceBundleDefinition def : bundleDefinitions ) { if ( def . isComposite ( ) ) { resourceBundles . add ( buildCompositeResourcebundle ( def ) ) ; } else resourceBundles . add ( buildResourcebundle ( def ) ) ; } } if ( ! jawrConfig . getGeneratorRegistry ( ) . isPathGenerated ( baseDir ) ) { this . baseDir = PathNormalizer . asDirPath ( baseDir ) ; } if ( useDirMapperFactory ) { if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Using ResourceBundleDirMapper. " ) ; ResourceBundleDirMapper dirFactory = new ResourceBundleDirMapper ( baseDir , resourceReaderHandler , resourceBundles , fileExtension , excludedDirMapperDirs ) ; Map < String , String > mappings = dirFactory . getBundleMapping ( ) ; for ( Entry < String , String > entry : mappings . entrySet ( ) ) { resourceBundles . add ( buildDirMappedResourceBundle ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } } if ( this . scanForOrphans ) { OrphanResourceBundlesMapper orphanFactory = new OrphanResourceBundlesMapper ( baseDir , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) , resourceBundles , fileExtension ) ; List < String > orphans = orphanFactory . getOrphansList ( ) ; if ( useSingleResourceFactory ) { if ( ! singleFileBundleName . endsWith ( fileExtension ) ) singleFileBundleName += fileExtension ; if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Building bundle of orphan resources with the name: " + singleFileBundleName ) ; resourceBundles . add ( buildOrphansResourceBundle ( singleFileBundleName , orphans ) ) ; } else { if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Creating mappings for orphan resources. " ) ; for ( Iterator < String > it = orphans . iterator ( ) ; it . hasNext ( ) ; ) { resourceBundles . add ( buildOrphanResourceBundle ( it . next ( ) ) ) ; } } } else if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Skipping orphan file auto processing. " ) ; if ( "" . equals ( jawrConfig . getServletMapping ( ) ) ) LOGGER . debug ( "Note that there is no specified mapping for Jawr " + "(it has been seet to serve *.js or *.css requests). " + "The orphan files will become unreachable through the server." ) ; } for ( ResourceBundleDefinition definition : bundleDefinitionsWithDependencies ) { JoinableResourceBundle bundle = getBundleFromName ( definition . getBundleName ( ) , resourceBundles ) ; if ( bundle != null ) { bundle . setDependencies ( getBundleDependencies ( definition , resourceBundles ) ) ; } } }
Initialize the resource bundles
2,384
private JoinableResourceBundle getBundleFromName ( String name , List < JoinableResourceBundle > bundles ) { JoinableResourceBundle bundle = null ; for ( JoinableResourceBundle aBundle : bundles ) { if ( aBundle . getName ( ) . equals ( name ) ) { bundle = aBundle ; break ; } } return bundle ; }
Returns a bundle from its name
2,385
private JoinableResourceBundle buildResourcebundle ( ResourceBundleDefinition definition ) throws BundleDependencyException { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Init bundle with id:" + definition . getBundleId ( ) ) ; validateBundleId ( definition ) ; DebugInclusion inclusion = DebugInclusion . ALWAYS ; if ( definition . isDebugOnly ( ) ) { inclusion = DebugInclusion . ONLY ; } if ( definition . isDebugNever ( ) ) { inclusion = DebugInclusion . NEVER ; } InclusionPattern include = new InclusionPattern ( definition . isGlobal ( ) , definition . getInclusionOrder ( ) , inclusion ) ; JoinableResourceBundleImpl newBundle = new JoinableResourceBundleImpl ( definition . getBundleId ( ) , definition . getBundleName ( ) , definition . getBundlePrefix ( ) , fileExtension , include , definition . getMappings ( ) , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) ) ; if ( null != definition . getBundlePostProcessorKeys ( ) ) newBundle . setBundlePostProcessor ( chainFactory . buildPostProcessorChain ( definition . getBundlePostProcessorKeys ( ) ) ) ; if ( null != definition . getUnitaryPostProcessorKeys ( ) ) newBundle . setUnitaryPostProcessor ( chainFactory . buildPostProcessorChain ( definition . getUnitaryPostProcessorKeys ( ) ) ) ; if ( null != definition . getIeConditionalExpression ( ) ) newBundle . setExplorerConditionalExpression ( definition . getIeConditionalExpression ( ) ) ; if ( null != definition . getAlternateProductionURL ( ) ) newBundle . setAlternateProductionURL ( definition . getAlternateProductionURL ( ) ) ; if ( null != definition . getDebugURL ( ) ) newBundle . setDebugURL ( definition . getDebugURL ( ) ) ; if ( null != definition . getDependencies ( ) && ! definition . getDependencies ( ) . isEmpty ( ) ) { bundleDefinitionsWithDependencies . add ( definition ) ; } return newBundle ; }
Build a JoinableResourceBundle using a ResourceBundleDefinition
2,386
private void validateBundleId ( ResourceBundleDefinition definition ) { String bundleId = definition . getBundleId ( ) ; if ( bundleId != null ) { if ( ! bundleId . endsWith ( fileExtension ) ) { throw new BundlingProcessException ( "The extension of the bundle " + definition . getBundleName ( ) + " - " + bundleId + " doesn't match the allowed extension : '" + fileExtension + "'. Please update your bundle definition." ) ; } else if ( bundleId . startsWith ( JawrConstant . WEB_INF_DIR_PREFIX ) || bundleId . startsWith ( JawrConstant . META_INF_DIR_PREFIX ) ) { throw new BundlingProcessException ( "For the bundle " + definition . getBundleName ( ) + ", the bundle id '" + bundleId + "' is not allowed because it starts with \"/WEB-INF/\". Please update your bundle definition." ) ; } } }
Validates the bundle ID
2,387
private List < JoinableResourceBundle > getBundleDependencies ( ResourceBundleDefinition definition , List < JoinableResourceBundle > bundles ) throws BundleDependencyException { List < JoinableResourceBundle > dependencies = new ArrayList < > ( ) ; List < String > processedBundles = new ArrayList < > ( ) ; if ( definition . isGlobal ( ) && definition . getDependencies ( ) != null && ! definition . getDependencies ( ) . isEmpty ( ) ) { throw new BundleDependencyException ( definition . getBundleName ( ) , "The dependencies property is not allowed for global bundles. Please use the order property " + "to define the import order." ) ; } initBundleDependencies ( definition . getBundleName ( ) , definition , dependencies , processedBundles , bundles ) ; return dependencies ; }
Returns the bundle dependencies from the resource bundle definition
2,388
private void initBundleDependencies ( String rootBundleDefinition , ResourceBundleDefinition definition , List < JoinableResourceBundle > bundleDependencies , List < String > processedBundles , List < JoinableResourceBundle > bundles ) throws BundleDependencyException { List < String > bundleDefDependencies = definition . getDependencies ( ) ; if ( definition . isGlobal ( ) ) { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "The global bundle '" + definition . getBundleName ( ) + "' belongs to the dependencies of '" + rootBundleDefinition + "'." + "As it's a global bundle, it will not be defined as part of the dependencies." ) ; } return ; } if ( bundleDefDependencies != null && ! bundleDefDependencies . isEmpty ( ) ) { if ( processedBundles . contains ( definition . getBundleName ( ) ) ) { throw new BundleDependencyException ( rootBundleDefinition , "There is a circular dependency. The bundle in conflict is '" + definition . getBundleName ( ) + "'" ) ; } else { processedBundles . add ( definition . getBundleName ( ) ) ; for ( String dependency : bundleDefDependencies ) { for ( ResourceBundleDefinition dependencyBundle : bundleDefinitions ) { String dependencyBundleName = dependencyBundle . getBundleName ( ) ; if ( dependencyBundleName . equals ( dependency ) ) { if ( ! bundleListContains ( bundleDependencies , dependencyBundleName ) ) { if ( ! processedBundles . contains ( dependencyBundleName ) ) { initBundleDependencies ( rootBundleDefinition , dependencyBundle , bundleDependencies , processedBundles , bundles ) ; bundleDependencies . add ( getBundleFromName ( dependencyBundleName , bundles ) ) ; } else { throw new BundleDependencyException ( rootBundleDefinition , "There is a circular dependency. The bundle in conflict is '" + dependencyBundleName + "'" ) ; } } else { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "The bundle '" + dependencyBundle . getBundleId ( ) + "' occurs multiple time in the dependencies hierarchy of the bundle '" + rootBundleDefinition + "'." ) ; } } } } } } } }
Initialize the bundle dependencies
2,389
private boolean bundleListContains ( List < JoinableResourceBundle > bundles , String bundleName ) { boolean contains = false ; for ( JoinableResourceBundle bundle : bundles ) { if ( bundle . getName ( ) . equals ( bundleName ) ) { contains = true ; break ; } } return contains ; }
Checks if the bundle name exists in the bundle list
2,390
private JoinableResourceBundle buildDirMappedResourceBundle ( String bundleId , String pathMapping ) { List < String > path = Collections . singletonList ( pathMapping ) ; JoinableResourceBundle newBundle = new JoinableResourceBundleImpl ( bundleId , generateBundleNameFromBundleId ( bundleId ) , null , fileExtension , new InclusionPattern ( ) , path , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) ) ; return newBundle ; }
Build a bundle based on a mapping returned by the ResourceBundleDirMapperFactory .
2,391
private String generateBundleNameFromBundleId ( String bundleId ) { String bundleName = bundleId ; if ( bundleName . startsWith ( "/" ) ) { bundleName = bundleName . substring ( 1 ) ; } int idxExtension = FileNameUtils . indexOfExtension ( bundleName ) ; if ( idxExtension != - 1 ) { bundleName = bundleName . substring ( 0 , idxExtension ) ; } return bundleName . replaceAll ( "(/|\\.|:)" , "_" ) ; }
Generates the bundle ID from the bundle name
2,392
private JoinableResourceBundle buildOrphansResourceBundle ( String bundleId , List < String > orphanPaths ) { JoinableResourceBundle newBundle = new JoinableResourceBundleImpl ( bundleId , generateBundleNameFromBundleId ( bundleId ) , null , fileExtension , new InclusionPattern ( ) , orphanPaths , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) ) ; return newBundle ; }
Builds a single bundle containing all the paths specified . Useful to make a single bundle out of every resource that is orphan after processing config definitions .
2,393
private JoinableResourceBundle buildOrphanResourceBundle ( String orphanPath ) { String mapping = orphanPath ; List < String > paths = Collections . singletonList ( mapping ) ; JoinableResourceBundle newBundle = new JoinableResourceBundleImpl ( orphanPath , generateBundleNameFromBundleId ( orphanPath ) , null , fileExtension , new InclusionPattern ( ) , paths , resourceReaderHandler , jawrConfig . getGeneratorRegistry ( ) ) ; return newBundle ; }
Build a non - global single - file resource bundle for orphans .
2,394
public void setExludedDirMapperDirs ( Set < String > exludedDirMapperDirs ) { if ( null != exludedDirMapperDirs ) this . excludedDirMapperDirs = PathNormalizer . normalizePaths ( exludedDirMapperDirs ) ; }
Sets the paths to exclude when using the dirMapper .
2,395
@ SuppressWarnings ( "static-access" ) public static Object bindings ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { if ( args . length == 1 ) { Object arg = args [ 0 ] ; if ( arg instanceof Wrapper ) { arg = ( ( Wrapper ) arg ) . unwrap ( ) ; } if ( arg instanceof ExternalScriptable ) { ScriptContext ctx = ( ( ExternalScriptable ) arg ) . getContext ( ) ; Bindings bind = ctx . getBindings ( ScriptContext . ENGINE_SCOPE ) ; return Context . javaToJS ( bind , ScriptableObject . getTopLevelScope ( thisObj ) ) ; } } return cx . getUndefinedValue ( ) ; }
The bindings function takes a JavaScript scope object of type ExternalScriptable and returns the underlying Bindings instance .
2,396
public synchronized void write ( byte [ ] b , int off , int len ) throws IOException { super . write ( b , off , len ) ; this . branch . write ( b , off , len ) ; }
Write the specified bytes to both streams .
2,397
public static ResourceReader getResourceReaderProxy ( ResourceGenerator generator , ResourceReaderHandler rsReaderHandler , JawrConfig config ) { ResourceReader proxy = null ; int nbExtraInterface = 0 ; Class < ? > [ ] extraInterfaces = new Class < ? > [ 2 ] ; boolean isResourceGenerator = generator instanceof ResourceGenerator ; boolean isStreamResourceGenerator = generator instanceof StreamResourceGenerator ; if ( isResourceGenerator ) { extraInterfaces [ nbExtraInterface ++ ] = TextResourceReader . class ; } if ( isStreamResourceGenerator ) { extraInterfaces [ nbExtraInterface ++ ] = StreamResourceReader . class ; } Class < ? > [ ] generatorInterfaces = getGeneratorInterfaces ( generator ) ; Class < ? > [ ] implementedInterfaces = new Class [ generatorInterfaces . length + nbExtraInterface ] ; System . arraycopy ( generatorInterfaces , 0 , implementedInterfaces , 0 , generatorInterfaces . length ) ; System . arraycopy ( extraInterfaces , 0 , implementedInterfaces , generatorInterfaces . length , nbExtraInterface ) ; InvocationHandler handler = new ResourceGeneratorReaderWrapperInvocationHandler ( generator , rsReaderHandler , config ) ; proxy = ( ResourceReader ) Proxy . newProxyInstance ( ResourceGeneratorReaderProxyFactory . class . getClassLoader ( ) , implementedInterfaces , handler ) ; return proxy ; }
Creates a Resource reader from a resource generator .
2,398
private static Class < ? > [ ] getGeneratorInterfaces ( ResourceGenerator generator ) { Set < Class < ? > > interfaces = new HashSet < > ( ) ; addInterfaces ( generator , interfaces ) ; return ( Class [ ] ) interfaces . toArray ( new Class [ ] { } ) ; }
Returns the array of interfaces implemented by the ResourceGenerator
2,399
private static void addInterfaces ( Object obj , Set < Class < ? > > interfaces ) { Class < ? > [ ] generatorInterfaces = null ; Class < ? > superClass = null ; if ( obj instanceof Class ) { generatorInterfaces = ( ( Class < ? > ) obj ) . getInterfaces ( ) ; superClass = ( ( Class < ? > ) obj ) . getSuperclass ( ) ; } else { generatorInterfaces = obj . getClass ( ) . getInterfaces ( ) ; superClass = obj . getClass ( ) . getSuperclass ( ) ; } for ( Class < ? > generatorInterface : generatorInterfaces ) { interfaces . add ( generatorInterface ) ; addInterfaces ( generatorInterface , interfaces ) ; } if ( superClass != null && superClass != Object . class ) { addInterfaces ( superClass , interfaces ) ; } }
Adds all the interfaces of the object passed in parameter in the set of interfaces .