text
stringlengths
30
1.67M
<s> package org . payments4j . spi . payflowpro . converter ; import org . payments4j . spi . payflowpro . Pair ; import java . util . ArrayList ; import java . util . List ; public class CredentialsConverter extends AbstractBaseConverter { private String username ; private String password ; public CredentialsConverter ( String username , String password ) { this . username = username ; this . password = password ; } @ Override public List < Pair > toParamsList ( ) { List < Pair > paramsList = new ArrayList < Pair > ( ) ; paramsList . add ( new Pair ( "<STR_LIT>" , username ) ) ; paramsList . add ( new Pair ( "<STR_LIT>" , username ) ) ; paramsList . add ( new Pair ( "<STR_LIT>" , password ) ) ; paramsList . add ( new Pair ( "<STR_LIT>" , "<STR_LIT>" ) ) ; return paramsList ; } } </s>
<s> package org . payments4j . common ; import java . util . Map ; import java . util . UUID ; import static com . google . common . base . Preconditions . checkArgument ; public class ParamUtil { private ParamUtil ( ) { } public static void requireOption ( Map < String , Object > options , String option ) { checkArgument ( options != null && options . get ( option ) != null , "<STR_LIT>" , option ) ; } public static String requestId ( ) { return UUID . randomUUID ( ) . toString ( ) ; } } </s>
<s> package org . payments4j . test . spi ; import org . junit . Before ; import org . junit . Test ; import org . payments4j . core . PaymentGateway ; import org . payments4j . core . TransactionResponse ; import org . payments4j . model . CreditCard ; import org . payments4j . model . CreditCardBuilder ; import org . payments4j . model . Money ; import org . payments4j . model . MoneyBuilder ; import java . util . Locale ; import java . util . Map ; import java . util . Properties ; import java . util . Random ; import static org . fest . assertions . Assertions . assertThat ; import static org . payments4j . model . CreditCard . Type . MASTER_CARD ; public abstract class AbstractBasePaymentGatewayIntegrationTest { protected Money money ; protected CreditCard creditCard ; protected PaymentGateway gateway ; protected Properties credentials ; @ Before public void setUp ( ) throws Exception { if ( credentials == null ) { credentials = new Properties ( ) ; credentials . load ( this . getClass ( ) . getResourceAsStream ( "<STR_LIT>" ) ) ; } int amount = new Random ( System . nanoTime ( ) ) . nextInt ( <NUM_LIT:30> ) ; money = new MoneyBuilder ( ) . withAmount ( String . valueOf ( amount ) ) . withCurrency ( Locale . US ) . build ( ) ; creditCard = getCreditCard ( ) ; this . gateway = buildGateway ( ) ; } protected abstract PaymentGateway buildGateway ( ) ; protected CreditCard getCreditCard ( ) { return new CreditCardBuilder ( ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withMonth ( "<STR_LIT>" ) . withYear ( "<STR_LIT>" ) . withNumber ( "<STR_LIT>" ) . withSecurityCode ( "<STR_LIT>" ) . withType ( MASTER_CARD ) . build ( ) ; } protected Map < String , Object > getCreditOptions ( ) { return null ; } protected Map < String , Object > getCaptureOptions ( ) { return null ; } protected Map < String , Object > getAuthOptions ( ) { return null ; } protected Map < String , Object > getPurchaseOptions ( ) { return null ; } protected Map < String , Object > getRevertOptions ( ) { return null ; } @ Test public void testAuthCaptureCredit ( ) throws Exception { TransactionResponse authResponse = gateway . authorize ( money , creditCard , getAuthOptions ( ) ) ; assertThat ( authResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + authResponse ) . isTrue ( ) ; TransactionResponse captureResponse = gateway . capture ( money , authResponse . getAuthorizationId ( ) , getCaptureOptions ( ) ) ; assertThat ( captureResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + captureResponse ) . isTrue ( ) ; TransactionResponse creditResponse = gateway . credit ( money , captureResponse . getAuthorizationId ( ) , getCreditOptions ( ) ) ; assertThat ( creditResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + creditResponse ) . isTrue ( ) ; } @ Test public void testPurchaseCredit ( ) throws Exception { TransactionResponse purchaseResponse = gateway . purchase ( money , creditCard , getPurchaseOptions ( ) ) ; assertThat ( purchaseResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + purchaseResponse ) . isTrue ( ) ; TransactionResponse creditResponse = gateway . credit ( money , purchaseResponse . getAuthorizationId ( ) , getCreditOptions ( ) ) ; assertThat ( creditResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + creditResponse ) . isTrue ( ) ; } @ Test public void testAuthRevert ( ) throws Exception { TransactionResponse authResponse = gateway . authorize ( money , creditCard , getAuthOptions ( ) ) ; assertThat ( authResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + authResponse ) . isTrue ( ) ; TransactionResponse revertResponse = gateway . revert ( authResponse . getAuthorizationId ( ) , getRevertOptions ( ) ) ; assertThat ( revertResponse . isSuccessful ( ) ) . as ( "<STR_LIT>" + revertResponse ) . isTrue ( ) ; } } </s>
<s> package org . payments4j . core ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; public class TransactionResponse { private boolean successful ; private boolean test ; private String authorizationId ; private String message ; private long code ; private long reasonCode ; private AvsResponse avsResponse ; private CvvResponse cvvResponse ; public boolean isSuccessful ( ) { return successful ; } public void setSuccessful ( boolean successful ) { this . successful = successful ; } public boolean isTest ( ) { return test ; } public void setTest ( boolean test ) { this . test = test ; } public String getAuthorizationId ( ) { return authorizationId ; } public void setAuthorizationId ( String authorizationId ) { this . authorizationId = authorizationId ; } public String getMessage ( ) { return message ; } public void setMessage ( String message ) { this . message = message ; } public long getCode ( ) { return code ; } public void setCode ( long code ) { this . code = code ; } public long getReasonCode ( ) { return reasonCode ; } public void setReasonCode ( long reasonCode ) { this . reasonCode = reasonCode ; } public AvsResponse getAvsResponse ( ) { return avsResponse ; } public void setAvsResponse ( AvsResponse avsResponse ) { this . avsResponse = avsResponse ; } public CvvResponse getCvvResponse ( ) { return cvvResponse ; } public void setCvvResponse ( CvvResponse cvvResponse ) { this . cvvResponse = cvvResponse ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( successful ) . append ( test ) . append ( authorizationId ) . append ( message ) . append ( code ) . append ( reasonCode ) . append ( avsResponse ) . append ( cvvResponse ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } TransactionResponse that = ( TransactionResponse ) o ; return new EqualsBuilder ( ) . append ( this . successful , that . successful ) . append ( this . test , that . test ) . append ( this . authorizationId , that . authorizationId ) . append ( this . message , that . message ) . append ( this . code , that . code ) . append ( this . reasonCode , that . reasonCode ) . append ( this . avsResponse , that . avsResponse ) . append ( this . avsResponse , that . avsResponse ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT>" , successful ) . append ( "<STR_LIT:test>" , test ) . append ( "<STR_LIT>" , authorizationId ) . append ( "<STR_LIT:message>" , message ) . append ( "<STR_LIT:code>" , code ) . append ( "<STR_LIT>" , reasonCode ) . append ( "<STR_LIT>" , avsResponse ) . append ( "<STR_LIT>" , cvvResponse ) . toString ( ) ; } } </s>
<s> package org . payments4j . core ; import org . payments4j . model . CreditCard ; import org . payments4j . model . Money ; import java . util . Map ; public interface PaymentGateway { TransactionResponse purchase ( Money money , CreditCard creditCard , Map < String , Object > options ) ; TransactionResponse authorize ( Money money , CreditCard creditCard , Map < String , Object > options ) ; TransactionResponse capture ( Money money , String authorizationId , Map < String , Object > options ) ; TransactionResponse revert ( String transactionId , Map < String , Object > options ) ; TransactionResponse credit ( Money money , String transactionId , Map < String , Object > options ) ; TransactionResponse recurring ( Money money , CreditCard creditCard , Map < String , Object > options ) ; TransactionResponse storeCreditCard ( CreditCard creditCard , Map < String , Object > options ) ; TransactionResponse evictCreditCard ( String creditCardId , Map < String , Object > options ) ; boolean supportsPurchase ( ) ; boolean supportsAuthorize ( ) ; boolean supportsCapture ( ) ; boolean supportsRevert ( ) ; boolean supportsCredit ( ) ; boolean supportsStoreCreditCard ( ) ; boolean supportsEvictCreditCard ( ) ; void setTest ( boolean test ) ; } </s>
<s> package org . payments4j . core ; import org . payments4j . model . CreditCard ; import org . payments4j . model . Money ; import org . perf4j . StopWatch ; import org . perf4j . slf4j . Slf4JStopWatch ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import java . util . HashMap ; import java . util . Map ; import static java . lang . String . format ; import static org . payments4j . common . ParamUtil . requestId ; public abstract class AbstractPaymentGateway implements PaymentGateway { protected static Logger LOGGER ; protected static StopWatch STOP_WATCH ; protected AbstractPaymentGateway ( ) { LOGGER = LoggerFactory . getLogger ( this . getClass ( ) ) ; STOP_WATCH = new Slf4JStopWatch ( LOGGER ) ; STOP_WATCH . stop ( ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . warn ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; } } @ Override public TransactionResponse purchase ( Money money , CreditCard creditCard , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , money ) ; logParam ( "<STR_LIT>" , requestId , creditCard ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doPurchase ( money , creditCard , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doPurchase ( Money money , CreditCard creditCard , Map < String , Object > options ) ; @ Override public TransactionResponse authorize ( Money money , CreditCard creditCard , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , money ) ; logParam ( "<STR_LIT>" , requestId , creditCard ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doAuthorize ( money , creditCard , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doAuthorize ( Money money , CreditCard creditCard , Map < String , Object > options ) ; @ Override public TransactionResponse capture ( Money money , String authorizationId , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , money ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doCapture ( money , authorizationId , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doCapture ( Money money , String authorizationId , Map < String , Object > options ) ; @ Override public TransactionResponse revert ( String transactionId , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , transactionId ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doRevert ( transactionId , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doRevert ( String transactionId , Map < String , Object > options ) ; @ Override public TransactionResponse credit ( Money money , String transactionId , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , money ) ; logParam ( "<STR_LIT>" , requestId , transactionId ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doCredit ( money , transactionId , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doCredit ( Money money , String transactionId , Map < String , Object > options ) ; @ Override public TransactionResponse recurring ( Money money , CreditCard creditCard , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , money ) ; logParam ( "<STR_LIT>" , requestId , creditCard ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doRecurring ( money , creditCard , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doRecurring ( Money money , CreditCard creditCard , Map < String , Object > options ) ; @ Override public TransactionResponse storeCreditCard ( CreditCard creditCard , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , creditCard ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doStoreCreditCard ( creditCard , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } protected abstract TransactionResponse doStoreCreditCard ( CreditCard creditCard , Map < String , Object > options ) ; @ Override public TransactionResponse evictCreditCard ( String creditCardId , Map < String , Object > options ) { String requestId = requestId ( ) ; options = initOptions ( options ) ; options . put ( "<STR_LIT>" , requestId ) ; logOperationStart ( requestId , "<STR_LIT>" ) ; logParam ( "<STR_LIT>" , requestId , creditCardId ) ; logParam ( "<STR_LIT>" , requestId , options ) ; TransactionResponse transactionResponse = doEvictCreditCard ( creditCardId , options ) ; logResponse ( requestId , transactionResponse ) ; logOperationEnd ( requestId , "<STR_LIT>" ) ; return transactionResponse ; } private Map < String , Object > initOptions ( Map < String , Object > options ) { if ( options == null ) { options = new HashMap < String , Object > ( ) ; } return options ; } protected abstract TransactionResponse doEvictCreditCard ( String creditCardIdd , Map < String , Object > options ) ; private void logResponse ( String requestId , TransactionResponse transactionResponse ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "<STR_LIT>" , requestId , transactionResponse ) ; } } private void logParam ( String name , String requestId , Object value ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "<STR_LIT>" + name + "<STR_LIT>" , requestId , value ) ; } } private void logOperationStart ( String requestId , String operation ) { String message = format ( "<STR_LIT>" , requestId , operation ) ; STOP_WATCH . setTag ( message ) ; LOGGER . info ( message ) ; } private void logOperationEnd ( String requestId , String operation ) { STOP_WATCH . stop ( ) ; LOGGER . info ( "<STR_LIT>" + operation + "<STR_LIT>" , requestId ) ; } } </s>
<s> package org . payments4j . core ; public class AvsResponse { private String code ; private String message ; private String streetMatch ; private String postalMatch ; public String getCode ( ) { return code ; } public void setCode ( String code ) { this . code = code ; } public String getMessage ( ) { return message ; } public void setMessage ( String message ) { this . message = message ; } public String getStreetMatch ( ) { return streetMatch ; } public void setStreetMatch ( String streetMatch ) { this . streetMatch = streetMatch ; } public String getPostalMatch ( ) { return postalMatch ; } public void setPostalMatch ( String postalMatch ) { this . postalMatch = postalMatch ; } } </s>
<s> package org . payments4j . core ; public class CvvResponse { private String code ; private String message ; public String getCode ( ) { return code ; } public void setCode ( String code ) { this . code = code ; } public String getMessage ( ) { return message ; } public void setMessage ( String message ) { this . message = message ; } } </s>
<s> package org . payments4j . model ; public class AddressBuilder extends AbstractBaseModelBuilder < Address > { public AddressBuilder ( ) { super ( Address . class ) ; } public AddressBuilder withFirstName ( String firstName ) { values . put ( "<STR_LIT>" , firstName ) ; return this ; } public AddressBuilder withLastName ( String lastName ) { values . put ( "<STR_LIT>" , lastName ) ; return this ; } public AddressBuilder withEmail ( String email ) { values . put ( "<STR_LIT:email>" , email ) ; return this ; } public AddressBuilder withCompany ( String company ) { values . put ( "<STR_LIT>" , company ) ; return this ; } public AddressBuilder withAddress1 ( String address1 ) { values . put ( "<STR_LIT>" , address1 ) ; return this ; } public AddressBuilder withAddress2 ( String address2 ) { values . put ( "<STR_LIT>" , address2 ) ; return this ; } public AddressBuilder withCity ( String city ) { values . put ( "<STR_LIT>" , city ) ; return this ; } public AddressBuilder withState ( String state ) { values . put ( "<STR_LIT:state>" , state ) ; return this ; } public AddressBuilder withCountryIsoCode ( String countryIsoCode ) { values . put ( "<STR_LIT>" , countryIsoCode ) ; return this ; } public AddressBuilder withPostalCode ( String postalCode ) { values . put ( "<STR_LIT>" , postalCode ) ; return this ; } public AddressBuilder withPhone ( String phone ) { values . put ( "<STR_LIT>" , phone ) ; return this ; } } </s>
<s> package org . payments4j . model ; public class OrderLineBuilder extends AbstractBaseModelBuilder < OrderLine > { public OrderLineBuilder ( ) { super ( OrderLine . class ) ; } public OrderLineBuilder withId ( String id ) { values . put ( "<STR_LIT:id>" , id ) ; return this ; } public OrderLineBuilder withUnitPrice ( Money unitPrice ) { values . put ( "<STR_LIT>" , unitPrice ) ; return this ; } public OrderLineBuilder withQuantity ( long quantity ) { values . put ( "<STR_LIT>" , quantity ) ; return this ; } public OrderLineBuilder withDescription ( String description ) { values . put ( "<STR_LIT:description>" , description ) ; return this ; } } </s>
<s> package org . payments4j . model ; import java . util . Set ; public class OrderBuilder extends AbstractBaseModelBuilder < Order > { public OrderBuilder ( ) { super ( Order . class ) ; } public OrderBuilder withId ( String id ) { values . put ( "<STR_LIT:id>" , id ) ; return this ; } public OrderBuilder withIpAddress ( String ipAddress ) { values . put ( "<STR_LIT>" , ipAddress ) ; return this ; } public OrderBuilder withCustomerName ( String customerName ) { values . put ( "<STR_LIT>" , customerName ) ; return this ; } public OrderBuilder withCustomerEmail ( String customerEmail ) { values . put ( "<STR_LIT>" , customerEmail ) ; return this ; } public OrderBuilder withInvoiceNumber ( String invoiceNumber ) { values . put ( "<STR_LIT>" , invoiceNumber ) ; return this ; } public OrderBuilder withMerchant ( String merchant ) { values . put ( "<STR_LIT>" , merchant ) ; return this ; } public OrderBuilder withDescription ( String description ) { values . put ( "<STR_LIT:description>" , description ) ; return this ; } public OrderBuilder withBillingAddress ( Address billingAddress ) { values . put ( "<STR_LIT>" , billingAddress ) ; return this ; } public OrderBuilder withShippingAddress ( Address shippingAddress ) { values . put ( "<STR_LIT>" , shippingAddress ) ; return this ; } public OrderBuilder withOrderLines ( Set < OrderLine > orderLines ) { values . put ( "<STR_LIT>" , orderLines ) ; return this ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; public class OrderLine { private String id ; private Money unitPrice ; private long quantity ; private String description ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public Money getUnitPrice ( ) { return unitPrice ; } public void setUnitPrice ( Money unitPrice ) { this . unitPrice = unitPrice ; } public long getQuantity ( ) { return quantity ; } public void setQuantity ( long quantity ) { this . quantity = quantity ; } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( this . id ) . append ( this . unitPrice ) . append ( this . quantity ) . append ( this . description ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } OrderLine that = ( OrderLine ) o ; return new EqualsBuilder ( ) . append ( this . id , that . id ) . append ( this . unitPrice , that . unitPrice ) . append ( this . quantity , that . quantity ) . append ( this . description , that . description ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT:id>" , this . id ) . append ( "<STR_LIT>" , this . unitPrice ) . append ( "<STR_LIT>" , this . quantity ) . append ( "<STR_LIT:description>" , this . description ) . toString ( ) ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; public class Address { private String firstName ; private String lastName ; private String email ; private String company ; private String address1 ; private String address2 ; private String city ; private String state ; private String countryIsoCode ; private String postalCode ; private String phone ; public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } public String getLastName ( ) { return lastName ; } public void setLastName ( String lastName ) { this . lastName = lastName ; } public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this . email = email ; } public String getCompany ( ) { return company ; } public void setCompany ( String company ) { this . company = company ; } public String getAddress1 ( ) { return address1 ; } public void setAddress1 ( String address1 ) { this . address1 = address1 ; } public String getAddress2 ( ) { return address2 ; } public void setAddress2 ( String address2 ) { this . address2 = address2 ; } public String getCity ( ) { return city ; } public void setCity ( String city ) { this . city = city ; } public String getState ( ) { return state ; } public void setState ( String state ) { this . state = state ; } public String getCountryIsoCode ( ) { return countryIsoCode ; } public void setCountryIsoCode ( String countryIsoCode ) { this . countryIsoCode = countryIsoCode ; } public String getPostalCode ( ) { return postalCode ; } public void setPostalCode ( String postalCode ) { this . postalCode = postalCode ; } public String getPhone ( ) { return phone ; } public void setPhone ( String phone ) { this . phone = phone ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( this . firstName ) . append ( this . lastName ) . append ( this . email ) . append ( this . company ) . append ( this . address1 ) . append ( this . address2 ) . append ( this . city ) . append ( this . state ) . append ( this . countryIsoCode ) . append ( this . postalCode ) . append ( this . phone ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } Address that = ( Address ) o ; return new EqualsBuilder ( ) . append ( this . firstName , that . firstName ) . append ( this . lastName , that . lastName ) . append ( this . email , that . email ) . append ( this . company , that . company ) . append ( this . address1 , that . address1 ) . append ( this . address2 , that . address2 ) . append ( this . city , that . city ) . append ( this . state , that . state ) . append ( this . countryIsoCode , that . countryIsoCode ) . append ( this . postalCode , that . postalCode ) . append ( this . phone , that . phone ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT>" , this . firstName ) . append ( "<STR_LIT>" , this . lastName ) . append ( "<STR_LIT:email>" , this . email ) . append ( "<STR_LIT>" , this . company ) . append ( "<STR_LIT>" , this . address1 ) . append ( "<STR_LIT>" , this . address2 ) . append ( "<STR_LIT>" , this . city ) . append ( "<STR_LIT:state>" , this . state ) . append ( "<STR_LIT>" , this . countryIsoCode ) . append ( "<STR_LIT>" , this . postalCode ) . append ( "<STR_LIT>" , this . phone ) . toString ( ) ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; import java . util . Set ; public class Order { private String id ; private String ipAddress ; private String customerName ; private String customerEmail ; private String invoiceNumber ; private String merchant ; private String description ; private Address billingAddress ; private Address shippingAddress ; private Set < OrderLine > orderLines ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getIpAddress ( ) { return ipAddress ; } public void setIpAddress ( String ipAddress ) { this . ipAddress = ipAddress ; } public String getCustomerName ( ) { return customerName ; } public void setCustomerName ( String customerName ) { this . customerName = customerName ; } public String getCustomerEmail ( ) { return customerEmail ; } public void setCustomerEmail ( String customerEmail ) { this . customerEmail = customerEmail ; } public String getInvoiceNumber ( ) { return invoiceNumber ; } public void setInvoiceNumber ( String invoiceNumber ) { this . invoiceNumber = invoiceNumber ; } public String getMerchant ( ) { return merchant ; } public void setMerchant ( String merchant ) { this . merchant = merchant ; } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } public Address getBillingAddress ( ) { return billingAddress ; } public void setBillingAddress ( Address billingAddress ) { this . billingAddress = billingAddress ; } public Address getShippingAddress ( ) { return shippingAddress ; } public void setShippingAddress ( Address shippingAddress ) { this . shippingAddress = shippingAddress ; } public Set < OrderLine > getOrderLines ( ) { return orderLines ; } public void setOrderLines ( Set < OrderLine > orderLines ) { this . orderLines = orderLines ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( this . id ) . append ( this . ipAddress ) . append ( this . customerName ) . append ( this . customerEmail ) . append ( this . invoiceNumber ) . append ( this . merchant ) . append ( this . description ) . append ( this . billingAddress ) . append ( this . shippingAddress ) . append ( this . orderLines ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } Order that = ( Order ) o ; return new EqualsBuilder ( ) . append ( this . id , that . id ) . append ( this . ipAddress , that . ipAddress ) . append ( this . customerName , that . customerName ) . append ( this . customerEmail , that . customerEmail ) . append ( this . invoiceNumber , that . invoiceNumber ) . append ( this . merchant , that . merchant ) . append ( this . description , that . description ) . append ( this . billingAddress , that . billingAddress ) . append ( this . shippingAddress , that . shippingAddress ) . append ( this . orderLines , that . orderLines ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT:id>" , this . id ) . append ( "<STR_LIT>" , this . ipAddress ) . append ( "<STR_LIT>" , this . customerName ) . append ( "<STR_LIT>" , this . customerEmail ) . append ( "<STR_LIT>" , this . invoiceNumber ) . append ( "<STR_LIT>" , this . merchant ) . append ( "<STR_LIT:description>" , this . description ) . append ( "<STR_LIT>" , this . billingAddress ) . append ( "<STR_LIT>" , this . shippingAddress ) . append ( "<STR_LIT>" , this . orderLines ) . toString ( ) ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; import static com . google . common . base . Preconditions . checkArgument ; public class CreditCard { public enum Type { VISA , MASTER_CARD , AMERICAN_EXPRESS , DISCOVER , JCP , CARTE_BLANCHE , DINERS_CLUB , EN_ROUTE , LASER , MAESTRO , SOLO , SWITCH } private String firstName ; private String lastName ; private String number ; private String month ; private String year ; private Type type ; private String securityCode ; public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } public String getLastName ( ) { return lastName ; } public void setLastName ( String lastName ) { this . lastName = lastName ; } public String getNumber ( ) { return number ; } public void setNumber ( String number ) { this . number = number ; } public String getMonth ( ) { return month ; } public void setMonth ( String month ) { checkArgument ( Integer . valueOf ( month ) >= <NUM_LIT:1> && Integer . valueOf ( month ) <= <NUM_LIT:12> , "<STR_LIT>" ) ; this . month = month ; } public String getYear ( ) { return year ; } public void setYear ( String year ) { checkArgument ( Integer . valueOf ( year ) >= <NUM_LIT> && Integer . valueOf ( year ) <= <NUM_LIT> , "<STR_LIT>" ) ; this . year = year ; } public Type getType ( ) { return type ; } public void setType ( Type type ) { this . type = type ; } public String getSecurityCode ( ) { return securityCode ; } public void setSecurityCode ( String securityCode ) { checkArgument ( securityCode . length ( ) >= <NUM_LIT:2> && securityCode . length ( ) <= <NUM_LIT:4> , "<STR_LIT>" ) ; this . securityCode = securityCode ; } public boolean isValid ( ) { return false ; } public boolean isExpired ( ) { return true ; } public String getDisplayNumber ( ) { return "<STR_LIT>" ; } public String getLastDigits ( ) { return "<STR_LIT>" ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( this . firstName ) . append ( this . lastName ) . append ( this . number ) . append ( this . month ) . append ( this . year ) . append ( this . type ) . append ( this . securityCode ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } CreditCard that = ( CreditCard ) o ; return new EqualsBuilder ( ) . append ( this . firstName , that . firstName ) . append ( this . lastName , that . lastName ) . append ( this . number , that . number ) . append ( this . month , that . month ) . append ( this . year , that . year ) . append ( this . type , that . type ) . append ( this . securityCode , that . securityCode ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT>" , this . firstName ) . append ( "<STR_LIT>" , this . lastName ) . append ( "<STR_LIT:number>" , this . number ) . append ( "<STR_LIT>" , this . month ) . append ( "<STR_LIT>" , this . year ) . append ( "<STR_LIT:type>" , this . type ) . append ( "<STR_LIT>" , this . securityCode ) . toString ( ) ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; import org . apache . commons . lang . builder . ToStringBuilder ; import java . math . BigDecimal ; import java . util . Currency ; import java . util . Locale ; public class Money { private BigDecimal amount ; private Currency currency ; public Money ( BigDecimal amount , Currency currency ) { this . amount = amount ; this . currency = currency ; } public Money ( String amount , Locale locale ) { this ( new BigDecimal ( amount ) , Currency . getInstance ( locale ) ) ; } public BigDecimal getAmount ( ) { return amount ; } public Currency getCurrency ( ) { return currency ; } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) . append ( this . amount ) . append ( this . currency ) . toHashCode ( ) ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } Money that = ( Money ) o ; return new EqualsBuilder ( ) . append ( this . amount , that . amount ) . append ( this . currency , that . currency ) . isEquals ( ) ; } @ Override public String toString ( ) { return new ToStringBuilder ( this ) . append ( "<STR_LIT>" , this . amount ) . append ( "<STR_LIT>" , this . currency ) . toString ( ) ; } } </s>
<s> package org . payments4j . model ; public class CreditCardBuilder extends AbstractBaseModelBuilder < CreditCard > { public CreditCardBuilder ( ) { super ( CreditCard . class ) ; } public CreditCardBuilder withFirstName ( String firstName ) { values . put ( "<STR_LIT>" , firstName ) ; return this ; } public CreditCardBuilder withLastName ( String lastName ) { values . put ( "<STR_LIT>" , lastName ) ; return this ; } public CreditCardBuilder withNumber ( String number ) { values . put ( "<STR_LIT:number>" , number ) ; return this ; } public CreditCardBuilder withMonth ( String month ) { values . put ( "<STR_LIT>" , month ) ; return this ; } public CreditCardBuilder withYear ( String year ) { values . put ( "<STR_LIT>" , year ) ; return this ; } public CreditCardBuilder withType ( CreditCard . Type type ) { values . put ( "<STR_LIT:type>" , type ) ; return this ; } public CreditCardBuilder withSecurityCode ( String securityCode ) { values . put ( "<STR_LIT>" , securityCode ) ; return this ; } } </s>
<s> package org . payments4j . model ; import java . math . BigDecimal ; import java . util . Currency ; import java . util . Locale ; public class MoneyBuilder extends AbstractBaseModelBuilder < Money > { public MoneyBuilder ( ) { super ( Money . class ) ; } public MoneyBuilder withAmount ( String amount ) { values . put ( "<STR_LIT>" , new BigDecimal ( amount ) ) ; return this ; } public MoneyBuilder withAmount ( BigDecimal amount ) { values . put ( "<STR_LIT>" , amount ) ; return this ; } public MoneyBuilder withCurrency ( Currency currency ) { values . put ( "<STR_LIT>" , currency ) ; return this ; } public MoneyBuilder withCurrency ( Locale locale ) { values . put ( "<STR_LIT>" , Currency . getInstance ( locale ) ) ; return this ; } @ Override public Money build ( ) { BigDecimal amount ; Object amountObj = values . get ( "<STR_LIT>" ) ; if ( amountObj == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } if ( amountObj instanceof String ) { amount = new BigDecimal ( ( String ) amountObj ) ; } else { amount = ( BigDecimal ) amountObj ; } Currency currency ; Object currencyObj = values . get ( "<STR_LIT>" ) ; if ( currencyObj == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } if ( currencyObj instanceof Locale ) { currency = Currency . getInstance ( ( Locale ) currencyObj ) ; } else { currency = ( Currency ) currencyObj ; } return new Money ( amount , currency ) ; } } </s>
<s> package org . payments4j . model ; import org . apache . commons . beanutils . WrapDynaBean ; import java . util . HashMap ; import java . util . Map ; public class AbstractBaseModelBuilder < T > { protected Map < String , Object > values = new HashMap < String , Object > ( ) ; protected Class < T > clazz ; public AbstractBaseModelBuilder ( Class < T > clazz ) { this . clazz = clazz ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public T build ( ) { try { WrapDynaBean bean = new WrapDynaBean ( clazz . newInstance ( ) ) ; for ( String key : values . keySet ( ) ) { bean . set ( key , values . get ( key ) ) ; } values . clear ( ) ; return ( T ) bean . getInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } } </s>
<s> package org . payments4j . spi . authorizenet ; import org . junit . Ignore ; import org . junit . Test ; import org . payments4j . core . PaymentGateway ; import org . payments4j . test . spi . AbstractBasePaymentGatewayIntegrationTest ; import java . util . HashMap ; import java . util . Map ; public class AuthorizeNetPaymentGatewayIntegrationTest extends AbstractBasePaymentGatewayIntegrationTest { protected PaymentGateway buildGateway ( ) { PaymentGateway gateway = new AuthorizeNetPaymentGateway ( credentials . getProperty ( "<STR_LIT>" ) , credentials . getProperty ( "<STR_LIT>" ) ) ; gateway . setTest ( true ) ; return gateway ; } @ Override @ Test @ Ignore ( "<STR_LIT>" + "<STR_LIT>" ) public void testAuthRevert ( ) throws Exception { super . testAuthRevert ( ) ; } @ Override @ Test @ Ignore ( "<STR_LIT>" + "<STR_LIT>" ) public void testAuthCaptureCredit ( ) throws Exception { super . testAuthCaptureCredit ( ) ; } @ Override protected Map < String , Object > getCreditOptions ( ) { Map < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; return options ; } } </s>
<s> package org . payments4j . spi . authorizenet ; import net . authorize . Merchant ; import net . authorize . ResponseField ; import net . authorize . Result ; import net . authorize . TransactionType ; import net . authorize . aim . Transaction ; import net . authorize . data . creditcard . CreditCard ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . ArgumentCaptor ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import org . payments4j . core . TransactionResponse ; import org . payments4j . model . CreditCardBuilder ; import org . payments4j . model . Money ; import org . payments4j . model . MoneyBuilder ; import java . math . BigDecimal ; import java . util . HashMap ; import java . util . Locale ; import java . util . Map ; import static net . authorize . TransactionType . * ; import static org . fest . assertions . Assertions . assertThat ; import static org . mockito . Mockito . * ; import static org . payments4j . model . CreditCard . Type . MASTER_CARD ; @ RunWith ( MockitoJUnitRunner . class ) public class AuthorizeNetPaymentGatewayTest { private static final String LOGIN_ID = "<STR_LIT>" ; private static final String TRANSACTION_KEY = "<STR_LIT>" ; @ Mock private Merchant mockMerchant ; private AuthorizeNetPaymentGateway_ForTest gateway ; private Money money ; private org . payments4j . model . CreditCard creditCard ; @ Before public void setUp ( ) throws Exception { gateway = new AuthorizeNetPaymentGateway_ForTest ( LOGIN_ID , TRANSACTION_KEY ) ; money = new MoneyBuilder ( ) . withAmount ( "<STR_LIT:10>" ) . withCurrency ( Locale . US ) . build ( ) ; creditCard = new CreditCardBuilder ( ) . withNumber ( "<STR_LIT>" ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withMonth ( "<STR_LIT>" ) . withYear ( "<STR_LIT>" ) . withType ( MASTER_CARD ) . withSecurityCode ( "<STR_LIT:123>" ) . build ( ) ; } @ Test public void testPurchase ( ) throws Exception { Transaction mockTransaction = setUpTransactionMock ( AUTH_CAPTURE , new BigDecimal ( "<STR_LIT:10>" ) ) ; TransactionResponse transactionResponse = gateway . purchase ( money , creditCard , null ) ; verifyTransactionResult ( mockTransaction , transactionResponse ) ; } @ Test public void testAuthorize ( ) throws Exception { Transaction mockTransaction = setUpTransactionMock ( AUTH_ONLY , new BigDecimal ( "<STR_LIT:10>" ) ) ; TransactionResponse transactionResponse = gateway . authorize ( money , creditCard , null ) ; verifyTransactionResult ( mockTransaction , transactionResponse ) ; } @ Test public void testCapture ( ) throws Exception { Transaction mockTransaction = setUpTransactionMock ( PRIOR_AUTH_CAPTURE , new BigDecimal ( "<STR_LIT:10>" ) ) ; TransactionResponse transactionResponse = gateway . capture ( money , "<STR_LIT>" , null ) ; verifyTransactionResultWithTransactionId ( mockTransaction , transactionResponse ) ; } @ Test @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void testRevert ( ) throws Exception { Transaction mockTransaction = setUpTransactionMock ( VOID , null ) ; TransactionResponse transactionResponse = gateway . revert ( "<STR_LIT>" , null ) ; verifyTransactionResultWithTransactionId ( mockTransaction , transactionResponse ) ; } @ Test public void testCredit ( ) throws Exception { Transaction mockTransaction = setUpTransactionMock ( CREDIT , new BigDecimal ( "<STR_LIT:10>" ) ) ; HashMap < String , Object > optionals = new HashMap < String , Object > ( ) ; optionals . put ( "<STR_LIT>" , "<STR_LIT>" ) ; optionals . put ( "<STR_LIT>" , "<STR_LIT>" ) ; optionals . put ( "<STR_LIT>" , "<STR_LIT>" ) ; TransactionResponse transactionResponse = gateway . credit ( money , "<STR_LIT>" , optionals ) ; assertThat ( gateway . buildMerchant_wasCalled ) . isTrue ( ) ; verify ( mockTransaction ) . setTransactionId ( "<STR_LIT>" ) ; CreditCard value = captureCreditCard ( mockTransaction ) ; assertThat ( value . getCreditCardNumber ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( value . getExpirationMonth ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( value . getExpirationYear ( ) ) . isEqualTo ( "<STR_LIT>" ) ; verifyTransactionResponse ( transactionResponse , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; } private void verifyTransactionResultWithTransactionId ( Transaction mockTransaction , TransactionResponse transactionResponse ) { assertThat ( gateway . buildMerchant_wasCalled ) . isTrue ( ) ; verify ( mockTransaction ) . setTransactionId ( "<STR_LIT>" ) ; verifyTransactionResponse ( transactionResponse , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; } private void verifyTransactionResult ( Transaction mockTransaction , TransactionResponse transactionResponse ) { assertThat ( gateway . buildMerchant_wasCalled ) . isTrue ( ) ; CreditCard value = captureCreditCard ( mockTransaction ) ; assertThatCreditCardEquals ( value , creditCard ) ; verifyTransactionResponse ( transactionResponse , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) private Transaction setUpTransactionMock ( TransactionType transactionType , BigDecimal amount ) { Transaction mockTransaction = mock ( Transaction . class ) ; when ( mockMerchant . createAIMTransaction ( transactionType , amount ) ) . thenReturn ( mockTransaction ) ; Result < Transaction > mockResult = buildMockResult ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; when ( mockMerchant . postTransaction ( mockTransaction ) ) . thenReturn ( ( Result ) mockResult ) ; return mockTransaction ; } private CreditCard captureCreditCard ( Transaction mockTransaction ) { ArgumentCaptor < CreditCard > captor = ArgumentCaptor . forClass ( CreditCard . class ) ; verify ( mockTransaction ) . setCreditCard ( captor . capture ( ) ) ; return captor . getValue ( ) ; } private void verifyTransactionResponse ( TransactionResponse transactionResponse , String code , String message , String reasonCode , String authId ) { assertThat ( transactionResponse . getCode ( ) ) . isEqualTo ( Long . valueOf ( code ) ) ; assertThat ( transactionResponse . getMessage ( ) ) . isEqualTo ( message ) ; assertThat ( transactionResponse . getReasonCode ( ) ) . isEqualTo ( Long . valueOf ( reasonCode ) ) ; assertThat ( transactionResponse . getAuthorizationId ( ) ) . isEqualTo ( authId ) ; assertThat ( transactionResponse . isSuccessful ( ) ) . isTrue ( ) ; } private Result < Transaction > buildMockResult ( String code , String message , String reasonCode , String authId ) { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Result < Transaction > mockResult = mock ( Result . class ) ; Transaction mockResultTransaction = mock ( Transaction . class ) ; Map < ResponseField , String > responseMap = new HashMap < ResponseField , String > ( ) ; responseMap . put ( ResponseField . RESPONSE_CODE , code ) ; responseMap . put ( ResponseField . RESPONSE_REASON_TEXT , message ) ; responseMap . put ( ResponseField . RESPONSE_REASON_CODE , reasonCode ) ; responseMap . put ( ResponseField . AUTHORIZATION_CODE , authId ) ; when ( mockResultTransaction . getResponseMap ( ) ) . thenReturn ( responseMap ) ; when ( mockResult . getTarget ( ) ) . thenReturn ( mockResultTransaction ) ; return mockResult ; } private void assertThatCreditCardEquals ( CreditCard value , org . payments4j . model . CreditCard creditCard ) { assertThat ( value . getCreditCardNumber ( ) ) . isEqualTo ( creditCard . getNumber ( ) ) ; assertThat ( value . getExpirationYear ( ) ) . isEqualTo ( creditCard . getYear ( ) ) ; assertThat ( value . getExpirationMonth ( ) ) . isEqualTo ( creditCard . getMonth ( ) ) ; assertThat ( value . getCardCodeVerification ( ) ) . isEqualTo ( creditCard . getSecurityCode ( ) ) ; assertThat ( value . getCardType ( ) . name ( ) ) . isEqualToIgnoringCase ( creditCard . getType ( ) . name ( ) ) ; } private class AuthorizeNetPaymentGateway_ForTest extends AuthorizeNetPaymentGateway { private boolean buildMerchant_wasCalled ; public AuthorizeNetPaymentGateway_ForTest ( String apiLoginId , String transactionKey ) { super ( apiLoginId , transactionKey ) ; } @ Override Merchant buildMerchant ( String apiLoginId , String transactionKey ) { assertThat ( apiLoginId ) . isEqualTo ( LOGIN_ID ) ; assertThat ( transactionKey ) . isEqualTo ( transactionKey ) ; buildMerchant_wasCalled = true ; return mockMerchant ; } } } </s>
<s> package org . payments4j . spi . authorizenet ; import net . authorize . Environment ; import net . authorize . Merchant ; import net . authorize . ResponseCode ; import net . authorize . ResponseField ; import net . authorize . Result ; import net . authorize . TransactionType ; import net . authorize . aim . Transaction ; import net . authorize . data . creditcard . CardType ; import org . payments4j . core . AbstractPaymentGateway ; import org . payments4j . core . TransactionResponse ; import org . payments4j . model . CreditCard ; import org . payments4j . model . Money ; import java . math . BigDecimal ; import java . util . Map ; import static net . authorize . TransactionType . AUTH_CAPTURE ; import static net . authorize . TransactionType . AUTH_ONLY ; import static net . authorize . TransactionType . CREDIT ; import static net . authorize . TransactionType . PRIOR_AUTH_CAPTURE ; import static net . authorize . TransactionType . VOID ; import static org . payments4j . common . ParamUtil . requireOption ; public class AuthorizeNetPaymentGateway extends AbstractPaymentGateway { private String apiLoginId ; private String transactionKey ; private boolean test ; public AuthorizeNetPaymentGateway ( String apiLoginId , String transactionKey ) { this . apiLoginId = apiLoginId ; this . transactionKey = transactionKey ; } @ Override public TransactionResponse doPurchase ( Money money , CreditCard creditCard , Map < String , Object > specificOptions ) { return executeTransactionWithCreditCard ( AUTH_CAPTURE , creditCard , money . getAmount ( ) ) ; } @ Override public TransactionResponse doAuthorize ( Money money , CreditCard creditCard , Map < String , Object > options ) { return executeTransactionWithCreditCard ( AUTH_ONLY , creditCard , money . getAmount ( ) ) ; } @ Override public TransactionResponse doCapture ( Money money , String authorizationId , Map < String , Object > options ) { return executeTransactionWithTransactionId ( PRIOR_AUTH_CAPTURE , authorizationId , money . getAmount ( ) ) ; } @ Override public TransactionResponse doRevert ( String transactionId , Map < String , Object > options ) { return executeTransactionWithTransactionId ( VOID , transactionId , null ) ; } @ Override public TransactionResponse doCredit ( Money money , String transactionId , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; requireOption ( options , "<STR_LIT>" ) ; requireOption ( options , "<STR_LIT>" ) ; Merchant merchant = buildMerchant ( apiLoginId , transactionKey ) ; Transaction transaction = merchant . createAIMTransaction ( CREDIT , money . getAmount ( ) ) ; transaction . setTransactionId ( transactionId ) ; net . authorize . data . creditcard . CreditCard creditCard = net . authorize . data . creditcard . CreditCard . createCreditCard ( ) ; creditCard . setCreditCardNumber ( ( String ) options . get ( "<STR_LIT>" ) ) ; creditCard . setExpirationMonth ( ( String ) options . get ( "<STR_LIT>" ) ) ; creditCard . setExpirationYear ( ( String ) options . get ( "<STR_LIT>" ) ) ; transaction . setCreditCard ( creditCard ) ; Result < ? > result = merchant . postTransaction ( transaction ) ; return convert ( result ) ; } @ Override public TransactionResponse doRecurring ( Money money , CreditCard creditCard , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public TransactionResponse doStoreCreditCard ( CreditCard creditCard , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public TransactionResponse doEvictCreditCard ( String creditCardId , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean supportsPurchase ( ) { return true ; } @ Override public boolean supportsAuthorize ( ) { return true ; } @ Override public boolean supportsCapture ( ) { return true ; } @ Override public boolean supportsRevert ( ) { return true ; } @ Override public boolean supportsCredit ( ) { return true ; } @ Override public boolean supportsStoreCreditCard ( ) { return false ; } @ Override public boolean supportsEvictCreditCard ( ) { return false ; } private TransactionResponse executeTransactionWithTransactionId ( TransactionType transactionType , String authorizationId , BigDecimal amount ) { Merchant merchant = buildMerchant ( apiLoginId , transactionKey ) ; Transaction transaction = merchant . createAIMTransaction ( transactionType , amount ) ; transaction . setTransactionId ( authorizationId ) ; Result < ? > result = merchant . postTransaction ( transaction ) ; return convert ( result ) ; } private TransactionResponse executeTransactionWithCreditCard ( TransactionType transactionType , CreditCard creditCard , BigDecimal amount ) { Merchant merchant = buildMerchant ( apiLoginId , transactionKey ) ; Transaction transaction = merchant . createAIMTransaction ( transactionType , amount ) ; transaction . setCreditCard ( convert ( creditCard ) ) ; Result < ? > result = merchant . postTransaction ( transaction ) ; return convert ( result ) ; } @ Override public void setTest ( boolean test ) { this . test = test ; } private TransactionResponse convert ( Result < ? > result ) { TransactionResponse response = new TransactionResponse ( ) ; Transaction transaction = ( Transaction ) result . getTarget ( ) ; response . setCode ( getLongResponseField ( transaction , ResponseField . RESPONSE_CODE ) ) ; response . setReasonCode ( getLongResponseField ( transaction , ResponseField . RESPONSE_REASON_CODE ) ) ; response . setMessage ( getStringResponseField ( transaction , ResponseField . RESPONSE_REASON_TEXT ) ) ; response . setAuthorizationId ( getStringResponseField ( transaction , ResponseField . AUTHORIZATION_CODE ) ) ; response . setSuccessful ( ResponseCode . APPROVED == ResponseCode . findByResponseCode ( ( int ) response . getCode ( ) ) ) ; return response ; } private Long getLongResponseField ( Transaction transaction , ResponseField field ) { return Long . valueOf ( getStringResponseField ( transaction , field ) ) ; } private String getStringResponseField ( Transaction transaction , ResponseField field ) { return transaction . getResponseMap ( ) . get ( field ) ; } private net . authorize . data . creditcard . CreditCard convert ( CreditCard creditCard ) { net . authorize . data . creditcard . CreditCard converted = net . authorize . data . creditcard . CreditCard . createCreditCard ( ) ; converted . setCreditCardNumber ( creditCard . getNumber ( ) ) ; converted . setExpirationMonth ( creditCard . getMonth ( ) ) ; converted . setExpirationYear ( creditCard . getYear ( ) ) ; converted . setCardCodeVerification ( creditCard . getSecurityCode ( ) ) ; converted . setCardType ( CardType . valueOf ( creditCard . getType ( ) . name ( ) ) ) ; return converted ; } Merchant buildMerchant ( String apiLoginId , String transactionKey ) { Environment environment = Environment . PRODUCTION ; if ( test ) { environment = Environment . SANDBOX ; } return Merchant . createMerchant ( environment , apiLoginId , transactionKey ) ; } } </s>
<s> package org . payments4j . spi . cybersource ; import com . cybersource . schemas . transaction_data . transactionprocessor . ITransactionProcessor ; import com . cybersource . schemas . transaction_data . transactionprocessor . TransactionProcessor ; import com . cybersource . schemas . transaction_data_1 . PurchaseTotals ; import com . cybersource . schemas . transaction_data_1 . ReplyMessage ; import com . cybersource . schemas . transaction_data_1 . RequestMessage ; import com . google . common . annotations . VisibleForTesting ; import org . apache . cxf . endpoint . Endpoint ; import org . apache . cxf . frontend . ClientProxy ; import org . apache . cxf . ws . security . wss4j . WSS4JOutInterceptor ; import org . payments4j . core . AbstractPaymentGateway ; import org . payments4j . core . TransactionResponse ; import org . payments4j . model . CreditCard ; import org . payments4j . model . Money ; import org . payments4j . model . Order ; import org . payments4j . spi . cybersource . converter . AddressConverter ; import org . payments4j . spi . cybersource . converter . CreditCardConverter ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . HashMap ; import java . util . Map ; import static java . lang . String . format ; import static org . apache . ws . security . WSConstants . PW_TEXT ; import static org . apache . ws . security . handler . WSHandlerConstants . ACTION ; import static org . apache . ws . security . handler . WSHandlerConstants . PASSWORD_TYPE ; import static org . apache . ws . security . handler . WSHandlerConstants . PW_CALLBACK_REF ; import static org . apache . ws . security . handler . WSHandlerConstants . USER ; import static org . apache . ws . security . handler . WSHandlerConstants . USERNAME_TOKEN ; import static org . payments4j . common . ParamUtil . requireOption ; import static org . payments4j . spi . cybersource . TransactionType . AUTHORIZE ; import static org . payments4j . spi . cybersource . TransactionType . CAPTURE ; import static org . payments4j . spi . cybersource . TransactionType . CREDIT ; import static org . payments4j . spi . cybersource . TransactionType . PURCHASE ; import static org . payments4j . spi . cybersource . TransactionType . REVERT ; public class CybersourcePaymentGateway extends AbstractPaymentGateway { public static final URL HOSTNAME = initUrl ( "<STR_LIT>" ) ; public static final URL TEST_HOSTNAME = initUrl ( "<STR_LIT>" ) ; private boolean test ; private String username ; private String transactionKey ; public CybersourcePaymentGateway ( String username , String transactionKey ) { this . username = username ; this . transactionKey = transactionKey ; } @ Override public TransactionResponse doPurchase ( Money money , CreditCard creditCard , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; requireOption ( options , "<STR_LIT>" ) ; ITransactionProcessor processor = buildTransactionProcessor ( ) ; Order order = ( Order ) options . get ( "<STR_LIT>" ) ; RequestMessage request = buildRequestMessage ( PURCHASE , money , creditCard , order ) ; request . setMerchantReferenceCode ( ( String ) options . get ( "<STR_LIT>" ) ) ; return executeTransaction ( processor , request ) ; } @ Override public TransactionResponse doAuthorize ( Money money , CreditCard creditCard , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; requireOption ( options , "<STR_LIT>" ) ; ITransactionProcessor processor = buildTransactionProcessor ( ) ; Order order = ( Order ) options . get ( "<STR_LIT>" ) ; RequestMessage request = buildRequestMessage ( AUTHORIZE , money , creditCard , order ) ; request . setMerchantReferenceCode ( ( String ) options . get ( "<STR_LIT>" ) ) ; return executeTransaction ( processor , request ) ; } @ Override public TransactionResponse doCapture ( Money money , String authorizationId , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; ITransactionProcessor processor = buildTransactionProcessor ( ) ; RequestMessage request = buildRequestMessage ( CAPTURE , money , null , null ) ; request . setMerchantReferenceCode ( ( String ) options . get ( "<STR_LIT>" ) ) ; request . getCcCaptureService ( ) . setAuthRequestID ( authorizationId ) ; return executeTransaction ( processor , request ) ; } @ Override public TransactionResponse doRevert ( String transactionId , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; requireOption ( options , "<STR_LIT>" ) ; ITransactionProcessor processor = buildTransactionProcessor ( ) ; RequestMessage request = buildRequestMessage ( REVERT , null , null , null ) ; request . setMerchantReferenceCode ( ( String ) options . get ( "<STR_LIT>" ) ) ; request . setPurchaseTotals ( buildPurchaseTotals ( ( Money ) options . get ( "<STR_LIT>" ) ) ) ; request . getCcAuthReversalService ( ) . setAuthRequestID ( transactionId ) ; return executeTransaction ( processor , request ) ; } @ Override public TransactionResponse doCredit ( Money money , String transactionId , Map < String , Object > options ) { requireOption ( options , "<STR_LIT>" ) ; ITransactionProcessor processor = buildTransactionProcessor ( ) ; RequestMessage request = buildRequestMessage ( CREDIT , money , null , null ) ; request . setMerchantReferenceCode ( ( String ) options . get ( "<STR_LIT>" ) ) ; request . getCcCreditService ( ) . setCaptureRequestID ( transactionId ) ; return executeTransaction ( processor , request ) ; } @ Override public TransactionResponse doRecurring ( Money money , CreditCard creditCard , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public TransactionResponse doStoreCreditCard ( CreditCard creditCard , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public TransactionResponse doEvictCreditCard ( String creditCardId , Map < String , Object > options ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean supportsPurchase ( ) { return true ; } @ Override public boolean supportsAuthorize ( ) { return true ; } @ Override public boolean supportsCapture ( ) { return true ; } @ Override public boolean supportsRevert ( ) { return true ; } @ Override public boolean supportsCredit ( ) { return true ; } @ Override public boolean supportsStoreCreditCard ( ) { return false ; } @ Override public boolean supportsEvictCreditCard ( ) { return false ; } @ Override public void setTest ( boolean test ) { this . test = test ; } private TransactionResponse executeTransaction ( ITransactionProcessor processor , RequestMessage request ) { ReplyMessage replyMessage = processor . runTransaction ( request ) ; return buildTransactionResponse ( replyMessage ) ; } private RequestMessage buildRequestMessage ( TransactionType transactionType , Money money , CreditCard creditCard , Order order ) { RequestMessage request = new RequestMessage ( ) ; transactionType . setServices ( request ) ; request . setMerchantID ( username ) ; if ( creditCard != null ) { request . setCard ( new CreditCardConverter ( creditCard ) . toCard ( ) ) ; } if ( money != null ) { request . setPurchaseTotals ( buildPurchaseTotals ( money ) ) ; } if ( order != null ) { request . setBillTo ( new AddressConverter ( order . getBillingAddress ( ) ) . toBillTo ( ) ) ; request . setShipTo ( new AddressConverter ( order . getShippingAddress ( ) ) . toShipTo ( ) ) ; } return request ; } private ITransactionProcessor buildTransactionProcessor ( ) { ITransactionProcessor processor = buildProcessor ( test ? TEST_HOSTNAME : HOSTNAME ) ; addSecurityProperties ( processor , username , transactionKey ) ; return processor ; } private TransactionResponse buildTransactionResponse ( ReplyMessage replyMessage ) { TransactionResponse transactionResponse = new TransactionResponse ( ) ; String message = replyMessage . getDecision ( ) ; if ( ! replyMessage . getMissingField ( ) . isEmpty ( ) ) { message += ( "<STR_LIT>" + replyMessage . getMissingField ( ) . toString ( ) ) ; } if ( ! replyMessage . getInvalidField ( ) . isEmpty ( ) ) { message += ( "<STR_LIT>" + replyMessage . getInvalidField ( ) . toString ( ) ) ; } transactionResponse . setMessage ( message ) ; transactionResponse . setCode ( replyMessage . getReasonCode ( ) . intValue ( ) ) ; transactionResponse . setReasonCode ( replyMessage . getReasonCode ( ) . intValue ( ) ) ; transactionResponse . setAuthorizationId ( replyMessage . getRequestID ( ) ) ; transactionResponse . setSuccessful ( <NUM_LIT:100> == replyMessage . getReasonCode ( ) . intValue ( ) ) ; return transactionResponse ; } private PurchaseTotals buildPurchaseTotals ( Money money ) { PurchaseTotals purchaseTotals = new PurchaseTotals ( ) ; purchaseTotals . setGrandTotalAmount ( format ( "<STR_LIT>" , money . getAmount ( ) ) ) ; purchaseTotals . setCurrency ( money . getCurrency ( ) . getCurrencyCode ( ) ) ; return purchaseTotals ; } private void addSecurityProperties ( ITransactionProcessor processor , String username , String transactionKey ) { Endpoint endpoint = buildEndpoint ( processor ) ; HashMap < String , Object > headers = new HashMap < String , Object > ( ) ; headers . put ( ACTION , USERNAME_TOKEN ) ; headers . put ( USER , username ) ; headers . put ( PASSWORD_TYPE , PW_TEXT ) ; headers . put ( PW_CALLBACK_REF , new ClientPasswordHandler ( transactionKey ) ) ; WSS4JOutInterceptor interceptor = new WSS4JOutInterceptor ( headers ) ; endpoint . getOutInterceptors ( ) . add ( interceptor ) ; } @ VisibleForTesting Endpoint buildEndpoint ( ITransactionProcessor processor ) { return ClientProxy . getClient ( processor ) . getEndpoint ( ) ; } @ VisibleForTesting ITransactionProcessor buildProcessor ( URL wsdlLocation ) { return new TransactionProcessor ( wsdlLocation ) . getPortXML ( ) ; } private static URL initUrl ( String url ) { try { return new URL ( url ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } </s>
<s> package org . payments4j . spi . cybersource ; import com . cybersource . schemas . transaction_data_1 . CCAuthReversalService ; import com . cybersource . schemas . transaction_data_1 . CCAuthService ; import com . cybersource . schemas . transaction_data_1 . CCCaptureService ; import com . cybersource . schemas . transaction_data_1 . CCCreditService ; import com . cybersource . schemas . transaction_data_1 . RequestMessage ; enum TransactionType { PURCHASE { @ Override public void setServices ( RequestMessage request ) { AUTHORIZE . setServices ( request ) ; CAPTURE . setServices ( request ) ; } } , AUTHORIZE { @ Override public void setServices ( RequestMessage request ) { request . setCcAuthService ( new CCAuthService ( ) ) ; request . getCcAuthService ( ) . setRun ( "<STR_LIT:true>" ) ; } } , CAPTURE { @ Override public void setServices ( RequestMessage request ) { request . setCcCaptureService ( new CCCaptureService ( ) ) ; request . getCcCaptureService ( ) . setRun ( "<STR_LIT:true>" ) ; } } , REVERT { @ Override public void setServices ( RequestMessage request ) { request . setCcAuthReversalService ( new CCAuthReversalService ( ) ) ; request . getCcAuthReversalService ( ) . setRun ( "<STR_LIT:true>" ) ; } } , CREDIT { @ Override public void setServices ( RequestMessage request ) { request . setCcCreditService ( new CCCreditService ( ) ) ; request . getCcCreditService ( ) . setRun ( "<STR_LIT:true>" ) ; } } ; public abstract void setServices ( RequestMessage request ) ; } </s>
<s> package org . payments4j . spi . cybersource ; import org . apache . ws . security . WSPasswordCallback ; import javax . security . auth . callback . Callback ; import javax . security . auth . callback . CallbackHandler ; import javax . security . auth . callback . UnsupportedCallbackException ; import java . io . IOException ; public class ClientPasswordHandler implements CallbackHandler { private String key ; public ClientPasswordHandler ( String key ) { this . key = key ; } @ Override public void handle ( Callback [ ] callbacks ) throws IOException , UnsupportedCallbackException { for ( Callback callback : callbacks ) { if ( callback instanceof WSPasswordCallback ) { WSPasswordCallback passwordCallback = ( WSPasswordCallback ) callback ; passwordCallback . setPassword ( key ) ; } } } } </s>
<s> package org . payments4j . spi . cybersource . converter ; import com . cybersource . schemas . transaction_data_1 . Card ; import com . google . common . collect . ImmutableMap ; import org . payments4j . model . CreditCard ; import java . math . BigInteger ; import java . util . Map ; import static org . payments4j . model . CreditCard . Type . AMERICAN_EXPRESS ; import static org . payments4j . model . CreditCard . Type . CARTE_BLANCHE ; import static org . payments4j . model . CreditCard . Type . DINERS_CLUB ; import static org . payments4j . model . CreditCard . Type . DISCOVER ; import static org . payments4j . model . CreditCard . Type . EN_ROUTE ; import static org . payments4j . model . CreditCard . Type . JCP ; import static org . payments4j . model . CreditCard . Type . LASER ; import static org . payments4j . model . CreditCard . Type . MAESTRO ; import static org . payments4j . model . CreditCard . Type . MASTER_CARD ; import static org . payments4j . model . CreditCard . Type . SOLO ; import static org . payments4j . model . CreditCard . Type . VISA ; public class CreditCardConverter { private static final Map < CreditCard . Type , String > CARD_TYPE_TO_CODE = new ImmutableMap . Builder < CreditCard . Type , String > ( ) . put ( VISA , "<STR_LIT>" ) . put ( MASTER_CARD , "<STR_LIT>" ) . put ( AMERICAN_EXPRESS , "<STR_LIT>" ) . put ( DISCOVER , "<STR_LIT>" ) . put ( DINERS_CLUB , "<STR_LIT>" ) . put ( CARTE_BLANCHE , "<STR_LIT>" ) . put ( JCP , "<STR_LIT>" ) . put ( EN_ROUTE , "<STR_LIT>" ) . put ( MAESTRO , "<STR_LIT>" ) . put ( SOLO , "<STR_LIT>" ) . put ( LASER , "<STR_LIT>" ) . build ( ) ; private CreditCard creditCard ; public CreditCardConverter ( CreditCard creditCard ) { this . creditCard = creditCard ; } public Card toCard ( ) { Card card = new Card ( ) ; card . setAccountNumber ( creditCard . getNumber ( ) ) ; card . setFullName ( creditCard . getFirstName ( ) + "<STR_LIT:U+0020>" + creditCard . getLastName ( ) ) ; card . setCardType ( CARD_TYPE_TO_CODE . get ( creditCard . getType ( ) ) ) ; card . setExpirationMonth ( new BigInteger ( creditCard . getMonth ( ) ) ) ; card . setExpirationYear ( new BigInteger ( creditCard . getYear ( ) ) ) ; card . setCvNumber ( creditCard . getSecurityCode ( ) ) ; return card ; } } </s>
<s> package org . payments4j . spi . cybersource . converter ; import com . cybersource . schemas . transaction_data_1 . BillTo ; import com . cybersource . schemas . transaction_data_1 . ShipTo ; import org . payments4j . model . Address ; public class AddressConverter { private Address address ; public AddressConverter ( Address address ) { this . address = address ; } public BillTo toBillTo ( ) { BillTo billTo = new BillTo ( ) ; billTo . setFirstName ( address . getFirstName ( ) ) ; billTo . setLastName ( address . getLastName ( ) ) ; billTo . setEmail ( address . getEmail ( ) ) ; billTo . setStreet1 ( address . getAddress1 ( ) ) ; billTo . setStreet2 ( address . getAddress2 ( ) ) ; billTo . setCity ( address . getCity ( ) ) ; billTo . setPostalCode ( address . getPostalCode ( ) ) ; billTo . setState ( address . getState ( ) ) ; billTo . setCountry ( address . getCountryIsoCode ( ) ) ; billTo . setPhoneNumber ( address . getPhone ( ) ) ; return billTo ; } public ShipTo toShipTo ( ) { ShipTo shipTo = new ShipTo ( ) ; shipTo . setFirstName ( address . getFirstName ( ) ) ; shipTo . setLastName ( address . getLastName ( ) ) ; shipTo . setEmail ( address . getEmail ( ) ) ; shipTo . setStreet1 ( address . getAddress1 ( ) ) ; shipTo . setStreet2 ( address . getAddress2 ( ) ) ; shipTo . setCity ( address . getCity ( ) ) ; shipTo . setPostalCode ( address . getPostalCode ( ) ) ; shipTo . setState ( address . getState ( ) ) ; shipTo . setCountry ( address . getCountryIsoCode ( ) ) ; shipTo . setPhoneNumber ( address . getPhone ( ) ) ; return shipTo ; } } </s>
<s> package org . payments4j . spi . cybersource ; import org . apache . ws . security . WSPasswordCallback ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import javax . security . auth . callback . Callback ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . verifyZeroInteractions ; @ RunWith ( MockitoJUnitRunner . class ) public class ClientPasswordHandlerTest { @ Mock private WSPasswordCallback mockPasswordCallback ; @ Mock private Callback mockOtherCallback ; @ Test public void testHandle ( ) throws Exception { ClientPasswordHandler handler = new ClientPasswordHandler ( "<STR_LIT>" ) ; handler . handle ( new Callback [ ] { mockPasswordCallback , mockOtherCallback } ) ; verify ( mockPasswordCallback ) . setPassword ( "<STR_LIT>" ) ; verifyZeroInteractions ( mockOtherCallback ) ; } } </s>
<s> package org . payments4j . spi . cybersource ; import com . cybersource . schemas . transaction_data . transactionprocessor . ITransactionProcessor ; import com . cybersource . schemas . transaction_data_1 . BillTo ; import com . cybersource . schemas . transaction_data_1 . Card ; import com . cybersource . schemas . transaction_data_1 . PurchaseTotals ; import com . cybersource . schemas . transaction_data_1 . ReplyMessage ; import com . cybersource . schemas . transaction_data_1 . RequestMessage ; import com . cybersource . schemas . transaction_data_1 . ShipTo ; import org . apache . cxf . endpoint . Endpoint ; import org . apache . cxf . interceptor . Interceptor ; import org . apache . cxf . message . Message ; import org . apache . cxf . ws . security . wss4j . WSS4JOutInterceptor ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . ArgumentCaptor ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import org . payments4j . core . TransactionResponse ; import org . payments4j . model . AddressBuilder ; import org . payments4j . model . CreditCard ; import org . payments4j . model . CreditCardBuilder ; import org . payments4j . model . Money ; import org . payments4j . model . MoneyBuilder ; import org . payments4j . model . Order ; import org . payments4j . model . OrderBuilder ; import java . math . BigInteger ; import java . net . URL ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Locale ; import java . util . Map ; import static org . apache . ws . security . WSConstants . PW_TEXT ; import static org . apache . ws . security . handler . WSHandlerConstants . ACTION ; import static org . apache . ws . security . handler . WSHandlerConstants . PASSWORD_TYPE ; import static org . apache . ws . security . handler . WSHandlerConstants . PW_CALLBACK_REF ; import static org . apache . ws . security . handler . WSHandlerConstants . USER ; import static org . apache . ws . security . handler . WSHandlerConstants . USERNAME_TOKEN ; import static org . fest . assertions . Assertions . assertThat ; import static org . fest . assertions . MapAssert . entry ; import static org . mockito . Matchers . isA ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import static org . payments4j . model . CreditCard . Type . MASTER_CARD ; @ RunWith ( MockitoJUnitRunner . class ) public class CybersourcePaymentGatewayTest { private static final String USERNAME = "<STR_LIT>" ; private static final String KEY = "<STR_LIT>" ; private static final String AUTHORIZATION_ID = "<STR_LIT>" ; private CybersourcePaymentGateway_ForTest gateway ; private Money money ; private CreditCard creditCard ; @ Mock private Endpoint mockEndpoint ; @ Mock private ITransactionProcessor mockTransactionProcessor ; private List < Interceptor < ? extends Message > > outInterceptors ; private HashMap < String , Object > options ; @ Before public void setUp ( ) throws Exception { gateway = new CybersourcePaymentGateway_ForTest ( USERNAME , KEY ) ; gateway . setTest ( true ) ; money = new MoneyBuilder ( ) . withAmount ( "<STR_LIT:10>" ) . withCurrency ( Locale . US ) . build ( ) ; creditCard = new CreditCardBuilder ( ) . withNumber ( "<STR_LIT>" ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withMonth ( "<STR_LIT>" ) . withYear ( "<STR_LIT>" ) . withType ( MASTER_CARD ) . withSecurityCode ( "<STR_LIT:123>" ) . build ( ) ; Order order = new OrderBuilder ( ) . withBillingAddress ( new AddressBuilder ( ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withEmail ( "<STR_LIT>" ) . withAddress1 ( "<STR_LIT>" ) . withAddress2 ( "<STR_LIT>" ) . withCity ( "<STR_LIT>" ) . withPostalCode ( "<STR_LIT>" ) . withState ( "<STR_LIT>" ) . withCountryIsoCode ( "<STR_LIT>" ) . build ( ) ) . withShippingAddress ( new AddressBuilder ( ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withEmail ( "<STR_LIT>" ) . withAddress1 ( "<STR_LIT>" ) . withAddress2 ( "<STR_LIT>" ) . withCity ( "<STR_LIT>" ) . withPostalCode ( "<STR_LIT>" ) . withState ( "<STR_LIT>" ) . withCountryIsoCode ( "<STR_LIT>" ) . build ( ) ) . build ( ) ; options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT:123>" ) ; options . put ( "<STR_LIT>" , order ) ; options . put ( "<STR_LIT>" , money ) ; TransactionResponse transactionResponse = new TransactionResponse ( ) ; transactionResponse . setCode ( <NUM_LIT:100> ) ; transactionResponse . setAuthorizationId ( "<STR_LIT:123>" ) ; transactionResponse . setReasonCode ( <NUM_LIT:100> ) ; transactionResponse . setMessage ( "<STR_LIT>" ) ; transactionResponse . setSuccessful ( true ) ; outInterceptors = new ArrayList < Interceptor < ? extends Message > > ( ) ; ReplyMessage replyMessage = new ReplyMessage ( ) ; replyMessage . setDecision ( "<STR_LIT>" ) ; replyMessage . setReasonCode ( new BigInteger ( "<STR_LIT>" ) ) ; replyMessage . setRequestID ( "<STR_LIT:123>" ) ; when ( mockTransactionProcessor . runTransaction ( isA ( RequestMessage . class ) ) ) . thenReturn ( replyMessage ) ; when ( mockEndpoint . getOutInterceptors ( ) ) . thenReturn ( outInterceptors ) ; } @ After public void tearDown ( ) throws Exception { assertThatSecurityValuesAreSet ( ) ; } @ Test public void testPurchase ( ) throws Exception { gateway . purchase ( money , creditCard , options ) ; RequestMessage requestMessage = captureRequestMessage ( ) ; assertThat ( requestMessage . getCcAuthService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThat ( requestMessage . getCcCaptureService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThatCardEquals ( requestMessage . getCard ( ) ) ; assertThatPurchaseTotalsEquals ( requestMessage . getPurchaseTotals ( ) ) ; } @ Test public void testAuthorize ( ) throws Exception { gateway . authorize ( money , creditCard , options ) ; RequestMessage requestMessage = captureRequestMessage ( ) ; assertThat ( requestMessage . getCcAuthService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThatCardEquals ( requestMessage . getCard ( ) ) ; assertThatPurchaseTotalsEquals ( requestMessage . getPurchaseTotals ( ) ) ; assertThatBillingAddressEquals ( requestMessage . getBillTo ( ) ) ; assertThatShippingAddressEquals ( requestMessage . getShipTo ( ) ) ; } @ Test public void testCapture ( ) throws Exception { gateway . capture ( money , AUTHORIZATION_ID , options ) ; RequestMessage requestMessage = captureRequestMessage ( ) ; assertThat ( requestMessage . getCcCaptureService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThatPurchaseTotalsEquals ( requestMessage . getPurchaseTotals ( ) ) ; } @ Test public void testRevert ( ) throws Exception { gateway . revert ( AUTHORIZATION_ID , options ) ; RequestMessage requestMessage = captureRequestMessage ( ) ; assertThat ( requestMessage . getCcAuthReversalService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThat ( requestMessage . getCcAuthReversalService ( ) . getAuthRequestID ( ) ) . isEqualTo ( AUTHORIZATION_ID ) ; assertThatPurchaseTotalsEquals ( requestMessage . getPurchaseTotals ( ) ) ; } @ Test public void testCredit ( ) throws Exception { gateway . credit ( money , AUTHORIZATION_ID , options ) ; RequestMessage requestMessage = captureRequestMessage ( ) ; assertThat ( requestMessage . getCcCreditService ( ) . getRun ( ) ) . isEqualTo ( "<STR_LIT:true>" ) ; assertThat ( requestMessage . getCcCreditService ( ) . getCaptureRequestID ( ) ) . isEqualTo ( AUTHORIZATION_ID ) ; assertThatPurchaseTotalsEquals ( requestMessage . getPurchaseTotals ( ) ) ; } private void assertThatBillingAddressEquals ( BillTo billTo ) { assertThat ( billTo . getFirstName ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getLastName ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getEmail ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getStreet1 ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getStreet2 ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getCity ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getPostalCode ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getState ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( billTo . getCountry ( ) ) . isEqualTo ( "<STR_LIT>" ) ; } private void assertThatShippingAddressEquals ( ShipTo shipTo ) { assertThat ( shipTo . getFirstName ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getLastName ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getEmail ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getStreet1 ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getStreet2 ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getCity ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getPostalCode ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getState ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( shipTo . getCountry ( ) ) . isEqualTo ( "<STR_LIT>" ) ; } private void assertThatSecurityValuesAreSet ( ) { Map < String , Object > interceptorProperties = ( ( WSS4JOutInterceptor ) outInterceptors . get ( <NUM_LIT:0> ) ) . getProperties ( ) ; assertThat ( interceptorProperties ) . includes ( entry ( ACTION , USERNAME_TOKEN ) , entry ( USER , USERNAME ) , entry ( PASSWORD_TYPE , PW_TEXT ) ) ; assertThat ( interceptorProperties . get ( PW_CALLBACK_REF ) ) . isInstanceOf ( ClientPasswordHandler . class ) ; } private RequestMessage captureRequestMessage ( ) { ArgumentCaptor < RequestMessage > captor = ArgumentCaptor . forClass ( RequestMessage . class ) ; verify ( mockTransactionProcessor ) . runTransaction ( captor . capture ( ) ) ; return captor . getValue ( ) ; } private void assertThatPurchaseTotalsEquals ( PurchaseTotals purchaseTotals ) { assertThat ( purchaseTotals . getCurrency ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( purchaseTotals . getGrandTotalAmount ( ) ) . isEqualTo ( "<STR_LIT>" ) ; } private void assertThatCardEquals ( Card card ) { assertThat ( card . getAccountNumber ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( card . getAccountNumber ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( card . getFullName ( ) ) . isEqualTo ( "<STR_LIT>" ) ; assertThat ( card . getExpirationMonth ( ) ) . isEqualTo ( new BigInteger ( "<STR_LIT>" ) ) ; assertThat ( card . getExpirationYear ( ) ) . isEqualTo ( new BigInteger ( "<STR_LIT>" ) ) ; assertThat ( card . getCvNumber ( ) ) . isEqualTo ( "<STR_LIT:123>" ) ; assertThat ( card . getCardType ( ) ) . isEqualTo ( "<STR_LIT>" ) ; } private class CybersourcePaymentGateway_ForTest extends CybersourcePaymentGateway { public CybersourcePaymentGateway_ForTest ( String username , String transactionKey ) { super ( username , transactionKey ) ; } @ Override ITransactionProcessor buildProcessor ( URL wsdlLocation ) { assertThat ( wsdlLocation ) . isEqualTo ( TEST_HOSTNAME ) ; return mockTransactionProcessor ; } @ Override Endpoint buildEndpoint ( ITransactionProcessor processor ) { return mockEndpoint ; } } } </s>
<s> package org . payments4j . spi . cybersource ; import org . junit . Before ; import org . payments4j . core . PaymentGateway ; import org . payments4j . model . AddressBuilder ; import org . payments4j . model . CreditCard ; import org . payments4j . model . Order ; import org . payments4j . model . OrderBuilder ; import org . payments4j . test . spi . AbstractBasePaymentGatewayIntegrationTest ; import java . util . HashMap ; import java . util . Map ; public class CybersourcePaymentGatewayIntegrationTest extends AbstractBasePaymentGatewayIntegrationTest { private Order order ; @ Override protected PaymentGateway buildGateway ( ) { CybersourcePaymentGateway gateway = new CybersourcePaymentGateway ( credentials . getProperty ( "<STR_LIT>" ) , credentials . getProperty ( "<STR_LIT>" ) ) ; gateway . setTest ( true ) ; return gateway ; } @ Before public void setUp ( ) throws Exception { super . setUp ( ) ; order = new OrderBuilder ( ) . withBillingAddress ( new AddressBuilder ( ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withEmail ( "<STR_LIT>" ) . withAddress1 ( "<STR_LIT>" ) . withAddress2 ( "<STR_LIT>" ) . withCity ( "<STR_LIT>" ) . withPostalCode ( "<STR_LIT>" ) . withState ( "<STR_LIT>" ) . withCountryIsoCode ( "<STR_LIT>" ) . build ( ) ) . withShippingAddress ( new AddressBuilder ( ) . withFirstName ( "<STR_LIT>" ) . withLastName ( "<STR_LIT>" ) . withEmail ( "<STR_LIT>" ) . withAddress1 ( "<STR_LIT>" ) . withAddress2 ( "<STR_LIT>" ) . withCity ( "<STR_LIT>" ) . withPostalCode ( "<STR_LIT>" ) . withState ( "<STR_LIT>" ) . withCountryIsoCode ( "<STR_LIT>" ) . build ( ) ) . build ( ) ; } @ Override protected Map < String , Object > getAuthOptions ( ) { HashMap < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT:123>" ) ; options . put ( "<STR_LIT>" , order ) ; return options ; } @ Override protected Map < String , Object > getCaptureOptions ( ) { HashMap < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; return options ; } @ Override protected Map < String , Object > getPurchaseOptions ( ) { HashMap < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; options . put ( "<STR_LIT>" , order ) ; return options ; } @ Override protected Map < String , Object > getCreditOptions ( ) { HashMap < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; return options ; } @ Override protected Map < String , Object > getRevertOptions ( ) { HashMap < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( "<STR_LIT>" , "<STR_LIT>" ) ; options . put ( "<STR_LIT>" , money ) ; return options ; } @ Override protected CreditCard getCreditCard ( ) { CreditCard creditCard = super . getCreditCard ( ) ; creditCard . setNumber ( "<STR_LIT>" ) ; return creditCard ; } } </s>
<s> package org . payments4j . examples ; import net . authorize . Environment ; import net . authorize . Merchant ; import net . authorize . aim . Result ; import net . authorize . TransactionType ; import net . authorize . aim . Transaction ; import net . authorize . data . creditcard . CreditCard ; import java . math . BigDecimal ; public class AuthorizeNetClientExample { private static final String API_LOGIN_ID = "<STR_LIT>" ; private static final String TRANSACTION_KEY = "<STR_LIT>" ; public static void main ( String [ ] args ) { Merchant merchant = Merchant . createMerchant ( Environment . SANDBOX , API_LOGIN_ID , TRANSACTION_KEY ) ; CreditCard creditCard = CreditCard . createCreditCard ( ) ; creditCard . setCreditCardNumber ( "<STR_LIT>" ) ; creditCard . setExpirationMonth ( "<STR_LIT>" ) ; creditCard . setExpirationYear ( "<STR_LIT>" ) ; Transaction authCaptureTransaction = merchant . createAIMTransaction ( TransactionType . AUTH_CAPTURE , new BigDecimal ( <NUM_LIT> ) ) ; authCaptureTransaction . setCreditCard ( creditCard ) ; Result < Transaction > result = ( Result < Transaction > ) merchant . postTransaction ( authCaptureTransaction ) ; System . out . println ( result . getTarget ( ) . getTransactionId ( ) ) ; System . out . println ( "<STR_LIT>" + result . getResponseCode ( ) ) ; System . out . println ( "<STR_LIT>" + result . getResponseText ( ) ) ; System . out . println ( "<STR_LIT>" + result . getReasonResponseCode ( ) ) ; } } </s>
<s> package org . payments4j . examples ; import paypal . payflow . * ; public class PayFlowClientExample { private static final String MERCHANT_USERNAME = "<STR_LIT>" ; private static final String MERCHANT_PASSWORD = "<STR_LIT>" ; private static final String PARTNER = "<STR_LIT>" ; public static void main ( String [ ] args ) { Invoice invoice = new Invoice ( ) ; invoice . setAmt ( new Currency ( <NUM_LIT> ) ) ; invoice . setPoNum ( "<STR_LIT>" ) ; invoice . setInvNum ( "<STR_LIT>" ) ; invoice . setBillTo ( buildBuildTo ( ) ) ; invoice . addLineItem ( buildLineItem ( "<STR_LIT>" ) ) ; invoice . addLineItem ( buildLineItem ( "<STR_LIT>" ) ) ; CardTender card = buildCardTender ( ) ; UserInfo user = new UserInfo ( MERCHANT_USERNAME , MERCHANT_USERNAME , PARTNER , MERCHANT_PASSWORD ) ; PayflowConnectionData connection = new PayflowConnectionData ( "<STR_LIT>" , <NUM_LIT> ) ; AuthorizationTransaction trans = new AuthorizationTransaction ( user , connection , invoice , card , PayflowUtility . getRequestId ( ) ) ; Response resp = trans . submitTransaction ( ) ; TransactionResponse transactionResponse = resp . getTransactionResponse ( ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getResult ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getPnref ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getRespMsg ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getAuthCode ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getAvsAddr ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getAvsZip ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getIavs ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getCvv2Match ( ) ) ; System . out . println ( "<STR_LIT>" + transactionResponse . getDuplicate ( ) ) ; FraudResponse fraudResp = resp . getFraudResponse ( ) ; System . out . println ( "<STR_LIT>" + fraudResp . getPreFpsMsg ( ) ) ; System . out . println ( "<STR_LIT>" + fraudResp . getPostFpsMsg ( ) ) ; } private static LineItem buildLineItem ( String description ) { LineItem lineItem = new LineItem ( ) ; lineItem . setDesc ( description ) ; return lineItem ; } private static BillTo buildBuildTo ( ) { BillTo bill = new BillTo ( ) ; bill . setStreet ( "<STR_LIT>" ) ; bill . setZip ( "<STR_LIT>" ) ; return bill ; } private static CardTender buildCardTender ( ) { CreditCard cc = new CreditCard ( "<STR_LIT>" , "<STR_LIT>" ) ; cc . setCvv2 ( "<STR_LIT:123>" ) ; return new CardTender ( cc ) ; } } </s>
<s> package org . payments4j . examples ; import com . cybersource . schemas . transaction_data . transactionprocessor . ITransactionProcessor ; import com . cybersource . schemas . transaction_data . transactionprocessor . TransactionProcessor ; import com . cybersource . schemas . transaction_data_1 . BillTo ; import com . cybersource . schemas . transaction_data_1 . CCAuthService ; import com . cybersource . schemas . transaction_data_1 . Card ; import com . cybersource . schemas . transaction_data_1 . Item ; import com . cybersource . schemas . transaction_data_1 . PurchaseTotals ; import com . cybersource . schemas . transaction_data_1 . ReplyMessage ; import com . cybersource . schemas . transaction_data_1 . RequestMessage ; import org . apache . cxf . endpoint . Client ; import org . apache . cxf . endpoint . Endpoint ; import org . apache . cxf . frontend . ClientProxy ; import org . apache . cxf . version . Version ; import org . apache . cxf . ws . security . wss4j . WSS4JOutInterceptor ; import org . apache . ws . security . WSConstants ; import org . apache . ws . security . WSPasswordCallback ; import org . apache . ws . security . handler . WSHandlerConstants ; import javax . security . auth . callback . Callback ; import javax . security . auth . callback . CallbackHandler ; import javax . security . auth . callback . UnsupportedCallbackException ; import java . io . IOException ; import java . math . BigInteger ; import java . net . MalformedURLException ; import java . net . URL ; import java . rmi . RemoteException ; import java . util . HashMap ; public class CybersourceClientExample { private static final String MERCHANT_ID = "<STR_LIT>" ; private static final String MERCHANT_KEY = "<STR_LIT>" ; private static final String SERVER_URL = "<STR_LIT>" ; private static final String CLIENT_LIB_VERSION = Version . getCompleteVersionString ( ) + "<STR_LIT>" ; private static final String CLIENT_LIBRARY = "<STR_LIT>" ; private static final String CLIENT_ENV = System . getProperty ( "<STR_LIT>" ) + "<STR_LIT:/>" + System . getProperty ( "<STR_LIT>" ) + "<STR_LIT:/>" + System . getProperty ( "<STR_LIT>" ) + "<STR_LIT:/>" + System . getProperty ( "<STR_LIT>" ) ; public static void main ( String [ ] args ) throws RemoteException , MalformedURLException { RequestMessage request = new RequestMessage ( ) ; addClientLibraryInfo ( request ) ; request . setMerchantID ( MERCHANT_ID ) ; request . setMerchantReferenceCode ( "<STR_LIT>" ) ; request . setCcAuthService ( new CCAuthService ( ) ) ; request . getCcAuthService ( ) . setRun ( "<STR_LIT:true>" ) ; request . setBillTo ( buildBillTo ( ) ) ; request . setCard ( buildCard ( ) ) ; request . setPurchaseTotals ( buildPurchaseTotals ( ) ) ; request . getItem ( ) . add ( buildItem ( "<STR_LIT:0>" , "<STR_LIT>" , "<STR_LIT:2>" ) ) ; request . getItem ( ) . add ( buildItem ( "<STR_LIT:1>" , "<STR_LIT>" , "<STR_LIT:1>" ) ) ; ITransactionProcessor processor = new TransactionProcessor ( new URL ( SERVER_URL ) ) . getPortXML ( ) ; addSecurityValues ( processor ) ; ReplyMessage reply = processor . runTransaction ( request ) ; System . out . println ( "<STR_LIT>" + reply . getDecision ( ) ) ; System . out . println ( "<STR_LIT>" + reply . getReasonCode ( ) ) ; System . out . println ( "<STR_LIT>" + reply . getRequestID ( ) ) ; System . out . println ( "<STR_LIT>" + reply . getRequestToken ( ) ) ; System . out . println ( "<STR_LIT>" + reply . getCcAuthReply ( ) . getReasonCode ( ) ) ; } private static void addClientLibraryInfo ( RequestMessage request ) { request . setClientLibrary ( CLIENT_LIBRARY ) ; request . setClientLibraryVersion ( CLIENT_LIB_VERSION ) ; request . setClientEnvironment ( CLIENT_ENV ) ; } private static Item buildItem ( String id , String unitPrice , String quantity ) { Item item = new Item ( ) ; item . setId ( new BigInteger ( id ) ) ; item . setUnitPrice ( unitPrice ) ; item . setQuantity ( new BigInteger ( quantity ) ) ; return item ; } private static PurchaseTotals buildPurchaseTotals ( ) { PurchaseTotals purchaseTotals = new PurchaseTotals ( ) ; purchaseTotals . setCurrency ( "<STR_LIT>" ) ; purchaseTotals . setGrandTotalAmount ( "<STR_LIT>" ) ; return purchaseTotals ; } private static Card buildCard ( ) { Card card = new Card ( ) ; card . setAccountNumber ( "<STR_LIT>" ) ; card . setExpirationMonth ( new BigInteger ( "<STR_LIT>" ) ) ; card . setExpirationYear ( new BigInteger ( "<STR_LIT>" ) ) ; return card ; } private static BillTo buildBillTo ( ) { BillTo billTo = new BillTo ( ) ; billTo . setFirstName ( "<STR_LIT>" ) ; billTo . setLastName ( "<STR_LIT>" ) ; billTo . setStreet1 ( "<STR_LIT>" ) ; billTo . setCity ( "<STR_LIT>" ) ; billTo . setState ( "<STR_LIT>" ) ; billTo . setPostalCode ( "<STR_LIT>" ) ; billTo . setCountry ( "<STR_LIT>" ) ; billTo . setEmail ( "<STR_LIT>" ) ; billTo . setIpAddress ( "<STR_LIT>" ) ; return billTo ; } private static void addSecurityValues ( ITransactionProcessor processor ) { Client client = ClientProxy . getClient ( processor ) ; Endpoint endpoint = client . getEndpoint ( ) ; HashMap < String , Object > outHeaders = new HashMap < String , Object > ( ) ; outHeaders . put ( WSHandlerConstants . ACTION , WSHandlerConstants . USERNAME_TOKEN ) ; outHeaders . put ( WSHandlerConstants . USER , MERCHANT_ID ) ; outHeaders . put ( WSHandlerConstants . PASSWORD_TYPE , WSConstants . PW_TEXT ) ; outHeaders . put ( WSHandlerConstants . PW_CALLBACK_CLASS , ClientPasswordHandler . class . getName ( ) ) ; WSS4JOutInterceptor interceptor = new WSS4JOutInterceptor ( outHeaders ) ; endpoint . getOutInterceptors ( ) . add ( interceptor ) ; } public static class ClientPasswordHandler implements CallbackHandler { @ Override public void handle ( Callback [ ] callbacks ) throws IOException , UnsupportedCallbackException { for ( Callback callback : callbacks ) { if ( callback instanceof WSPasswordCallback ) { WSPasswordCallback passwordCallback = ( WSPasswordCallback ) callback ; passwordCallback . setPassword ( MERCHANT_KEY ) ; } } } } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; import java . io . IOException ; @ Buildable public class CheckedExceptionBean { public CheckedExceptionBean ( ) throws IOException { throw new IOException ( ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; import info . piwai . buildergen . api . Mandatory ; @ Buildable public class MandatoryBean { private final int intField ; private final String stringField ; private final Integer integerField ; private final SomeObject someObjectField ; MandatoryBean ( int intField , @ Mandatory String stringField , Integer integerField , @ Mandatory SomeObject someObjectField ) { this . intField = intField ; this . stringField = stringField ; this . integerField = integerField ; this . someObjectField = someObjectField ; } public int getIntField ( ) { return intField ; } public String getStringField ( ) { return stringField ; } public Integer getIntegerField ( ) { return integerField ; } public SomeObject getSomeObjectField ( ) { return someObjectField ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Builder ; import info . piwai . buildergen . api . UncheckedBuilder ; import java . util . ArrayList ; import java . util . List ; public class BuilderInterfaceExample { public < T > List < T > buildMultipleInstances ( Builder < T > builder , int numberOfInstances ) throws Exception { List < T > instances = new ArrayList < T > ( ) ; for ( int i = <NUM_LIT:0> ; i < numberOfInstances ; i ++ ) { instances . add ( builder . build ( ) ) ; } return instances ; } public < T > List < T > buildMultipleInstances ( UncheckedBuilder < T > builder , int numberOfInstances ) { List < T > instances = new ArrayList < T > ( ) ; for ( int i = <NUM_LIT:0> ; i < numberOfInstances ; i ++ ) { instances . add ( builder . build ( ) ) ; } return instances ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Build ; import info . piwai . buildergen . api . Buildable ; @ Buildable public class AnnotatedConstructorBean { private String field1 ; private String field2 ; public AnnotatedConstructorBean ( String field1 , String field2 ) { this . field1 = field1 ; this . field2 = field2 ; } @ Build public AnnotatedConstructorBean ( String field1 ) { this . field1 = field1 ; field2 = "<STR_LIT>" ; } public AnnotatedConstructorBean ( ) { } public String getField1 ( ) { return field1 ; } public String getField2 ( ) { return field2 ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; @ Buildable public class FieldsBean { private final int intField ; private final String stringField ; private final Integer integerField ; private final SomeObject someObjectField ; FieldsBean ( int intField , String stringField , Integer integerField , SomeObject someObjectField ) { this . intField = intField ; this . stringField = stringField ; this . integerField = integerField ; this . someObjectField = someObjectField ; } public int getIntField ( ) { return intField ; } public String getStringField ( ) { return stringField ; } public Integer getIntegerField ( ) { return integerField ; } public SomeObject getSomeObjectField ( ) { return someObjectField ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; @ Buildable public class Person { private final int age ; private final String name ; Person ( String name , int age ) { this . name = name ; this . age = age ; } public int getAge ( ) { return age ; } public String getName ( ) { return name ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; @ Buildable public class SimpleBean { } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; @ Buildable ( "<STR_LIT>" ) public class CustomNameBean { public static CustomNameBean factoryUsage ( ) { CustomNameBeanFactory factory = CustomNameBeanFactory . create ( ) ; return factory . build ( ) ; } } </s>
<s> package info . piwai . buildergen . bean ; public class SomeObject { } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . api . Buildable ; @ Buildable public class UncheckedExceptionBean { public UncheckedExceptionBean ( ) throws IllegalStateException { throw new IllegalArgumentException ( ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import static org . junit . Assert . assertSame ; import info . piwai . buildergen . bean . FieldsBean ; import info . piwai . buildergen . bean . FieldsBeanBuilder ; import info . piwai . buildergen . bean . SomeObject ; import org . junit . Test ; public class FieldsBeanTest { @ Test public void fieldsAssignment ( ) { Integer integerField = <NUM_LIT> ; int intField = <NUM_LIT> ; String stringField = "<STR_LIT>" ; SomeObject someObjectField = new SomeObject ( ) ; FieldsBean fieldsBean = FieldsBeanBuilder . create ( ) . integerField ( integerField ) . intField ( intField ) . stringField ( stringField ) . someObjectField ( someObjectField ) . build ( ) ; assertSame ( integerField , fieldsBean . getIntegerField ( ) ) ; assertSame ( intField , fieldsBean . getIntField ( ) ) ; assertSame ( stringField , fieldsBean . getStringField ( ) ) ; assertSame ( someObjectField , fieldsBean . getSomeObjectField ( ) ) ; } @ Test public void fieldsReassignment ( ) { Integer integerField1 = <NUM_LIT> ; Integer integerField2 = <NUM_LIT> ; FieldsBean fieldsBean = FieldsBeanBuilder . create ( ) . integerField ( integerField1 ) . integerField ( integerField2 ) . build ( ) ; assertSame ( integerField2 , fieldsBean . getIntegerField ( ) ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . bean . AnnotatedConstructorBean ; import info . piwai . buildergen . bean . AnnotatedConstructorBeanBuilder ; import org . junit . Assert ; import org . junit . Test ; public class AnnotatedConstructorBeanTest { @ Test public void annotatedConstructorIsUsed ( ) { AnnotatedConstructorBean bean = AnnotatedConstructorBeanBuilder . create ( ) . field1 ( "<STR_LIT:hello>" ) . build ( ) ; Assert . assertEquals ( "<STR_LIT:hello>" , bean . getField1 ( ) ) ; Assert . assertEquals ( "<STR_LIT>" , bean . getField2 ( ) ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . bean . SimpleBean ; import info . piwai . buildergen . bean . SimpleBeanBuilder ; import junit . framework . Assert ; import org . junit . Test ; public class SimpleBeanTest { @ Test public void newInstanceNotNull ( ) { Assert . assertNotNull ( SimpleBeanBuilder . create ( ) . build ( ) ) ; } @ Test public void notSameInstanceTwice ( ) { SimpleBeanBuilder builder = SimpleBeanBuilder . create ( ) ; SimpleBean bean1 = builder . build ( ) ; SimpleBean bean2 = builder . build ( ) ; Assert . assertNotSame ( bean1 , bean2 ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . bean . CheckedExceptionBeanBuilder ; import java . io . IOException ; import org . junit . Test ; public class CheckedExceptionBeanTest { @ Test ( expected = IOException . class ) public void throwsConstructorException ( ) throws IOException { CheckedExceptionBeanBuilder . create ( ) . build ( ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import info . piwai . buildergen . bean . UncheckedExceptionBeanBuilder ; import org . junit . Test ; public class UncheckedExceptionBeanTest { @ Test ( expected = IllegalArgumentException . class ) public void throwsConstructorException ( ) { UncheckedExceptionBeanBuilder . create ( ) . build ( ) ; } } </s>
<s> package info . piwai . buildergen . bean ; import static org . junit . Assert . assertSame ; import org . junit . Test ; public class MandatoryBeanTest { @ Test public void mandatoryParametersAssignmentThroughtCreate ( ) { String stringField = "<STR_LIT>" ; SomeObject someObjectField = new SomeObject ( ) ; MandatoryBean bean = MandatoryBeanBuilder . create ( stringField , someObjectField ) . build ( ) ; assertSame ( stringField , bean . getStringField ( ) ) ; assertSame ( someObjectField , bean . getSomeObjectField ( ) ) ; } @ Test public void mandatoryParametersAssignmentThroughtConstructor ( ) { String stringField = "<STR_LIT>" ; SomeObject someObjectField = new SomeObject ( ) ; MandatoryBean bean = new MandatoryBeanBuilder ( stringField , someObjectField ) . build ( ) ; assertSame ( stringField , bean . getStringField ( ) ) ; assertSame ( someObjectField , bean . getSomeObjectField ( ) ) ; } @ Test public void mandatoryParametersReassignment ( ) { String stringField1 = "<STR_LIT>" ; String stringField2 = "<STR_LIT>" ; SomeObject someObjectField = new SomeObject ( ) ; MandatoryBeanBuilder builder = MandatoryBeanBuilder . create ( stringField1 , someObjectField ) ; builder . stringField ( stringField2 ) ; MandatoryBean bean = builder . build ( ) ; assertSame ( stringField2 , bean . getStringField ( ) ) ; } } </s>
<s> package info . piwai . buildergen . generation ; import static org . junit . Assert . assertSame ; import static org . mockito . Matchers . anyString ; import static org . mockito . Mockito . doThrow ; import static org . mockito . Mockito . mock ; import static org . mockito . Mockito . times ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import java . io . IOException ; import java . io . OutputStream ; import javax . annotation . processing . Filer ; import javax . tools . JavaFileObject ; import org . junit . Test ; import com . sun . codemodel . JCodeModel ; import com . sun . codemodel . JPackage ; public class SourceCodeWriterTest { @ Test public void usesFilerToOpenStream ( ) throws IOException { Filer filer = mock ( Filer . class ) ; JavaFileObject fileObject = mock ( JavaFileObject . class ) ; when ( filer . createSourceFile ( anyString ( ) ) ) . thenReturn ( fileObject ) ; OutputStream expectedOS = mock ( OutputStream . class ) ; when ( fileObject . openOutputStream ( ) ) . thenReturn ( expectedOS ) ; SourceCodeWriter sourceCodeWriter = new SourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; OutputStream resultingOS = sourceCodeWriter . openBinary ( jPackage , "<STR_LIT>" ) ; assertSame ( expectedOS , resultingOS ) ; } @ Test public void doesNotCallOutputStreamCloseMethod ( ) throws IOException { Filer filer = mock ( Filer . class ) ; JavaFileObject fileObject = mock ( JavaFileObject . class ) ; when ( filer . createSourceFile ( anyString ( ) ) ) . thenReturn ( fileObject ) ; OutputStream expectedOS = mock ( OutputStream . class ) ; when ( fileObject . openOutputStream ( ) ) . thenReturn ( expectedOS ) ; SourceCodeWriter sourceCodeWriter = new SourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; sourceCodeWriter . openBinary ( jPackage , "<STR_LIT>" ) ; doThrow ( new RuntimeException ( "<STR_LIT>" ) ) . when ( expectedOS ) . close ( ) ; sourceCodeWriter . close ( ) ; } @ Test public void multipleCallsAreDelegatedToFiler ( ) throws IOException { Filer filer = mock ( Filer . class ) ; JavaFileObject fileObject = mock ( JavaFileObject . class ) ; when ( filer . createSourceFile ( anyString ( ) ) ) . thenReturn ( fileObject ) ; SourceCodeWriter sourceCodeWriter = new SourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; sourceCodeWriter . openBinary ( jPackage , "<STR_LIT>" ) ; sourceCodeWriter . openBinary ( jPackage , "<STR_LIT>" ) ; verify ( filer , times ( <NUM_LIT:2> ) ) . createSourceFile ( anyString ( ) ) ; } } </s>
<s> package info . piwai . buildergen . generation ; import static org . junit . Assert . assertSame ; import static org . mockito . Matchers . anyString ; import static org . mockito . Mockito . doThrow ; import static org . mockito . Mockito . mock ; import static org . mockito . Mockito . times ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import java . io . IOException ; import java . io . OutputStream ; import javax . annotation . processing . Filer ; import javax . tools . FileObject ; import javax . tools . JavaFileManager . Location ; import org . junit . Test ; import org . mockito . Mockito ; import com . sun . codemodel . JCodeModel ; import com . sun . codemodel . JPackage ; public class ResourceCodeWriterTest { @ Test public void usesFilerToOpenStream ( ) throws IOException { Filer filer = mock ( Filer . class ) ; FileObject fileObject = mock ( FileObject . class ) ; when ( filer . createResource ( Mockito . < Location > any ( ) , anyString ( ) , anyString ( ) ) ) . thenReturn ( fileObject ) ; OutputStream expectedOS = mock ( OutputStream . class ) ; when ( fileObject . openOutputStream ( ) ) . thenReturn ( expectedOS ) ; ResourceCodeWriter resourceCodeWriter = new ResourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; OutputStream resultingOS = resourceCodeWriter . openBinary ( jPackage , null ) ; assertSame ( expectedOS , resultingOS ) ; } @ Test public void doesNotCallOutputStreamCloseMethod ( ) throws IOException { Filer filer = mock ( Filer . class ) ; FileObject fileObject = mock ( FileObject . class ) ; when ( filer . createResource ( Mockito . < Location > any ( ) , anyString ( ) , anyString ( ) ) ) . thenReturn ( fileObject ) ; OutputStream expectedOS = mock ( OutputStream . class ) ; when ( fileObject . openOutputStream ( ) ) . thenReturn ( expectedOS ) ; ResourceCodeWriter resourceCodeWriter = new ResourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; resourceCodeWriter . openBinary ( jPackage , null ) ; doThrow ( new RuntimeException ( "<STR_LIT>" ) ) . when ( expectedOS ) . close ( ) ; resourceCodeWriter . close ( ) ; } @ Test public void multipleCallsAreDelegatedToFiler ( ) throws IOException { Filer filer = mock ( Filer . class ) ; FileObject fileObject = mock ( FileObject . class ) ; when ( filer . createResource ( Mockito . < Location > any ( ) , anyString ( ) , anyString ( ) ) ) . thenReturn ( fileObject ) ; ResourceCodeWriter resourceCodeWriter = new ResourceCodeWriter ( filer ) ; JPackage jPackage = new JCodeModel ( ) . _package ( "<STR_LIT>" ) ; resourceCodeWriter . openBinary ( jPackage , null ) ; resourceCodeWriter . openBinary ( jPackage , null ) ; verify ( filer , times ( <NUM_LIT:2> ) ) . createResource ( Mockito . < Location > any ( ) , anyString ( ) , anyString ( ) ) ; } } </s>
<s> package info . piwai . buildergen . validation ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import org . junit . Test ; public class IsValidTest { @ Test public void initialStateIsValid ( ) { IsValid valid = new IsValid ( ) ; assertTrue ( valid . isValid ( ) ) ; } @ Test public void invalidateInvalidates ( ) { IsValid valid = new IsValid ( ) ; valid . invalidate ( ) ; assertFalse ( valid . isValid ( ) ) ; } @ Test public void doubleInvalidateInvalidates ( ) { IsValid valid = new IsValid ( ) ; valid . invalidate ( ) ; valid . invalidate ( ) ; assertFalse ( valid . isValid ( ) ) ; } } </s>
<s> package info . piwai . buildergen . validation ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import static org . mockito . Matchers . any ; import static org . mockito . Matchers . anyString ; import static org . mockito . Mockito . RETURNS_DEEP_STUBS ; import static org . mockito . Mockito . mock ; import static org . mockito . Mockito . never ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import info . piwai . buildergen . api . Buildable ; import info . piwai . buildergen . helper . ElementHelper ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import javax . annotation . processing . Messager ; import javax . annotation . processing . ProcessingEnvironment ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . AnnotationValue ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . Name ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . tools . Diagnostic . Kind ; import org . junit . Before ; import org . junit . Test ; public class BuildableValidatorTest { private ProcessingEnvironment processingEnv ; private ElementHelper elementHelper ; private BuildableValidator buildableValidator ; private TypeElement element ; private Element enclosingElement ; private ExecutableElement constructor ; private Iterator < ExecutableElement > iterator ; private Buildable buildableAnnotation ; private Messager messager ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) @ Before public void setup ( ) { processingEnv = mock ( ProcessingEnvironment . class ) ; messager = mock ( Messager . class ) ; when ( processingEnv . getMessager ( ) ) . thenReturn ( messager ) ; elementHelper = mock ( ElementHelper . class ) ; constructor = mock ( ExecutableElement . class ) ; when ( constructor . getThrownTypes ( ) ) . thenReturn ( new ArrayList ( ) ) ; Set < ExecutableElement > constructors = mock ( Set . class , RETURNS_DEEP_STUBS ) ; when ( constructors . size ( ) ) . thenReturn ( <NUM_LIT:1> ) ; iterator = mock ( Iterator . class ) ; when ( iterator . next ( ) ) . thenReturn ( constructor ) ; when ( constructors . iterator ( ) ) . thenReturn ( iterator ) ; when ( elementHelper . findAccessibleConstructors ( any ( TypeElement . class ) ) ) . thenReturn ( constructors ) ; buildableValidator = new BuildableValidator ( processingEnv , elementHelper ) ; createMockValidTypeElement ( ) ; } @ SuppressWarnings ( { "<STR_LIT:unchecked>" , "<STR_LIT:rawtypes>" } ) private void createMockValidTypeElement ( ) { element = mock ( TypeElement . class ) ; when ( element . getKind ( ) ) . thenReturn ( ElementKind . CLASS ) ; enclosingElement = mock ( Element . class ) ; when ( element . getEnclosingElement ( ) ) . thenReturn ( enclosingElement ) ; when ( enclosingElement . getKind ( ) ) . thenReturn ( ElementKind . PACKAGE ) ; Set < Modifier > modifiers = mock ( Set . class ) ; when ( enclosingElement . getModifiers ( ) ) . thenReturn ( modifiers ) ; when ( modifiers . contains ( Modifier . ABSTRACT ) ) . thenReturn ( true ) ; buildableAnnotation = mock ( Buildable . class ) ; when ( buildableAnnotation . value ( ) ) . thenReturn ( "<STR_LIT>" ) ; when ( element . getAnnotation ( Buildable . class ) ) . thenReturn ( buildableAnnotation ) ; AnnotationMirror annotationMirror = mock ( AnnotationMirror . class ) ; ArrayList annotationMirrors = new ArrayList ( ) ; annotationMirrors . add ( annotationMirror ) ; when ( element . getAnnotationMirrors ( ) ) . thenReturn ( annotationMirrors ) ; DeclaredType annotationMirrorType = mock ( DeclaredType . class ) ; when ( annotationMirror . getAnnotationType ( ) ) . thenReturn ( annotationMirrorType ) ; TypeElement annotationMirrorElement = mock ( TypeElement . class ) ; when ( annotationMirrorType . asElement ( ) ) . thenReturn ( annotationMirrorElement ) ; Name annotationMirrorName = mock ( Name . class ) ; when ( annotationMirrorElement . getQualifiedName ( ) ) . thenReturn ( annotationMirrorName ) ; when ( annotationMirrorName . toString ( ) ) . thenReturn ( Buildable . class . getName ( ) ) ; Map annotationMirrorElementValues = new HashMap ( ) ; AnnotationValue annotationValue = mock ( AnnotationValue . class ) ; annotationMirrorElementValues . put ( mock ( ExecutableElement . class ) , annotationValue ) ; when ( annotationMirror . getElementValues ( ) ) . thenReturn ( annotationMirrorElementValues ) ; } @ Test public void validTypeElementIsValid ( ) { boolean valid = buildableValidator . validate ( element ) ; verify ( messager , never ( ) ) . printMessage ( any ( Kind . class ) , anyString ( ) ) ; verify ( messager , never ( ) ) . printMessage ( any ( Kind . class ) , anyString ( ) , any ( Element . class ) ) ; verify ( messager , never ( ) ) . printMessage ( any ( Kind . class ) , anyString ( ) , any ( Element . class ) , any ( AnnotationMirror . class ) ) ; verify ( messager , never ( ) ) . printMessage ( any ( Kind . class ) , anyString ( ) , any ( Element . class ) , any ( AnnotationMirror . class ) , any ( AnnotationValue . class ) ) ; assertTrue ( valid ) ; } @ Test public void emptyCustomBuilderNameIsNotValid ( ) { when ( buildableAnnotation . value ( ) ) . thenReturn ( "<STR_LIT>" ) ; boolean valid = buildableValidator . validate ( element ) ; verify ( messager ) . printMessage ( any ( Kind . class ) , anyString ( ) , any ( Element . class ) , any ( AnnotationMirror . class ) , any ( AnnotationValue . class ) ) ; assertFalse ( valid ) ; } } </s>
<s> package info . piwai . buildergen . processing ; import java . lang . annotation . Annotation ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import javax . annotation . processing . AbstractProcessor ; import javax . annotation . processing . Processor ; import javax . annotation . processing . SupportedAnnotationTypes ; import javax . tools . Diagnostic ; public abstract class AnnotatedAbstractProcessor extends AbstractProcessor { public Set < String > getSupportedAnnotationTypes ( ) { SupportedAnnotationClasses sac = this . getClass ( ) . getAnnotation ( SupportedAnnotationClasses . class ) ; if ( sac == null ) { if ( isInitialized ( ) ) processingEnv . getMessager ( ) . printMessage ( Diagnostic . Kind . WARNING , "<STR_LIT>" + SupportedAnnotationClasses . class . getSimpleName ( ) + "<STR_LIT>" + "<STR_LIT>" + this . getClass ( ) . getName ( ) + "<STR_LIT>" ) ; return super . getSupportedAnnotationTypes ( ) ; } else return arrayToSet ( sac . value ( ) ) ; } private static Set < String > arrayToSet ( Class < ? extends Annotation > [ ] array ) { assert array != null ; Set < String > set = new HashSet < String > ( array . length ) ; for ( Class < ? extends Annotation > c : array ) { set . add ( c . getName ( ) ) ; } return Collections . unmodifiableSet ( set ) ; } } </s>
<s> package info . piwai . buildergen . processing ; import info . piwai . buildergen . api . Buildable ; import info . piwai . buildergen . api . Builder ; import info . piwai . buildergen . generation . SourceGenerator ; import info . piwai . buildergen . helper . ElementHelper ; import info . piwai . buildergen . modeling . ModelBuilder ; import info . piwai . buildergen . validation . BuildableValidator ; import java . io . IOException ; import java . util . HashSet ; import java . util . Set ; import javax . annotation . processing . Filer ; import javax . annotation . processing . Messager ; import javax . annotation . processing . RoundEnvironment ; import javax . annotation . processing . SupportedSourceVersion ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . Element ; import javax . lang . model . element . TypeElement ; import javax . tools . Diagnostic ; import javax . tools . Diagnostic . Kind ; import com . sun . codemodel . JClassAlreadyExistsException ; import com . sun . codemodel . JCodeModel ; @ SupportedAnnotationClasses ( Buildable . class ) @ SupportedSourceVersion ( SourceVersion . RELEASE_6 ) public class BuilderGenProcessor extends AnnotatedAbstractProcessor { @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { try { processThrowing ( roundEnv ) ; } catch ( Exception e ) { printError ( annotations , roundEnv , e ) ; } return true ; } private void processThrowing ( RoundEnvironment roundEnv ) throws Exception { printCompileNote ( ) ; Set < TypeElement > annotatedElements = getBuildableAnnotatedElements ( roundEnv ) ; printNumberOfBuildables ( annotatedElements ) ; Set < TypeElement > validatedElements = validateElements ( annotatedElements ) ; JCodeModel codeModel = buildModel ( validatedElements ) ; generateSources ( codeModel ) ; } private void printCompileNote ( ) { Messager messager = processingEnv . getMessager ( ) ; messager . printMessage ( Diagnostic . Kind . NOTE , "<STR_LIT>" ) ; } private Set < TypeElement > getBuildableAnnotatedElements ( RoundEnvironment roundEnv ) { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Set < TypeElement > annotatedElements = ( Set < TypeElement > ) roundEnv . getElementsAnnotatedWith ( Buildable . class ) ; return annotatedElements ; } private void printNumberOfBuildables ( Set < ? > buildableElements ) { Messager messager = processingEnv . getMessager ( ) ; messager . printMessage ( Kind . NOTE , "<STR_LIT>" + buildableElements . size ( ) + "<STR_LIT>" ) ; } private Set < TypeElement > validateElements ( Set < TypeElement > annotatedElements ) { BuildableValidator validator = new BuildableValidator ( processingEnv , new ElementHelper ( ) ) ; Set < TypeElement > validatedElements = new HashSet < TypeElement > ( ) ; for ( TypeElement annotatedElement : annotatedElements ) { if ( validator . validate ( annotatedElement ) ) { validatedElements . add ( annotatedElement ) ; } } return validatedElements ; } private JCodeModel buildModel ( Set < TypeElement > validatedElements ) throws JClassAlreadyExistsException { JCodeModel codeModel = new JCodeModel ( ) ; ModelBuilder modelBuilder = new ModelBuilder ( codeModel , new ElementHelper ( ) ) ; for ( TypeElement validatedElement : validatedElements ) { modelBuilder . buildClass ( validatedElement ) ; } return codeModel ; } private void generateSources ( JCodeModel codeModel ) throws IOException { Filer filer = processingEnv . getFiler ( ) ; SourceGenerator sourceGenerator = new SourceGenerator ( filer ) ; sourceGenerator . generate ( codeModel ) ; } private void printError ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv , Exception e ) { Messager messager = processingEnv . getMessager ( ) ; Throwable rootCause = e ; while ( rootCause . getCause ( ) != null ) { rootCause = rootCause . getCause ( ) ; } StackTraceElement firstElement = e . getStackTrace ( ) [ <NUM_LIT:0> ] ; StackTraceElement rootFirstElement = rootCause . getStackTrace ( ) [ <NUM_LIT:0> ] ; String errorMessage = e . toString ( ) + "<STR_LIT:U+0020>" + firstElement . toString ( ) + "<STR_LIT>" + rootCause . toString ( ) + "<STR_LIT:U+0020>" + rootFirstElement . toString ( ) ; messager . printMessage ( Diagnostic . Kind . ERROR , "<STR_LIT>" + errorMessage ) ; e . printStackTrace ( ) ; Element element = roundEnv . getElementsAnnotatedWith ( annotations . iterator ( ) . next ( ) ) . iterator ( ) . next ( ) ; messager . printMessage ( Diagnostic . Kind . ERROR , "<STR_LIT>" + errorMessage , element ) ; } } </s>
<s> package info . piwai . buildergen . processing ; import java . lang . annotation . Annotation ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Documented @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) public @ interface SupportedAnnotationClasses { Class < ? extends Annotation > [ ] value ( ) ; } </s>
<s> package info . piwai . buildergen . modeling ; import static com . sun . codemodel . JExpr . _this ; import info . piwai . buildergen . api . Buildable ; import info . piwai . buildergen . api . Builder ; import info . piwai . buildergen . api . Mandatory ; import info . piwai . buildergen . api . UncheckedBuilder ; import info . piwai . buildergen . helper . ElementHelper ; import info . piwai . buildergen . processing . BuilderGenProcessor ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . Set ; import javax . annotation . Generated ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . VariableElement ; import javax . lang . model . type . TypeMirror ; import com . sun . codemodel . JBlock ; import com . sun . codemodel . JClass ; import com . sun . codemodel . JClassAlreadyExistsException ; import com . sun . codemodel . JCodeModel ; import com . sun . codemodel . JDefinedClass ; import com . sun . codemodel . JDocComment ; import com . sun . codemodel . JExpr ; import com . sun . codemodel . JFieldVar ; import com . sun . codemodel . JInvocation ; import com . sun . codemodel . JMethod ; import com . sun . codemodel . JMod ; import com . sun . codemodel . JType ; import com . sun . codemodel . JVar ; public class ModelBuilder { private final ElementHelper elementHelper ; private final JCodeModel codeModel ; public ModelBuilder ( JCodeModel codeModel , ElementHelper elementHelper ) { this . elementHelper = elementHelper ; this . codeModel = codeModel ; } public void buildClass ( TypeElement buildableElement ) throws JClassAlreadyExistsException { String builderFullyQualifiedName = extractBuilderFullyQualifiedName ( buildableElement ) ; Set < ExecutableElement > constructors = elementHelper . findAccessibleConstructors ( buildableElement ) ; ExecutableElement constructor = elementHelper . findBuilderConstructor ( constructors ) ; JDefinedClass builderClass = codeModel . _class ( builderFullyQualifiedName ) ; JClass buildableClass = codeModel . ref ( buildableElement . getQualifiedName ( ) . toString ( ) ) ; SimpleDateFormat isoDateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; builderClass . annotate ( Generated . class ) . param ( "<STR_LIT>" , "<STR_LIT>" ) . param ( "<STR_LIT:value>" , BuilderGenProcessor . class . getName ( ) ) . param ( "<STR_LIT:date>" , isoDateFormat . format ( new Date ( ) ) ) ; List < ? extends VariableElement > parameters = constructor . getParameters ( ) ; for ( VariableElement parameter : parameters ) { String paramName = parameter . getSimpleName ( ) . toString ( ) ; String paramClassFullyQualifiedName = parameter . asType ( ) . toString ( ) ; JClass paramClass = codeModel . ref ( paramClassFullyQualifiedName ) ; JFieldVar setterField = builderClass . field ( JMod . PRIVATE , paramClass , paramName ) ; JMethod setter = builderClass . method ( JMod . PUBLIC , builderClass , paramName ) ; JVar setterParam = setter . param ( paramClass , paramName ) ; setter . body ( ) . assign ( _this ( ) . ref ( setterField ) , setterParam ) . _return ( _this ( ) ) ; JDocComment javadoc = setter . javadoc ( ) . append ( "<STR_LIT>" ) . append ( paramName ) . append ( "<STR_LIT>" ) ; javadoc . addParam ( setterParam ) . append ( "<STR_LIT>" ) . append ( paramName ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) ; javadoc . addReturn ( ) . append ( "<STR_LIT>" ) . append ( builderClass ) . append ( "<STR_LIT>" ) ; } List < VariableElement > mandatoryParameters = new ArrayList < VariableElement > ( ) ; for ( VariableElement parameter : parameters ) { if ( parameter . getAnnotation ( Mandatory . class ) != null ) { mandatoryParameters . add ( parameter ) ; } } JMethod buildMethod = builderClass . method ( JMod . PUBLIC , buildableClass , "<STR_LIT>" ) ; JDocComment javadoc = buildMethod . javadoc ( ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) ; javadoc . addReturn ( ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) ; boolean hasCheckedExceptions = false ; JClass runtimeException = codeModel . ref ( RuntimeException . class ) ; List < ? extends TypeMirror > thrownTypes = constructor . getThrownTypes ( ) ; for ( TypeMirror thrownType : thrownTypes ) { JClass thrownClass = codeModel . ref ( thrownType . toString ( ) ) ; buildMethod . _throws ( thrownClass ) ; javadoc . addThrows ( thrownClass ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) ; if ( ! runtimeException . isAssignableFrom ( thrownClass ) ) { hasCheckedExceptions = true ; } } if ( hasCheckedExceptions ) { JClass builderInterface = codeModel . ref ( Builder . class ) ; JClass narrowedInterface = builderInterface . narrow ( buildableClass ) ; builderClass . _implements ( narrowedInterface ) ; } else { JClass builderInterface = codeModel . ref ( UncheckedBuilder . class ) ; JClass narrowedInterface = builderInterface . narrow ( buildableClass ) ; builderClass . _implements ( narrowedInterface ) ; } JBlock buildBody = buildMethod . body ( ) ; JInvocation newBuildable = JExpr . _new ( buildableClass ) ; for ( VariableElement parameter : constructor . getParameters ( ) ) { String paramName = parameter . getSimpleName ( ) . toString ( ) ; newBuildable . arg ( JExpr . ref ( paramName ) ) ; } buildBody . _return ( newBuildable ) ; JClass mandatoryClass = codeModel . ref ( Mandatory . class ) ; if ( mandatoryParameters . size ( ) != <NUM_LIT:0> ) { JMethod builderConstructor = builderClass . constructor ( JMod . PUBLIC ) ; JBlock constructorBody = builderConstructor . body ( ) ; JDocComment constructorJavadoc = builderConstructor . javadoc ( ) . append ( "<STR_LIT>" ) . append ( mandatoryClass ) . append ( "<STR_LIT>" ) ; for ( VariableElement parameter : mandatoryParameters ) { String paramName = parameter . getSimpleName ( ) . toString ( ) ; JFieldVar paramField = builderClass . fields ( ) . get ( paramName ) ; JType paramClass = paramField . type ( ) ; JVar constructorParam = builderConstructor . param ( paramClass , paramName ) ; constructorBody . assign ( _this ( ) . ref ( paramField ) , constructorParam ) ; constructorJavadoc . addParam ( constructorParam ) . append ( "<STR_LIT>" ) . append ( paramName ) . append ( "<STR_LIT>" ) . append ( mandatoryClass ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) ; } } JMethod createMethod = builderClass . method ( JMod . PUBLIC | JMod . STATIC , builderClass , "<STR_LIT>" ) ; JBlock createBody = createMethod . body ( ) ; JDocComment createJavadoc = createMethod . javadoc ( ) ; JInvocation newBuilder = JExpr . _new ( builderClass ) ; if ( mandatoryParameters . size ( ) != <NUM_LIT:0> ) { for ( VariableElement parameter : mandatoryParameters ) { String paramName = parameter . getSimpleName ( ) . toString ( ) ; JFieldVar paramField = builderClass . fields ( ) . get ( paramName ) ; JType paramClass = paramField . type ( ) ; JVar createParam = createMethod . param ( paramClass , paramName ) ; newBuilder . arg ( createParam ) ; createJavadoc . addParam ( createParam ) . append ( "<STR_LIT>" ) . append ( paramName ) . append ( "<STR_LIT>" ) . append ( mandatoryClass ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) ; } } createBody . _return ( newBuilder ) ; createJavadoc . append ( "<STR_LIT>" ) . append ( builderClass ) . append ( "<STR_LIT>" ) . addReturn ( ) . append ( "<STR_LIT>" ) . append ( builderClass ) . append ( "<STR_LIT>" ) ; addBuilderClassJavadoc ( builderClass , buildableClass ) ; } private void addBuilderClassJavadoc ( JDefinedClass builderClass , JClass buildableClass ) { builderClass . javadoc ( ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( builderClass ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( buildableClass ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) ; } private String extractBuilderFullyQualifiedName ( TypeElement buildableElement ) { Buildable buildableAnnotation = buildableElement . getAnnotation ( Buildable . class ) ; String builderSuffix = buildableAnnotation . value ( ) ; String buildableFullyQualifiedName = buildableElement . getQualifiedName ( ) . toString ( ) ; return buildableFullyQualifiedName + builderSuffix ; } } </s>
<s> package info . piwai . buildergen . validation ; public class IsValid { private boolean valid = true ; public void invalidate ( ) { valid = false ; } public boolean isValid ( ) { return valid ; } } </s>
<s> package info . piwai . buildergen . validation ; import info . piwai . buildergen . api . Build ; import info . piwai . buildergen . api . Buildable ; import info . piwai . buildergen . helper . ElementHelper ; import java . lang . annotation . Annotation ; import java . util . List ; import java . util . Set ; import javax . annotation . processing . ProcessingEnvironment ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . AnnotationValue ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; import javax . tools . Diagnostic ; import javax . tools . Diagnostic . Kind ; public class BuildableValidator { private final ProcessingEnvironment processingEnv ; private final ElementHelper elementHelper ; public BuildableValidator ( ProcessingEnvironment processingEnv , ElementHelper elementHelper ) { this . processingEnv = processingEnv ; this . elementHelper = elementHelper ; } public boolean validate ( TypeElement element ) { IsValid valid = new IsValid ( ) ; if ( element . getKind ( ) != ElementKind . CLASS ) { valid . invalidate ( ) ; printBuildableError ( element , "<STR_LIT>" ) ; } if ( element . getEnclosingElement ( ) . getKind ( ) != ElementKind . PACKAGE ) { valid . invalidate ( ) ; printBuildableError ( element , "<STR_LIT>" ) ; } if ( element . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ) { valid . invalidate ( ) ; printBuildableError ( element , "<STR_LIT>" ) ; } Buildable buildableAnnotation = element . getAnnotation ( Buildable . class ) ; String builderNameSuffix = buildableAnnotation . value ( ) ; if ( "<STR_LIT>" . equals ( builderNameSuffix ) ) { valid . invalidate ( ) ; AnnotationMirror annotationMirror = findAnnotationMirror ( element , Buildable . class ) ; AnnotationValue annotationValue = annotationMirror . getElementValues ( ) . values ( ) . iterator ( ) . next ( ) ; processingEnv . getMessager ( ) . printMessage ( Kind . ERROR , "<STR_LIT>" , element , annotationMirror , annotationValue ) ; } Set < ExecutableElement > constructors = elementHelper . findAccessibleConstructors ( element ) ; if ( constructors . size ( ) == <NUM_LIT:0> ) { valid . invalidate ( ) ; printBuildableError ( element , "<STR_LIT>" ) ; } else { ExecutableElement builderConstructor = null ; if ( constructors . size ( ) == <NUM_LIT:1> ) { builderConstructor = constructors . iterator ( ) . next ( ) ; } else { Set < ExecutableElement > builderConstructors = elementHelper . findBuilderConstructors ( constructors ) ; if ( builderConstructors . size ( ) == <NUM_LIT:0> ) { valid . invalidate ( ) ; String message = "<STR_LIT>" + Build . class . getSimpleName ( ) + "<STR_LIT>" ; printBuildableError ( element , message ) ; for ( ExecutableElement constructor : constructors ) { processingEnv . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , message , constructor ) ; } } else if ( builderConstructors . size ( ) > <NUM_LIT:1> ) { valid . invalidate ( ) ; for ( ExecutableElement constructor : builderConstructors ) { printBuildError ( constructor , "<STR_LIT>" ) ; } } else { builderConstructor = builderConstructors . iterator ( ) . next ( ) ; } } if ( builderConstructor != null ) { List < ? extends TypeMirror > thrownTypes = builderConstructor . getThrownTypes ( ) ; if ( thrownTypes . size ( ) > <NUM_LIT:0> ) { Types typeUtils = processingEnv . getTypeUtils ( ) ; Elements elementUtils = processingEnv . getElementUtils ( ) ; TypeElement exceptionElement = elementUtils . getTypeElement ( Exception . class . getName ( ) ) ; TypeMirror exceptionMirror = exceptionElement . asType ( ) ; for ( TypeMirror thrownType : thrownTypes ) { if ( ! typeUtils . isSubtype ( thrownType , exceptionMirror ) ) { valid . invalidate ( ) ; processingEnv . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , "<STR_LIT>" , builderConstructor ) ; } } } } } return valid . isValid ( ) ; } private void printBuildError ( Element annotatedElement , String message ) { printMessageOnAnnotation ( Diagnostic . Kind . ERROR , annotatedElement , Build . class , String . format ( message , "<STR_LIT:@>" + Build . class . getSimpleName ( ) ) ) ; } private void printBuildableError ( Element annotatedElement , String message ) { printMessageOnAnnotation ( Diagnostic . Kind . ERROR , annotatedElement , Buildable . class , String . format ( message , "<STR_LIT:@>" + Buildable . class . getSimpleName ( ) ) ) ; } private void printMessageOnAnnotation ( Diagnostic . Kind diagnosticKind , Element annotatedElement , Class < ? extends Annotation > annotationClass , String message ) { AnnotationMirror annotationMirror = findAnnotationMirror ( annotatedElement , annotationClass ) ; if ( annotationMirror != null ) { processingEnv . getMessager ( ) . printMessage ( diagnosticKind , message , annotatedElement , annotationMirror ) ; } else { processingEnv . getMessager ( ) . printMessage ( diagnosticKind , message , annotatedElement ) ; } } private AnnotationMirror findAnnotationMirror ( Element annotatedElement , Class < ? extends Annotation > annotationClass ) { List < ? extends AnnotationMirror > annotationMirrors = annotatedElement . getAnnotationMirrors ( ) ; for ( AnnotationMirror annotationMirror : annotationMirrors ) { TypeElement annotationElement = ( TypeElement ) annotationMirror . getAnnotationType ( ) . asElement ( ) ; if ( hasSameQualifiedName ( annotationElement , annotationClass ) ) { return annotationMirror ; } } return null ; } private boolean hasSameQualifiedName ( TypeElement annotation , Class < ? extends Annotation > annotationClass ) { return annotation . getQualifiedName ( ) . toString ( ) . equals ( annotationClass . getName ( ) ) ; } } </s>
<s> package info . piwai . buildergen . helper ; import info . piwai . buildergen . api . Build ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . TypeElement ; public class ElementHelper { public Set < ExecutableElement > findAccessibleConstructors ( TypeElement buildableElement ) { Set < ExecutableElement > constructors = new HashSet < ExecutableElement > ( ) ; List < ? extends Element > enclosedElements = buildableElement . getEnclosedElements ( ) ; for ( Element enclosedElement : enclosedElements ) { ElementKind enclosedElementKind = enclosedElement . getKind ( ) ; if ( enclosedElementKind == ElementKind . CONSTRUCTOR ) { if ( ! enclosedElement . getModifiers ( ) . contains ( Modifier . PRIVATE ) ) { constructors . add ( ( ExecutableElement ) enclosedElement ) ; } } } return constructors ; } public ExecutableElement findBuilderConstructor ( Set < ExecutableElement > constructors ) { Set < ExecutableElement > buildersConstructor = findBuilderConstructors ( constructors ) ; if ( buildersConstructor . size ( ) == <NUM_LIT:1> ) { return buildersConstructor . iterator ( ) . next ( ) ; } else { throw new IllegalStateException ( "<STR_LIT>" ) ; } } public Set < ExecutableElement > findBuilderConstructors ( Set < ExecutableElement > constructors ) { if ( constructors . size ( ) == <NUM_LIT:1> ) { return constructors ; } else { Set < ExecutableElement > buildersConstructors = new HashSet < ExecutableElement > ( ) ; for ( ExecutableElement candidateConstructor : constructors ) { if ( candidateConstructor . getAnnotation ( Build . class ) != null ) { buildersConstructors . add ( candidateConstructor ) ; } } return buildersConstructors ; } } } </s>
<s> package info . piwai . buildergen . generation ; import java . io . IOException ; import javax . annotation . processing . Filer ; import com . sun . codemodel . JCodeModel ; import com . sun . codemodel . writer . PrologCodeWriter ; public class SourceGenerator { private static final String HEADER_WARNING = "<STR_LIT>" ; private final Filer filer ; public SourceGenerator ( Filer filer ) { this . filer = filer ; } public void generate ( JCodeModel codeModel ) throws IOException { SourceCodeWriter sourceCodeWriter = new SourceCodeWriter ( filer ) ; PrologCodeWriter prologCodeWriter = new PrologCodeWriter ( sourceCodeWriter , HEADER_WARNING ) ; codeModel . build ( prologCodeWriter , new ResourceCodeWriter ( filer ) ) ; } } </s>
<s> package info . piwai . buildergen . generation ; import java . io . IOException ; import java . io . OutputStream ; import javax . annotation . processing . Filer ; import javax . tools . FileObject ; import javax . tools . StandardLocation ; import com . sun . codemodel . CodeWriter ; import com . sun . codemodel . JPackage ; public class ResourceCodeWriter extends CodeWriter { private final Filer filer ; public ResourceCodeWriter ( Filer filer ) { this . filer = filer ; } @ Override public OutputStream openBinary ( JPackage pkg , String fileName ) throws IOException { FileObject resource = filer . createResource ( StandardLocation . SOURCE_OUTPUT , pkg . name ( ) , fileName ) ; return resource . openOutputStream ( ) ; } @ Override public void close ( ) throws IOException { } } </s>
<s> package info . piwai . buildergen . generation ; import java . io . IOException ; import java . io . OutputStream ; import javax . annotation . processing . Filer ; import javax . tools . JavaFileObject ; import com . sun . codemodel . CodeWriter ; import com . sun . codemodel . JPackage ; public class SourceCodeWriter extends CodeWriter { private final Filer filer ; public SourceCodeWriter ( Filer filer ) { this . filer = filer ; } @ Override public OutputStream openBinary ( JPackage pkg , String fileName ) throws IOException { String qualifiedClassName = toQualifiedClassName ( pkg , fileName ) ; JavaFileObject sourceFile = filer . createSourceFile ( qualifiedClassName ) ; return sourceFile . openOutputStream ( ) ; } private String toQualifiedClassName ( JPackage pkg , String fileName ) { int suffixPosition = fileName . lastIndexOf ( '<CHAR_LIT:.>' ) ; String className = fileName . substring ( <NUM_LIT:0> , suffixPosition ) ; String qualifiedClassName = pkg . name ( ) + "<STR_LIT:.>" + className ; return qualifiedClassName ; } @ Override public void close ( ) throws IOException { } } </s>
<s> package info . piwai . buildergen . api ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . SOURCE ) @ Target ( ElementType . PARAMETER ) public @ interface Mandatory { } </s>
<s> package info . piwai . buildergen . api ; public interface UncheckedBuilder < T > extends Builder < T > { T build ( ) ; } </s>
<s> package info . piwai . buildergen . api ; public interface Builder < T > { T build ( ) throws Exception ; } </s>
<s> package info . piwai . buildergen . api ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . SOURCE ) @ Target ( ElementType . CONSTRUCTOR ) public @ interface Build { } </s>
<s> package info . piwai . buildergen . api ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . SOURCE ) @ Target ( ElementType . TYPE ) public @ interface Buildable { String value ( ) default "<STR_LIT>" ; } </s>
<s> package dcll . tarti . tartiquizz ; import static org . junit . Assert . * ; import org . junit . Test ; public class ParserQuizzMoodleTest { @ Test public void ParserTest ( ) { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; assertEquals ( pars . getRacineName ( ) , "<STR_LIT>" ) ; } } </s>
<s> package dcll . tarti . tartiquizz ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import elementMoodle . AnswerMoodle ; import elementMoodle . QuizzMoodle ; import exception . AttributNotFoundException ; import exception . TypeQuestionNotFoundException ; public class MultichoiceQuestionTest { @ Test public void parserMultichoice ( ) throws AttributNotFoundException { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz ; try { monQuizz = pars . createQuizz ( ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT:name>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:0>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:false>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:OK>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:abc>" ) ; List < String > answer = monQuizz . getAnswers ( <NUM_LIT:1> ) ; assertEquals ( answer . get ( <NUM_LIT:0> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:1> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:2> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:3> ) , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } } @ Test public void exportMultichoice ( ) throws AttributNotFoundException { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz ; try { monQuizz = pars . createQuizz ( ) ; pars . exportQuizzMoodle ( monQuizz , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } ParserQuizzMoodle pars2 = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz2 ; try { monQuizz2 = pars2 . createQuizz ( ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT:name>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:0>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:false>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:OK>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:abc>" ) ; List < String > answer = monQuizz2 . getAnswers ( <NUM_LIT:1> ) ; assertEquals ( answer . get ( <NUM_LIT:0> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:1> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:2> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:3> ) , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } } } </s>
<s> package dcll . tarti . tartiquizz ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import elementMoodle . QuizzMoodle ; import exception . AttributNotFoundException ; import exception . TypeQuestionNotFoundException ; public class TrueFalseQuestionTest { @ Test public void parserTrueFalse ( ) throws AttributNotFoundException { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz ; try { monQuizz = pars . createQuizz ( ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT:name>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:0>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; List < String > answer = monQuizz . getAnswers ( <NUM_LIT:1> ) ; assertEquals ( answer . get ( <NUM_LIT:0> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:1> ) , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } } @ Test public void exportTrueFalse ( ) throws AttributNotFoundException { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz ; try { monQuizz = pars . createQuizz ( ) ; pars . exportQuizzMoodle ( monQuizz , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } ParserQuizzMoodle pars2 = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz2 ; try { monQuizz2 = pars . createQuizz ( ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT:name>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:0>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT>" ) ; assertEquals ( monQuizz2 . getAttributQuestion ( <NUM_LIT:1> , "<STR_LIT>" ) , "<STR_LIT:1>" ) ; List < String > answer = monQuizz2 . getAnswers ( <NUM_LIT:1> ) ; assertEquals ( answer . get ( <NUM_LIT:0> ) , "<STR_LIT>" ) ; assertEquals ( answer . get ( <NUM_LIT:1> ) , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } } } </s>
<s> package exception ; public class AttributNotFoundException extends Exception { private String attribut ; public AttributNotFoundException ( String attribut ) { super ( ) ; this . attribut = attribut ; } public String getMessage ( ) { return "<STR_LIT>" + this . attribut + "<STR_LIT>" ; } } </s>
<s> package exception ; public class TypeQuestionNotFoundException extends Exception { private String type ; public TypeQuestionNotFoundException ( String type ) { super ( ) ; this . type = type ; } @ Override public String getMessage ( ) { return "<STR_LIT>" + this . type + "<STR_LIT>" ; } } </s>
<s> package dcll . tarti . tartiquizz ; import elementMoodle . QuizzMoodle ; import exception . AttributNotFoundException ; import exception . TypeQuestionNotFoundException ; public class App { public static void main ( String [ ] args ) { ParserQuizzMoodle pars = new ParserQuizzMoodle ( "<STR_LIT>" ) ; QuizzMoodle monQuizz ; try { monQuizz = pars . createQuizz ( ) ; System . out . println ( monQuizz ) ; pars . exportQuizzMoodle ( monQuizz , "<STR_LIT>" ) ; } catch ( TypeQuestionNotFoundException e ) { e . printStackTrace ( ) ; } } } </s>
<s> package dcll . tarti . tartiquizz ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import elementMoodle . QuizzMoodle ; import exception . TypeQuestionNotFoundException ; import org . jdom . Document ; import org . jdom . Element ; import org . jdom . JDOMException ; import org . jdom . input . SAXBuilder ; import org . jdom . output . Format ; import org . jdom . output . XMLOutputter ; public class ParserQuizzMoodle { private Document doc ; private Element racine ; public ParserQuizzMoodle ( String file ) { SAXBuilder sxb = new SAXBuilder ( ) ; try { doc = sxb . build ( new File ( file ) ) ; } catch ( JDOMException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } racine = doc . getRootElement ( ) ; } public QuizzMoodle createQuizz ( ) throws TypeQuestionNotFoundException { QuizzMoodle quizz = null ; quizz = new QuizzMoodle ( this . racine ) ; return quizz ; } public void exportQuizzMoodle ( QuizzMoodle quizz , String file ) { Document document = new Document ( quizz . export ( ) ) ; try { XMLOutputter sortie = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; sortie . output ( document , new FileOutputStream ( file ) ) ; } catch ( java . io . IOException e ) { } } public String getRacineName ( ) { return this . racine . getName ( ) ; } } </s>
<s> package elementMoodle ; import java . util . ArrayList ; import java . util . List ; import org . jdom . Element ; import org . jdom . Attribute ; import exception . AttributNotFoundException ; public class MultichoiceQuestion extends QuestionMoodle { private String single ; private String shuffleanswers ; private String correctfeedback ; private String partiallycorrectfeedback ; private String incorrectfeedback ; private String answernumbering ; private List < AnswerMoodle > answers ; public MultichoiceQuestion ( final Element element ) { super ( element ) ; if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . single = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . shuffleanswers = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . correctfeedback = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; } if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . partiallycorrectfeedback = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; } if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . incorrectfeedback = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; } if ( element . getChildText ( "<STR_LIT>" ) != null ) { this . answernumbering = element . getChildText ( "<STR_LIT>" ) ; } answers = new ArrayList < AnswerMoodle > ( ) ; List < Element > elementsAnswer = element . getChildren ( "<STR_LIT>" ) ; for ( Element currant : elementsAnswer ) { answers . add ( new AnswerMoodle ( currant ) ) ; } } @ Override public final Element export ( ) { Element element = super . export ( ) ; element . setAttribute ( new Attribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ) ; if ( this . shuffleanswers != null ) { Element tmp = new Element ( "<STR_LIT>" ) ; tmp . setText ( this . shuffleanswers ) ; element . addContent ( tmp ) ; } if ( this . single != null ) { Element tmp = new Element ( "<STR_LIT>" ) ; tmp . setText ( this . single ) ; element . addContent ( tmp ) ; } if ( this . answernumbering != null ) { Element tmp = new Element ( "<STR_LIT>" ) ; tmp . setText ( this . answernumbering ) ; element . addContent ( tmp ) ; } for ( AnswerMoodle current : this . answers ) { Element tmp = current . export ( ) ; element . addContent ( tmp ) ; } if ( this . correctfeedback != null ) { Element text = new Element ( "<STR_LIT:text>" ) ; text . setText ( this . correctfeedback ) ; Element tmp = new Element ( "<STR_LIT>" ) ; tmp . addContent ( text ) ; element . addContent ( tmp ) ; } if ( this . partiallycorrectfeedback != null ) { Element text = new Element ( "<STR_LIT:text>" ) ; text . setText ( this . partiallycorrectfeedback ) ; Element tmp = new Element ( "<STR_LIT>" ) ; tmp . addContent ( text ) ; element . addContent ( tmp ) ; } if ( this . incorrectfeedback != null ) { Element text = new Element ( "<STR_LIT:text>" ) ; text . setText ( this . incorrectfeedback ) ; Element tmp = new Element ( "<STR_LIT>" ) ; tmp . addContent ( text ) ; element . addContent ( tmp ) ; } return element ; } @ Override public final String getAttribut ( final String attribut ) throws AttributNotFoundException { if ( attribut . equals ( "<STR_LIT>" ) && this . single != null ) { return this . single ; } if ( attribut . equals ( "<STR_LIT>" ) && this . shuffleanswers != null ) { return this . shuffleanswers ; } if ( attribut . equals ( "<STR_LIT>" ) && this . correctfeedback != null ) { return this . correctfeedback ; } if ( attribut . equals ( "<STR_LIT>" ) && this . partiallycorrectfeedback != null ) { return this . partiallycorrectfeedback ; } if ( attribut . equals ( "<STR_LIT>" ) && this . incorrectfeedback != null ) { return this . incorrectfeedback ; } if ( attribut . equals ( "<STR_LIT>" ) && this . answernumbering != null ) { return this . answernumbering ; } return super . getAttribut ( attribut ) ; } @ Override public final List < String > getAnswers ( ) { List < String > listAnswer = new ArrayList < String > ( ) ; String answer ; for ( AnswerMoodle currant : answers ) { try { answer = currant . getAttribut ( "<STR_LIT:text>" ) + "<STR_LIT>" + currant . getAttribut ( "<STR_LIT>" ) + "<STR_LIT:U+0020(>" + currant . getAttribut ( "<STR_LIT>" ) + "<STR_LIT:)>" ; listAnswer . add ( answer ) ; } catch ( AttributNotFoundException e ) { e . printStackTrace ( ) ; } } return listAnswer ; } @ Override public final String toString ( ) { int i = <NUM_LIT:1> ; String mess = "<STR_LIT>" + super . toString ( ) ; for ( AnswerMoodle currant : answers ) { mess += "<STR_LIT:t>" + i + "<STR_LIT>" + currant ; i ++ ; } return mess ; } } </s>
<s> package elementMoodle ; import java . util . List ; import org . jdom . Attribute ; import org . jdom . Element ; import exception . AttributNotFoundException ; public abstract class QuestionMoodle extends ElementMoodle { private String name ; private String questiontext ; private String format ; private String penalty ; private String generalfeedback ; private String defaultgrade ; private String hidden ; private String image ; private String image_base64 ; public QuestionMoodle ( Element element ) { super ( element ) ; this . name = element . getChild ( "<STR_LIT:name>" ) . getChildText ( "<STR_LIT:text>" ) ; this . questiontext = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; this . format = element . getChild ( "<STR_LIT>" ) . getAttributeValue ( "<STR_LIT>" ) ; if ( element . getChild ( "<STR_LIT>" ) != null ) { this . penalty = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChild ( "<STR_LIT>" ) != null ) { this . generalfeedback = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; } if ( element . getChild ( "<STR_LIT>" ) != null ) { this . defaultgrade = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChild ( "<STR_LIT>" ) != null ) { this . hidden = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChild ( "<STR_LIT>" ) != null ) { this . image = element . getChildText ( "<STR_LIT>" ) ; } if ( element . getChild ( "<STR_LIT>" ) != null ) { this . image_base64 = element . getChildText ( "<STR_LIT>" ) ; } } public Element export ( ) { Element element = new Element ( "<STR_LIT>" ) ; Element name = new Element ( "<STR_LIT:name>" ) ; Element textName = new Element ( "<STR_LIT:text>" ) ; textName . setText ( this . name ) ; name . addContent ( textName ) ; element . addContent ( name ) ; Element questiontext = new Element ( "<STR_LIT>" ) ; questiontext . setAttribute ( new Attribute ( "<STR_LIT>" , this . format ) ) ; Element textQuestiontext = new Element ( "<STR_LIT:text>" ) ; textQuestiontext . setText ( this . questiontext ) ; questiontext . addContent ( textQuestiontext ) ; element . addContent ( questiontext ) ; if ( this . penalty != null ) { Element penalty = new Element ( "<STR_LIT>" ) ; penalty . setText ( this . penalty ) ; element . addContent ( penalty ) ; } if ( this . generalfeedback != null ) { Element generalfeedback = new Element ( "<STR_LIT>" ) ; Element textGeneralfeedback = new Element ( "<STR_LIT:text>" ) ; textGeneralfeedback . setText ( this . generalfeedback ) ; generalfeedback . addContent ( textGeneralfeedback ) ; element . addContent ( generalfeedback ) ; } if ( this . defaultgrade != null ) { Element defaultgrade = new Element ( "<STR_LIT>" ) ; defaultgrade . setText ( this . defaultgrade ) ; element . addContent ( defaultgrade ) ; } if ( this . hidden != null ) { Element hidden = new Element ( "<STR_LIT>" ) ; hidden . setText ( this . hidden ) ; element . addContent ( hidden ) ; } if ( this . image != null ) { Element image = new Element ( "<STR_LIT>" ) ; image . setText ( this . image ) ; element . addContent ( image ) ; } if ( this . image_base64 != null ) { Element image_base64 = new Element ( "<STR_LIT>" ) ; image_base64 . setText ( this . image_base64 ) ; element . addContent ( image_base64 ) ; } return element ; } public String getAttribut ( String attribut ) throws AttributNotFoundException { if ( attribut . equals ( "<STR_LIT:name>" ) ) { return this . name ; } if ( attribut . equals ( "<STR_LIT>" ) ) { return this . questiontext ; } if ( attribut . equals ( "<STR_LIT>" ) ) { return this . format ; } if ( attribut . equals ( "<STR_LIT>" ) && this . penalty != null ) { return this . penalty ; } if ( attribut . equals ( "<STR_LIT>" ) && this . generalfeedback != null ) { return this . generalfeedback ; } if ( attribut . equals ( "<STR_LIT>" ) && this . defaultgrade != null ) { return this . defaultgrade ; } if ( attribut . equals ( "<STR_LIT>" ) && this . hidden != null ) { return this . hidden ; } if ( attribut . equals ( "<STR_LIT>" ) && this . image != null ) { return this . image ; } if ( attribut . equals ( "<STR_LIT>" ) && this . image_base64 != null ) { return this . image_base64 ; } throw new AttributNotFoundException ( attribut ) ; } public abstract List < String > getAnswers ( ) ; public String toString ( ) { return "<STR_LIT>" + this . name + "<STR_LIT:n>" + questiontext + "<STR_LIT:n>" ; } } </s>
<s> package elementMoodle ; import java . util . ArrayList ; import java . util . List ; import org . jdom . Attribute ; import org . jdom . Element ; import exception . AttributNotFoundException ; public class TrueFalseQuestion extends QuestionMoodle { private String shuffleanswers ; private List < AnswerMoodle > answers ; public TrueFalseQuestion ( final Element element ) { super ( element ) ; if ( element . getChild ( "<STR_LIT>" ) != null ) { this . shuffleanswers = element . getChildText ( "<STR_LIT>" ) ; } answers = new ArrayList < AnswerMoodle > ( ) ; List < Element > answeelem = element . getChildren ( "<STR_LIT>" ) ; for ( Element currant : answeelem ) { answers . add ( new AnswerMoodle ( currant ) ) ; } } @ Override public final Element export ( ) { Element element = super . export ( ) ; element . setAttribute ( new Attribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ) ; for ( AnswerMoodle ans : answers ) { element . addContent ( ans . export ( ) ) ; } if ( this . shuffleanswers != null ) { Element shuffleanswersE = new Element ( "<STR_LIT>" ) ; shuffleanswersE . setText ( this . shuffleanswers ) ; element . addContent ( shuffleanswersE ) ; } return element ; } @ Override public final List < String > getAnswers ( ) { List < String > lisAnswer = new ArrayList < String > ( ) ; String res = null ; for ( AnswerMoodle courant : answers ) { try { res = courant . getAttribut ( "<STR_LIT:text>" ) + "<STR_LIT>" + courant . getAttribut ( "<STR_LIT>" ) + "<STR_LIT:U+0020(>" + courant . getAttribut ( "<STR_LIT>" ) + "<STR_LIT:)>" ; } catch ( AttributNotFoundException e ) { e . printStackTrace ( ) ; } lisAnswer . add ( res ) ; } return lisAnswer ; } @ Override public final String getAttribut ( final String attribut ) throws AttributNotFoundException { if ( attribut . equals ( "<STR_LIT>" ) && this . shuffleanswers != null ) { return shuffleanswers ; } return super . getAttribut ( attribut ) ; } @ Override public final String toString ( ) { int i = <NUM_LIT:1> ; String mess = "<STR_LIT>" + super . toString ( ) ; for ( AnswerMoodle currant : answers ) { mess += "<STR_LIT:t>" + i + "<STR_LIT>" + currant ; i ++ ; } return mess ; } } </s>
<s> package elementMoodle ; import java . util . ArrayList ; import java . util . List ; import org . jdom . Element ; import org . jdom . filter . Filter ; import exception . AttributNotFoundException ; import exception . TypeQuestionNotFoundException ; public class QuizzMoodle extends ElementMoodle { List < QuestionMoodle > questions ; public QuizzMoodle ( Element element ) throws TypeQuestionNotFoundException { super ( element ) ; this . questions = new ArrayList < QuestionMoodle > ( ) ; Filter questionFilter = new Filter ( ) { public boolean matches ( Object arg0 ) { boolean isQuestion = false ; if ( ! ( arg0 instanceof Element ) ) { return false ; } Element element = ( Element ) arg0 ; return ! element . getAttributeValue ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ; } } ; boolean typeNotFound ; List < Element > elementsQuestion = element . getContent ( questionFilter ) ; for ( Element currant : elementsQuestion ) { typeNotFound = true ; if ( currant . getAttributeValue ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ) { questions . add ( new MultichoiceQuestion ( currant ) ) ; typeNotFound = false ; } if ( currant . getAttributeValue ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ) { questions . add ( new TrueFalseQuestion ( currant ) ) ; typeNotFound = false ; } if ( typeNotFound ) { throw new TypeQuestionNotFoundException ( currant . getAttributeValue ( "<STR_LIT:type>" ) ) ; } } } public Element export ( ) { Element element = new Element ( "<STR_LIT>" ) ; for ( QuestionMoodle currant : questions ) { element . addContent ( currant . export ( ) ) ; } return element ; } public String getAttributQuestion ( int indexQuestion , String attribut ) throws AttributNotFoundException { return this . questions . get ( indexQuestion - <NUM_LIT:1> ) . getAttribut ( attribut ) ; } public List < String > getAnswers ( int indexQuestion ) { return questions . get ( indexQuestion - <NUM_LIT:1> ) . getAnswers ( ) ; } @ Override public String getAttribut ( String attribut ) throws AttributNotFoundException { throw new AttributNotFoundException ( attribut ) ; } @ Override public String toString ( ) { String listQuestion = "<STR_LIT>" ; int i = <NUM_LIT:1> ; for ( QuestionMoodle currant : questions ) { listQuestion += i + "<STR_LIT>" + currant + "<STR_LIT:n>" ; i ++ ; } return listQuestion ; } } </s>
<s> package elementMoodle ; import org . jdom . Attribute ; import org . jdom . Element ; import exception . AttributNotFoundException ; public class AnswerMoodle extends ElementMoodle { private String fraction ; private String text ; private String feedback ; public AnswerMoodle ( Element element ) { super ( element ) ; this . fraction = element . getAttributeValue ( "<STR_LIT>" ) ; this . text = element . getChildText ( "<STR_LIT:text>" ) ; this . feedback = element . getChild ( "<STR_LIT>" ) . getChildText ( "<STR_LIT:text>" ) ; } @ Override public Element export ( ) { Element element = new Element ( "<STR_LIT>" ) ; element . setAttribute ( new Attribute ( "<STR_LIT>" , this . fraction ) ) ; Element text = new Element ( "<STR_LIT:text>" ) ; text . setText ( this . text ) ; element . addContent ( text ) ; Element feedback = new Element ( "<STR_LIT>" ) ; Element textFeedback = new Element ( "<STR_LIT:text>" ) ; textFeedback . setText ( this . feedback ) ; feedback . addContent ( textFeedback ) ; element . addContent ( feedback ) ; return element ; } @ Override public String getAttribut ( String attribut ) throws AttributNotFoundException { if ( attribut . equals ( "<STR_LIT>" ) && this . fraction != null ) { return this . fraction ; } if ( attribut . equals ( "<STR_LIT:text>" ) && this . text != null ) { return this . text ; } if ( attribut . equals ( "<STR_LIT>" ) && this . feedback != null ) { return this . feedback ; } throw new AttributNotFoundException ( attribut ) ; } @ Override public String toString ( ) { return this . text + "<STR_LIT:n>" ; } } </s>
<s> package elementMoodle ; import org . jdom . Element ; import exception . AttributNotFoundException ; public abstract class ElementMoodle { public ElementMoodle ( Element element ) { } public abstract Element export ( ) ; public abstract String getAttribut ( String attribut ) throws AttributNotFoundException ; public abstract String toString ( ) ; } </s>
<s> package me . NerdsWBNerds . SimpleWarps ; import org . bukkit . Location ; public class Warp { public String name ; public Location location ; public Warp ( String s , Location l ) { name = s ; location = l ; } } </s>
<s> package me . NerdsWBNerds . SimpleWarps ; import org . bukkit . ChatColor ; import org . bukkit . Material ; import org . bukkit . block . Sign ; import org . bukkit . entity . Player ; import org . bukkit . event . EventHandler ; import org . bukkit . event . Listener ; import org . bukkit . event . block . Action ; import org . bukkit . event . block . SignChangeEvent ; import org . bukkit . event . player . PlayerInteractEvent ; public class SWListener implements Listener { public SimpleWarps plugin ; public SWListener ( SimpleWarps p ) { plugin = p ; } @ EventHandler public void onInteract ( PlayerInteractEvent e ) { if ( e . getAction ( ) == Action . RIGHT_CLICK_BLOCK ) { if ( e . getClickedBlock ( ) . getType ( ) == Material . WALL_SIGN || e . getClickedBlock ( ) . getType ( ) == Material . SIGN_POST || e . getClickedBlock ( ) . getType ( ) == Material . SIGN ) { Sign sign = ( Sign ) e . getClickedBlock ( ) . getState ( ) ; if ( ChatColor . stripColor ( sign . getLine ( <NUM_LIT:0> ) ) . equalsIgnoreCase ( "<STR_LIT>" ) || ChatColor . stripColor ( sign . getLine ( <NUM_LIT:0> ) ) . equalsIgnoreCase ( "<STR_LIT>" ) || ChatColor . stripColor ( sign . getLine ( <NUM_LIT:0> ) ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { String warp = ChatColor . stripColor ( sign . getLine ( <NUM_LIT:1> ) ) ; if ( ! SimpleWarps . isWarp ( warp ) ) { sign . setLine ( <NUM_LIT:0> , ChatColor . DARK_RED + "<STR_LIT>" ) ; sign . setLine ( <NUM_LIT:1> , "<STR_LIT>" ) ; sign . setLine ( <NUM_LIT:2> , "<STR_LIT>" ) ; sign . setLine ( <NUM_LIT:3> , "<STR_LIT>" ) ; return ; } if ( ! e . getPlayer ( ) . hasPermission ( "<STR_LIT>" ) ) { e . getPlayer ( ) . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return ; } if ( e . getPlayer ( ) . hasPermission ( "<STR_LIT>" ) || e . getPlayer ( ) . hasPermission ( "<STR_LIT>" + warp ) ) { e . getPlayer ( ) . teleport ( SimpleWarps . getWarp ( warp ) . location ) ; e . getPlayer ( ) . sendMessage ( SimpleWarps . prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + warp + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; } else { e . getPlayer ( ) . sendMessage ( ChatColor . RED + "<STR_LIT>" + warp ) ; } } } } } @ EventHandler public void onSignCreate ( SignChangeEvent e ) { Player player = e . getPlayer ( ) ; if ( e . getLine ( <NUM_LIT:0> ) . equalsIgnoreCase ( "<STR_LIT>" ) || e . getLine ( <NUM_LIT:0> ) . equalsIgnoreCase ( "<STR_LIT>" ) || e . getLine ( <NUM_LIT:0> ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { e . setLine ( <NUM_LIT:0> , ChatColor . DARK_RED + "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:1> , "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:2> , "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:3> , "<STR_LIT>" ) ; return ; } if ( ! SimpleWarps . isWarp ( e . getLine ( <NUM_LIT:1> ) ) ) { e . setLine ( <NUM_LIT:0> , ChatColor . DARK_RED + "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:1> , "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:2> , "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:3> , "<STR_LIT>" ) ; } else { e . setLine ( <NUM_LIT:0> , ChatColor . WHITE + "<STR_LIT>" ) ; e . setLine ( <NUM_LIT:1> , ChatColor . BOLD + e . getLine ( <NUM_LIT:1> ) ) ; e . setLine ( <NUM_LIT:2> , player . getName ( ) ) ; e . setLine ( <NUM_LIT:3> , ChatColor . DARK_GRAY + e . getLine ( <NUM_LIT:3> ) ) ; player . sendMessage ( SimpleWarps . prefix + ChatColor . GREEN + "<STR_LIT>" ) ; } } } } </s>
<s> package me . NerdsWBNerds . SimpleWarps ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . logging . Logger ; import org . bukkit . Bukkit ; import org . bukkit . ChatColor ; import org . bukkit . Location ; import org . bukkit . command . Command ; import org . bukkit . command . CommandSender ; import org . bukkit . entity . Player ; import org . bukkit . plugin . java . JavaPlugin ; public class SimpleWarps extends JavaPlugin { public Logger log ; public static ArrayList < Warp > warps = new ArrayList < Warp > ( ) ; public static String prefix = ChatColor . GOLD + "<STR_LIT>" + ChatColor . WHITE ; public void onEnable ( ) { log = getServer ( ) . getLogger ( ) ; getServer ( ) . getPluginManager ( ) . registerEvents ( new SWListener ( this ) , this ) ; loadWarps ( ) ; } public void onDisable ( ) { saveWarps ( ) ; } public boolean onCommand ( CommandSender sender , Command cmd , String label , String args [ ] ) { if ( sender instanceof Player ) { Player player = ( Player ) sender ; if ( cmd . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { if ( args . length == <NUM_LIT:0> ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } String list = "<STR_LIT>" ; for ( Warp w : warps ) { list += "<STR_LIT>" + w . name ; } player . sendMessage ( ChatColor . DARK_AQUA + "<STR_LIT>" ) ; if ( list . length ( ) > <NUM_LIT:1> ) player . sendMessage ( ChatColor . GREEN + list . substring ( <NUM_LIT:1> ) ) ; else player . sendMessage ( ChatColor . GREEN + "<STR_LIT>" ) ; return true ; } if ( args . length == <NUM_LIT:1> ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( ! isWarp ( args [ <NUM_LIT:0> ] ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:0> ] + "<STR_LIT>" ) ; return true ; } if ( ! player . hasPermission ( "<STR_LIT>" + args [ <NUM_LIT:0> ] ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:0> ] + "<STR_LIT>" ) ; return true ; } player . teleport ( getWarp ( args [ <NUM_LIT:0> ] ) . location ) ; player . sendMessage ( prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:0> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; return true ; } if ( args . length == <NUM_LIT:2> ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } Player target = getServer ( ) . getPlayer ( args [ <NUM_LIT:0> ] ) ; if ( target == null || ! target . isOnline ( ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( ! isWarp ( args [ <NUM_LIT:1> ] ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:1> ] + "<STR_LIT>" ) ; return true ; } if ( ! player . hasPermission ( "<STR_LIT>" + args [ <NUM_LIT:0> ] ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:1> ] + "<STR_LIT>" ) ; return true ; } target . teleport ( getWarp ( args [ <NUM_LIT:1> ] ) . location ) ; player . sendMessage ( prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + target . getName ( ) + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:1> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; target . sendMessage ( prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:1> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; return true ; } } if ( cmd . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) && args . length == <NUM_LIT:1> ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( args [ <NUM_LIT:0> ] . length ( ) > <NUM_LIT> ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( isWarp ( args [ <NUM_LIT:0> ] ) ) { getWarp ( args [ <NUM_LIT:0> ] ) . location = player . getLocation ( ) ; } else { addWarp ( args [ <NUM_LIT:0> ] , player . getLocation ( ) ) ; } player . sendMessage ( prefix + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:0> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; saveWarps ( ) ; return true ; } if ( cmd . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) && args . length == <NUM_LIT:1> ) { if ( ! player . hasPermission ( "<STR_LIT>" ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( ! isWarp ( args [ <NUM_LIT:0> ] ) ) { player . sendMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:0> ] + "<STR_LIT>" ) ; return true ; } removeWarp ( args [ <NUM_LIT:0> ] ) ; player . sendMessage ( prefix + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:0> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; saveWarps ( ) ; return true ; } } else { if ( cmd . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { if ( args . length == <NUM_LIT:0> ) { String list = "<STR_LIT>" ; for ( Warp w : warps ) { list += "<STR_LIT>" + w . name ; } consoleMessage ( ChatColor . DARK_AQUA + "<STR_LIT>" ) ; consoleMessage ( ChatColor . GREEN + list . substring ( <NUM_LIT:1> ) ) ; return true ; } if ( args . length == <NUM_LIT:2> ) { Player target = getServer ( ) . getPlayer ( args [ <NUM_LIT:0> ] ) ; if ( target == null || ! target . isOnline ( ) ) { consoleMessage ( ChatColor . RED + "<STR_LIT>" ) ; return true ; } if ( ! isWarp ( args [ <NUM_LIT:1> ] ) ) { consoleMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:1> ] + "<STR_LIT>" ) ; return true ; } target . teleport ( getWarp ( args [ <NUM_LIT:1> ] ) . location ) ; consoleMessage ( prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + target . getName ( ) + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:1> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; target . sendMessage ( prefix + ChatColor . GREEN + "<STR_LIT>" + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:1> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; return true ; } } if ( cmd . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) && args . length == <NUM_LIT:1> ) { if ( ! isWarp ( args [ <NUM_LIT:0> ] ) ) { consoleMessage ( ChatColor . RED + "<STR_LIT>" + args [ <NUM_LIT:0> ] + "<STR_LIT>" ) ; return true ; } removeWarp ( args [ <NUM_LIT:0> ] ) ; consoleMessage ( prefix + ChatColor . AQUA + "<STR_LIT:'>" + args [ <NUM_LIT:0> ] + "<STR_LIT:'>" + ChatColor . GREEN + "<STR_LIT>" ) ; saveWarps ( ) ; return true ; } } return false ; } public void consoleMessage ( String m ) { Bukkit . getConsoleSender ( ) . sendMessage ( m ) ; } public static boolean isWarp ( String s ) { for ( Warp w : warps ) { if ( w . name . equalsIgnoreCase ( s ) ) return true ; } return false ; } public static Warp getWarp ( String s ) { if ( isWarp ( s ) ) { for ( Warp w : warps ) { if ( w . name . equalsIgnoreCase ( s ) ) return w ; } } return null ; } public static void removeWarp ( String s ) { if ( isWarp ( s ) ) { warps . remove ( getWarp ( s ) ) ; } } public static void addWarp ( String s , Location l ) { warps . add ( new Warp ( s , l ) ) ; } public void saveWarps ( ) { String fName = "<STR_LIT>" ; ArrayList < String > format = new ArrayList < String > ( ) ; for ( Warp w : warps ) { String toAdd = w . name ; toAdd += "<STR_LIT:U+002C>" + w . location . getWorld ( ) . getName ( ) ; toAdd += "<STR_LIT:U+002C>" + w . location . getBlockX ( ) ; toAdd += "<STR_LIT:U+002C>" + w . location . getBlockY ( ) ; toAdd += "<STR_LIT:U+002C>" + w . location . getBlockZ ( ) ; toAdd += "<STR_LIT:U+002C>" + w . location . getYaw ( ) ; toAdd += "<STR_LIT:U+002C>" + w . location . getPitch ( ) ; format . add ( toAdd ) ; } File file = new File ( "<STR_LIT>" + fName ) ; new File ( "<STR_LIT>" ) . mkdir ( ) ; new File ( "<STR_LIT>" ) . mkdir ( ) ; if ( ! file . exists ( ) ) { try { file . createNewFile ( ) ; } catch ( IOException e ) { System . out . println ( "<STR_LIT>" ) ; } } try { ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( file . getAbsolutePath ( ) ) ) ; oos . writeObject ( format ) ; oos . flush ( ) ; oos . close ( ) ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" ) ; } } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void loadWarps ( ) { String fName = "<STR_LIT>" ; File file = new File ( "<STR_LIT>" + fName ) ; if ( file . exists ( ) ) { try { ObjectInputStream ois = new ObjectInputStream ( new FileInputStream ( file . getAbsolutePath ( ) ) ) ; Object result = ois . readObject ( ) ; ois . close ( ) ; if ( result != null ) { ArrayList < String > parse = ( ArrayList < String > ) result ; for ( String i : parse ) { try { String [ ] args = i . split ( "<STR_LIT:U+002C>" ) ; Location warpL = new Location ( getServer ( ) . getWorld ( args [ <NUM_LIT:1> ] ) , Integer . parseInt ( args [ <NUM_LIT:2> ] ) , Integer . parseInt ( args [ <NUM_LIT:3> ] ) , Integer . parseInt ( args [ <NUM_LIT:4> ] ) , Float . parseFloat ( args [ <NUM_LIT:5> ] ) , Float . parseFloat ( args [ <NUM_LIT:6> ] ) ) ; Warp warp = new Warp ( args [ <NUM_LIT:0> ] , warpL ) ; warps . add ( warp ) ; ois . close ( ) ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" ) ; } } } } catch ( Exception e ) { System . out . println ( "<STR_LIT>" ) ; } } } } </s>
<s> package org . wadael . gwtcleaner ; import java . io . File ; import java . io . FileFilter ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; public class Activator implements BundleActivator { static String [ ] GWT_PREFIXES = { "<STR_LIT>" , "<STR_LIT>" } ; static String FOLDER_TO_CLEAN = System . getProperty ( "<STR_LIT>" ) ; FileFilter toBeDeletedFiles_fileFilter = new FileFilter ( ) { public boolean accept ( File file ) { for ( String prefix : GWT_PREFIXES ) { if ( file . getName ( ) . startsWith ( prefix ) ) return true ; } return false ; } } ; public void start ( BundleContext context ) throws Exception { cleanGWTTempFiles ( ) ; } public void stop ( BundleContext context ) throws Exception { cleanGWTTempFiles ( ) ; } public void cleanGWTTempFiles ( ) { File toBeCleaned = new File ( FOLDER_TO_CLEAN ) ; File [ ] extraFiles = toBeCleaned . listFiles ( toBeDeletedFiles_fileFilter ) ; int counter = <NUM_LIT:0> ; int errors = <NUM_LIT:0> ; long sizesSum = <NUM_LIT:0> ; for ( File erase : extraFiles ) { long size = erase . length ( ) ; if ( erase . delete ( ) ) { sizesSum += size ; counter ++ ; } else { System . out . println ( "<STR_LIT>" + erase . getName ( ) ) ; errors ++ ; } } System . out . println ( "<STR_LIT>" + counter + "<STR_LIT>" + ( sizesSum / ( <NUM_LIT> * <NUM_LIT> ) ) + "<STR_LIT>" + errors + "<STR_LIT>" ) ; } } </s>
<s> package gov . nasa . daveml . dave2otis ; import gov . nasa . daveml . dave . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . logging . Level ; import java . util . logging . Logger ; class OtisModelWriter extends OtisWriter { BlockArrayList inputBlocks ; BlockArrayList outputBlocks ; int nextCalVarNumber ; String CLdef ; String CDdef ; String Cmdef ; static final int MAX_COMMENT_LENGTH = <NUM_LIT> ; public OtisModelWriter ( Model theModel , String sourceFileName ) throws IOException { super ( theModel , sourceFileName ) ; inputBlocks = new BlockArrayList ( <NUM_LIT:10> ) ; outputBlocks = new BlockArrayList ( <NUM_LIT:10> ) ; nextCalVarNumber = <NUM_LIT:1> ; CLdef = null ; CDdef = null ; Cmdef = null ; } public void writeln ( String cbuf ) throws IOException { super . write ( cbuf + "<STR_LIT:n>" ) ; } public void writeModel ( BlockArrayList sortedBlocks , String modelName ) throws IOException { CodeAndVarNames cvn = new CodeAndVarNames ( ) ; Iterator < Block > blkIt ; Block blk ; ourModel . setCodeDialect ( Model . DT_FORTRAN ) ; blkIt = sortedBlocks . iterator ( ) ; while ( blkIt . hasNext ( ) ) { blk = blkIt . next ( ) ; boolean skip = false ; if ( blk instanceof BlockLimiter || blk instanceof BlockMathSwitch ) blk . getOutput ( ) . clearDerivedFlag ( ) ; Signal outSig = blk . getOutput ( ) ; if ( outSig != null ) if ( outSig . isDerived ( ) ) { skip = true ; } if ( blk instanceof BlockBP ) { } else if ( blk instanceof BlockInput ) { inputBlocks . add ( blk ) ; translateInputBlockVarID ( blk ) ; skip = true ; } else if ( blk instanceof BlockOutput ) { outputBlocks . add ( blk ) ; translateOutputBlockVarID ( blk ) ; skip = true ; } else if ( blk instanceof BlockFuncTable ) { cvn . appendCode ( this . generateTableCall ( ( BlockFuncTable ) blk ) ) ; } else { if ( ! skip ) cvn . append ( blk . genCode ( ) ) ; } } writeModelHeader ( modelName ) ; writeAsOtisCalc ( cvn . getCode ( ) ) ; writeModelFooter ( modelName , "<STR_LIT>" , "<STR_LIT>" ) ; } private String generateTableCall ( BlockFuncTable bft ) { String outVarID = bft . getOutputVarID ( ) ; return outVarID + "<STR_LIT>" + outVarID + "<STR_LIT>" ; } void writeModelHeader ( String modelName ) { try { writeln ( "<STR_LIT>" + modelName + "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; int xparNumber = <NUM_LIT:1> ; Iterator < Block > blkIt = inputBlocks . iterator ( ) ; while ( blkIt . hasNext ( ) ) { Block inputBlk = blkIt . next ( ) ; Signal theSignal = inputBlk . getOutput ( ) ; if ( ! theSignal . isMarked ( ) ) { writeln ( "<STR_LIT>" + theSignal . getVarID ( ) . trim ( ) + "<STR_LIT:U+0020(>" + theSignal . getName ( ) . trim ( ) + "<STR_LIT>" ) ; String description = theSignal . getDescription ( ) . trim ( ) ; while ( description . length ( ) > ( MAX_COMMENT_LENGTH - <NUM_LIT:4> ) ) { int finalSpace = description . lastIndexOf ( "<STR_LIT:U+0020>" ) ; writeln ( "<STR_LIT>" + description . substring ( <NUM_LIT:0> , finalSpace ) ) ; description = description . substring ( finalSpace + <NUM_LIT:1> ) ; } writeln ( "<STR_LIT>" + description ) ; writeln ( "<STR_LIT:!>" ) ; String icVal = "<STR_LIT>" ; if ( theSignal . hasIC ( ) ) icVal = theSignal . getIC ( ) ; writeln ( "<STR_LIT>" + xparNumber + "<STR_LIT>" + icVal ) ; writeln ( "<STR_LIT:!>" ) ; xparNumber ++ ; } } writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; blkIt = inputBlocks . iterator ( ) ; while ( blkIt . hasNext ( ) ) { Block inputBlk = blkIt . next ( ) ; Signal theSignal = inputBlk . getOutput ( ) ; if ( ! theSignal . isMarked ( ) ) { writeln ( "<STR_LIT>" + nextCalVarNumber + "<STR_LIT>" + nextCalVarNumber + "<STR_LIT>" + theSignal . getVarID ( ) . trim ( ) + "<STR_LIT>" ) ; nextCalVarNumber ++ ; } } writeln ( "<STR_LIT:!>" ) ; } catch ( IOException ex ) { System . err . println ( "<STR_LIT>" ) ; Logger . getLogger ( OtisModelWriter . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } private void writeAsOtisCalc ( String codeBody ) throws IOException { writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; String lines [ ] = null ; try { lines = convertIfBlocks ( codeBody ) ; } catch ( DAVEException ex ) { Logger . getLogger ( OtisModelWriter . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } int numLines = lines . length ; for ( int i = <NUM_LIT:0> ; i < numLines ; i ++ ) { String equationParts [ ] = lines [ i ] . split ( "<STR_LIT:=>" ) ; if ( equationParts . length != <NUM_LIT:2> ) { System . err . println ( "<STR_LIT>" + lines [ i ] ) ; } else { boolean skip = false ; String varName = equationParts [ <NUM_LIT:0> ] ; String rhs = equationParts [ <NUM_LIT:1> ] ; if ( varName . equals ( "<STR_LIT>" ) ) { CLdef = rhs ; skip = true ; } if ( varName . equals ( "<STR_LIT>" ) ) { CDdef = rhs ; skip = true ; } if ( varName . equals ( "<STR_LIT>" ) ) { Cmdef = rhs ; skip = true ; } if ( varName . equals ( "<STR_LIT>" ) ) { skip = true ; } if ( ! skip ) { writeln ( "<STR_LIT>" + nextCalVarNumber + "<STR_LIT>" + varName + "<STR_LIT>" + rhs + "<STR_LIT>" ) ; nextCalVarNumber += <NUM_LIT:1> ; } } } writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; } private String [ ] convertIfBlocks ( String codeBody ) throws DAVEException { String line [ ] = codeBody . replace ( "<STR_LIT:U+0020>" , "<STR_LIT>" ) . split ( "<STR_LIT:n>" ) ; ArrayList < String > outLines = new ArrayList < String > ( <NUM_LIT> ) ; String parts [ ] ; String newLine = "<STR_LIT>" ; int numLines = line . length ; for ( int i = <NUM_LIT:0> ; i < ( numLines - <NUM_LIT:3> ) ; i ++ ) { if ( ( line [ i + <NUM_LIT:1> ] . startsWith ( "<STR_LIT>" ) ) && ( line [ i + <NUM_LIT:3> ] . startsWith ( "<STR_LIT>" ) ) ) { parts = line [ i ] . split ( "<STR_LIT:=>" ) ; if ( parts . length != <NUM_LIT:2> ) throw new DAVEException ( "<STR_LIT>" + i + "<STR_LIT>" + line [ i ] ) ; String varname = parts [ <NUM_LIT:0> ] ; String z = parts [ <NUM_LIT:1> ] ; parts = line [ i + <NUM_LIT:1> ] . split ( "<STR_LIT:\\.>" ) ; if ( parts . length != <NUM_LIT:3> ) throw new DAVEException ( "<STR_LIT>" + ( i + <NUM_LIT:1> ) + "<STR_LIT>" + line [ i + <NUM_LIT:1> ] ) ; String a = parts [ <NUM_LIT:0> ] . replace ( "<STR_LIT>" , "<STR_LIT>" ) ; String test = parts [ <NUM_LIT:1> ] ; String b = parts [ <NUM_LIT:2> ] . replace ( "<STR_LIT>" , "<STR_LIT>" ) ; String relTest = "<STR_LIT>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT:<>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT:>>" ; if ( test . equals ( "<STR_LIT>" ) ) relTest = "<STR_LIT>" ; String x = a + relTest + b ; parts = line [ i + <NUM_LIT:2> ] . split ( "<STR_LIT:=>" ) ; if ( parts . length != <NUM_LIT:2> ) throw new DAVEException ( "<STR_LIT>" + ( i + <NUM_LIT:2> ) + "<STR_LIT>" + line [ i + <NUM_LIT:2> ] ) ; String y = parts [ <NUM_LIT:1> ] ; newLine += x + "<STR_LIT:U+002C>" + y ; newLine = varname + "<STR_LIT>" + x + "<STR_LIT:U+002C>" + y + "<STR_LIT:U+002C>" + z + "<STR_LIT:)>" ; outLines . add ( newLine ) ; i = i + <NUM_LIT:3> ; } else { outLines . add ( line [ i ] ) ; } } outLines . add ( line [ numLines - <NUM_LIT:3> ] ) ; outLines . add ( line [ numLines - <NUM_LIT:2> ] ) ; outLines . add ( line [ numLines - <NUM_LIT:1> ] ) ; return outLines . toArray ( new String [ <NUM_LIT:0> ] ) ; } private void writeModelFooter ( String vehicleName , String vehicleWeight , String vehicleRefArea ) { try { writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" + vehicleName + "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" + vehicleRefArea + "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; int aeroNumber = <NUM_LIT:1> ; if ( CLdef != null ) { writeln ( "<STR_LIT>" + aeroNumber + "<STR_LIT>" + CLdef + "<STR_LIT>" ) ; aeroNumber ++ ; } if ( CLdef != null ) { writeln ( "<STR_LIT>" + aeroNumber + "<STR_LIT>" + CDdef + "<STR_LIT>" ) ; aeroNumber ++ ; } if ( Cmdef != null ) { writeln ( "<STR_LIT>" + aeroNumber + "<STR_LIT>" + Cmdef + "<STR_LIT>" ) ; aeroNumber ++ ; } writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" + vehicleWeight + "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT:!>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; } catch ( IOException ex ) { Logger . getLogger ( OtisModelWriter . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; System . err . println ( "<STR_LIT>" ) ; } } private void translateInputBlockVarID ( Block blk ) { String dmlVarID = blk . getOutputVarID ( ) ; if ( this . needsTranslation ( dmlVarID ) ) { String otisVarID = this . translate ( dmlVarID ) ; Signal sig = blk . getOutput ( ) ; sig . mark ( ) ; sig . setVarID ( otisVarID ) ; } } private void translateOutputBlockVarID ( Block blk ) { Signal inputSig = blk . getInput ( <NUM_LIT:0> ) ; String dmlVarID = inputSig . getVarID ( ) ; if ( this . needsTranslation ( dmlVarID ) ) { String otisVarID = this . translate ( dmlVarID ) ; inputSig . mark ( ) ; inputSig . setVarID ( otisVarID ) ; } } } </s>
<s> package gov . nasa . daveml . dave2otis ; </s>
<s> package gov . nasa . daveml . dave2otis ; import gov . nasa . daveml . dave . Model ; import gov . nasa . daveml . dave . Signal ; import java . io . FileWriter ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; public abstract class OtisWriter extends FileWriter { Map < String , String > idMap ; Model ourModel ; public OtisWriter ( Model theModel , String tableFileName ) throws IOException { super ( tableFileName ) ; ourModel = theModel ; } protected String translate ( String varID ) { String output = varID ; if ( idMap == null ) this . setupMap ( ) ; Signal signal = ourModel . getSignals ( ) . findByID ( varID ) ; if ( signal . isStdAIAA ( ) ) { String aiaaName = this . getAIAAName ( signal ) ; String otisName = idMap . get ( aiaaName ) ; if ( otisName != null ) { output = otisName ; } } return output ; } private void setupMap ( ) { idMap = new HashMap < String , String > ( ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; idMap . put ( "<STR_LIT>" , "<STR_LIT>" ) ; } private String getAIAAName ( Signal signal ) { String varName = signal . getName ( ) ; String units = signal . getUnits ( ) ; String aiaaName = varName ; String axisName = "<STR_LIT>" ; int underbar = varName . indexOf ( "<STR_LIT:_>" ) ; int varNameLen = varName . length ( ) ; if ( underbar > <NUM_LIT:0> ) { axisName = varName . substring ( underbar , ( varNameLen - underbar ) ) ; aiaaName = varName . substring ( underbar ) ; } if ( ! units . equalsIgnoreCase ( "<STR_LIT>" ) ) { aiaaName = varName + "<STR_LIT:_>" + units ; } aiaaName += axisName ; return aiaaName ; } public String normalize ( String input ) { if ( input != null ) { input = input . replace ( '<STR_LIT:\n>' , '<CHAR_LIT:U+0020>' ) ; input = input . replace ( '<STR_LIT:\t>' , '<CHAR_LIT:U+0020>' ) ; input = input . replace ( "<STR_LIT:U+0020U+0020>" , "<STR_LIT:U+0020>" ) ; input = input . replace ( "<STR_LIT:U+0020U+0020>" , "<STR_LIT:U+0020>" ) ; } return input ; } public boolean needsTranslation ( String varID ) { String output = varID ; if ( idMap == null ) this . setupMap ( ) ; Signal signal = ourModel . getSignals ( ) . findByID ( varID ) ; if ( signal . isStdAIAA ( ) ) { String aiaaName = this . getAIAAName ( signal ) ; String otisName = idMap . get ( aiaaName ) ; if ( otisName != null ) { return true ; } } return false ; } } </s>
<s> package gov . nasa . daveml . dave2otis ; import gov . nasa . daveml . dave . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . logging . Level ; import java . util . logging . Logger ; class OtisTableWriter extends OtisWriter { int tableNumber , tableRefNumber ; int lineWrapLen ; BlockFuncTable bft ; FuncTable ft ; String outVarID ; String outOtisName ; String indent ; int [ ] dims ; int [ ] coords ; int numDims ; public OtisTableWriter ( Model theModel , String tableFileName ) throws IOException { super ( theModel , tableFileName ) ; indent = "<STR_LIT>" ; lineWrapLen = <NUM_LIT> ; ft = null ; outVarID = "<STR_LIT>" ; outOtisName = "<STR_LIT>" ; dims = null ; numDims = - <NUM_LIT:1> ; idMap = null ; } private void writeln ( String cbuf ) throws IOException { super . write ( cbuf + "<STR_LIT:n>" ) ; } private void writeln ( ) throws IOException { this . writeln ( "<STR_LIT>" ) ; } void generateTableDescription ( ) { ft = bft . getFunctionTableDef ( ) ; outVarID = bft . getOutputVarID ( ) ; outOtisName = outVarID ; dims = ft . getDimensions ( ) ; numDims = dims . length ; try { this . writeTable ( ) ; } catch ( IOException ex ) { Logger . getLogger ( OtisTableWriter . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } private void writeTable ( ) throws IOException { writeln ( "<STR_LIT>" ) ; writeln ( indent + outVarID ) ; writeln ( "<STR_LIT>" ) ; writeln ( indent + outOtisName ) ; writeln ( "<STR_LIT>" ) ; writeln ( indent + "<STR_LIT:1.0>" ) ; writeln ( "<STR_LIT>" ) ; String descr = bft . getDescription ( ) ; this . writeTextComment ( normalize ( descr ) ) ; writeln ( "<STR_LIT>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( indent + "<STR_LIT:1>" ) ; writeln ( "<STR_LIT>" ) ; writeln ( indent + "<STR_LIT>" ) ; write ( indent + "<STR_LIT>" ) ; if ( numDims == <NUM_LIT:1> ) write ( "<STR_LIT>" ) ; else write ( numDims + "<STR_LIT>" ) ; for ( int dim = numDims ; dim >= <NUM_LIT:1> ; dim -- ) { write ( bft . getVarID ( dim ) ) ; if ( dim > <NUM_LIT:2> ) write ( "<STR_LIT:U+002CU+0020>" ) ; if ( dim == <NUM_LIT:2> ) write ( "<STR_LIT:U+0020andU+0020>" ) ; } writeln ( ) ; writeln ( indent + numDims ) ; this . writeIndependentValues ( ) ; this . writeDependentValues ( ) ; writeln ( "<STR_LIT:*>" ) ; writeln ( "<STR_LIT>" ) ; } private void writeIndependentValues ( ) throws IOException { for ( int dim = numDims ; dim >= <NUM_LIT:1> ; dim -- ) { String inVarID = bft . getVarID ( dim ) ; String inOtisName = inVarID ; String bpID = ft . getBPID ( dim ) ; ArrayList < Double > bps = ourModel . getBPSetByID ( bpID ) . values ( ) ; Iterator < Double > bpIt = bps . iterator ( ) ; writeln ( indent + inOtisName ) ; writeln ( indent + "<STR_LIT>" + inOtisName + "<STR_LIT:s>" ) ; writeln ( indent + bps . size ( ) ) ; writeln ( indent + "<STR_LIT>" + inOtisName + "<STR_LIT>" ) ; String origIndent = indent ; indent = indent + "<STR_LIT>" ; String buffer = indent ; while ( bpIt . hasNext ( ) ) { double breakpointVal = bpIt . next ( ) ; String testBuffer = buffer + breakpointVal + "<STR_LIT:U+0020U+0020>" ; if ( testBuffer . length ( ) > lineWrapLen ) { writeln ( buffer ) ; buffer = indent + breakpointVal + "<STR_LIT:U+0020U+0020>" ; } else { buffer = testBuffer ; } } writeln ( buffer ) ; indent = origIndent ; } } private void writeDependentValues ( ) throws IOException { ArrayList < Double > pts = ft . getValues ( ) ; Iterator < Double > ptIt = pts . iterator ( ) ; coords = dims . clone ( ) ; for ( int i = <NUM_LIT:0> ; i < coords . length ; i ++ ) { coords [ i ] = <NUM_LIT:0> ; } write ( indent + "<STR_LIT>" + outOtisName + "<STR_LIT>" ) ; if ( numDims > <NUM_LIT:1> ) writeln ( "<STR_LIT>" + bft . getVarID ( numDims ) ) ; else writeln ( ) ; writeIndepValsWithHdr ( ptIt , <NUM_LIT:1> ) ; } private void writeIndepValsWithHdr ( Iterator < Double > ptIt , int dim ) throws IOException { if ( dim < numDims ) { String bpID = ft . getBPID ( dim ) ; ArrayList < Double > bps = ourModel . getBPSetByID ( bpID ) . values ( ) ; for ( int i = <NUM_LIT:0> ; i < bps . size ( ) ; i ++ ) { coords [ dim ] = i ; double bpVal = bps . get ( coords [ dim ] ) ; writeln ( indent + "<STR_LIT>" + bft . getVarID ( dim ) + "<STR_LIT:U+0020=U+0020>" + bpVal + "<STR_LIT:U+0020>" ) ; writeIndepValsWithHdr ( ptIt , dim + <NUM_LIT:1> ) ; } } else { String lastBpID = ft . getBPID ( numDims ) ; int numLastBps = ourModel . getBPSetByID ( lastBpID ) . values ( ) . size ( ) ; String buffer = indent + "<STR_LIT:U+0020U+0020>" ; for ( int i = <NUM_LIT:0> ; i < numLastBps ; i ++ ) { double val = ptIt . next ( ) ; String testBuffer = buffer + val + "<STR_LIT:U+0020U+0020>" ; if ( testBuffer . length ( ) > lineWrapLen ) { writeln ( buffer ) ; buffer = indent + "<STR_LIT:U+0020U+0020>" + val + "<STR_LIT:U+0020U+0020>" ; } else { buffer = testBuffer ; } } writeln ( buffer ) ; } } private void writeTextComment ( String input ) throws IOException { String buffer = "<STR_LIT>" ; String testBuffer ; if ( input != null ) { input = normalize ( input ) ; String [ ] word = input . split ( "<STR_LIT:U+0020>" ) ; buffer = indent + "<STR_LIT:*>" ; for ( int i = <NUM_LIT:0> ; i < word . length ; i ++ ) { testBuffer = buffer + "<STR_LIT:U+0020>" + word [ i ] ; if ( testBuffer . length ( ) > lineWrapLen ) { writeln ( buffer ) ; buffer = indent + "<STR_LIT>" + word [ i ] ; } else { buffer = testBuffer ; } } } writeln ( buffer ) ; } void writeTables ( BlockArrayList blocks ) { Iterator < Block > it = blocks . iterator ( ) ; while ( it . hasNext ( ) ) { Block blk = it . next ( ) ; if ( blk instanceof BlockFuncTable ) { bft = ( BlockFuncTable ) blk ; this . generateTableDescription ( ) ; } } } } </s>
<s> package gov . nasa . daveml . dave2otis ; import gov . nasa . daveml . dave . * ; import java . io . File ; import java . io . IOException ; import java . util . Iterator ; import java . util . logging . Level ; import java . util . logging . Logger ; public class DAVE2OTIS extends DAVE { String tableFileName ; String modelFileName ; public DAVE2OTIS ( ) { super ( ) ; } public DAVE2OTIS ( String [ ] args ) { this ( ) ; this . parseOptions ( args ) ; if ( this . isVerbose ( ) ) { this . getModel ( ) . makeVerbose ( ) ; } } @ Override public void setInputFileName ( String fn ) { super . setInputFileName ( fn ) ; this . tableFileName = this . getStubName ( ) + "<STR_LIT>" ; this . modelFileName = this . getStubName ( ) + "<STR_LIT>" ; } private void parseOptions ( String inArgs [ ] ) { String exampleUse = "<STR_LIT>" ; int numArgs = inArgs . length ; this . setArgs ( inArgs ) ; if ( numArgs > <NUM_LIT:0> ) { int parsedArgs = <NUM_LIT:0> ; if ( this . matchOptionArgs ( "<STR_LIT:c>" , "<STR_LIT:count>" ) ) { this . setGenStatsFlag ( ) ; parsedArgs ++ ; } if ( this . matchOptionArgs ( "<STR_LIT:d>" , "<STR_LIT>" ) ) { this . makeVerbose ( ) ; parsedArgs ++ ; } if ( matchOptionArgs ( "<STR_LIT>" , "<STR_LIT:version>" ) ) { System . out . println ( "<STR_LIT>" + getVersion ( ) ) ; System . exit ( <NUM_LIT:0> ) ; } if ( parsedArgs < ( numArgs - <NUM_LIT:1> ) ) { if ( numArgs == <NUM_LIT:2> ) { System . err . println ( "<STR_LIT>" + getArgs ( ) [ <NUM_LIT:2> ] + "<STR_LIT>" ) ; } else { System . err . println ( "<STR_LIT>" + ( numArgs - <NUM_LIT:1> ) + "<STR_LIT>" ) ; } System . err . println ( exampleUse ) ; System . exit ( <NUM_LIT:0> ) ; } } else { System . out . println ( exampleUse ) ; System . out . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } this . setInputFileName ( inArgs [ numArgs - <NUM_LIT:1> ] ) ; } public void createModel ( ) throws IOException { Model theModel = this . getModel ( ) ; File file = new File ( this . getStubName ( ) ) ; String modelName = file . getName ( ) ; theModel . clearSelections ( ) ; if ( ! theModel . selectOutputByName ( "<STR_LIT>" ) ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } if ( ! theModel . selectOutputByName ( "<STR_LIT>" ) ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } OtisTableWriter tableWriter = new OtisTableWriter ( theModel , this . tableFileName ) ; OtisModelWriter modelWriter = new OtisModelWriter ( theModel , this . modelFileName ) ; BlockArrayList sortedBlocks = null ; try { sortedBlocks = theModel . getSelectedBlocks ( ) ; if ( sortedBlocks == null ) { System . err . println ( "<STR_LIT>" + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } if ( sortedBlocks . isEmpty ( ) ) { System . err . println ( "<STR_LIT>" + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } } catch ( DAVEException ex ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } modelWriter . writeModel ( sortedBlocks , modelName ) ; tableWriter . writeTables ( sortedBlocks ) ; tableWriter . close ( ) ; modelWriter . close ( ) ; } public static void main ( String args [ ] ) { boolean success = false ; DAVE2OTIS dave2otis = new DAVE2OTIS ( args ) ; try { System . out . println ( "<STR_LIT>" ) ; success = dave2otis . parseFile ( ) ; } catch ( Exception e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; } if ( ! success ) { System . out . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } System . out . println ( "<STR_LIT>" ) ; try { if ( dave2otis . hasCheckcases ( ) ) { System . out . println ( "<STR_LIT>" ) ; if ( ! dave2otis . verify ( ) ) { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } } } catch ( NoSuchMethodError e ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } try { if ( dave2otis . getGenStatsFlag ( ) ) { dave2otis . reportStats ( ) ; } } catch ( NoSuchMethodError e ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:1> ) ; } System . out . println ( "<STR_LIT>" ) ; try { dave2otis . createModel ( ) ; } catch ( IOException e ) { return ; } System . out . println ( "<STR_LIT>" + dave2otis . getStubName ( ) + "<STR_LIT:.>" ) ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import gov . nasa . daveml . dave . NameList ; @ SuppressWarnings ( "<STR_LIT:serial>" ) public class MDLNameList extends NameList { public MDLNameList ( ) { super ( ) ; } public MDLNameList ( int initialCapacity ) { super ( initialCapacity ) ; } public static String convertToMDLString ( String s ) { StringBuffer sb = new StringBuffer ( s ) ; for ( int i = <NUM_LIT:0> ; i < s . length ( ) ; i ++ ) { switch ( sb . charAt ( i ) ) { case '<CHAR_LIT:U+0020>' : case '<CHAR_LIT:->' : case '<CHAR_LIT::>' : case '<CHAR_LIT:/>' : case '<STR_LIT:\\>' : case '<CHAR_LIT>' : case '<CHAR_LIT:(>' : case '<CHAR_LIT:)>' : case '<CHAR_LIT:[>' : case '<CHAR_LIT:]>' : case '<CHAR_LIT>' : case '<CHAR_LIT:}>' : case '<CHAR_LIT>' : case '<CHAR_LIT>' : case '<CHAR_LIT>' : case '<CHAR_LIT:U+002C>' : case '<CHAR_LIT:.>' : case '<CHAR_LIT>' : case '<CHAR_LIT:;>' : case '<CHAR_LIT>' : case '<CHAR_LIT>' : case '<CHAR_LIT>' : case '<CHAR_LIT>' : sb . setCharAt ( i , '<CHAR_LIT:_>' ) ; break ; default : } } return sb . toString ( ) ; } public String fixName ( String s ) { return convertToMDLString ( s ) ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import gov . nasa . daveml . dave . * ; import java . util . ArrayList ; import java . util . Iterator ; import java . io . PrintStream ; import java . io . IOException ; public class SLDiagram { Model model ; ArrayList < SLRowColumnVector > rows ; ArrayList < SLRowColumnVector > cols ; ArrayList < SLCell > cells ; ArrayList < SLBlock > slblockList ; ArrayList < String > inputNames ; ArrayList < String > outputNames ; boolean verboseFlag ; double SLversion ; boolean warnOnClip ; boolean resetOutputsWhenDisabled ; boolean makeLib ; boolean makeEnabledSubSys ; static int padding = <NUM_LIT:20> ; static int xMargin = <NUM_LIT:10> ; static int yMargin = <NUM_LIT:10> ; public SLDiagram ( Model theModel ) { int row = <NUM_LIT:0> ; SLBlock slb = null ; this . inputNames = new ArrayList < String > ( <NUM_LIT:20> ) ; this . outputNames = new ArrayList < String > ( <NUM_LIT:20> ) ; this . SLversion = <NUM_LIT> ; this . warnOnClip = false ; this . resetOutputsWhenDisabled = true ; this . makeLib = false ; this . makeEnabledSubSys = false ; if ( theModel . isVerbose ( ) ) this . makeVerbose ( ) ; if ( this . isVerbose ( ) ) System . out . println ( "<STR_LIT>" ) ; this . model = theModel ; this . slblockList = new ArrayList < SLBlock > ( this . model . getNumBlocks ( ) ) ; MDLNameList nl = new MDLNameList ( this . model . getNumBlocks ( ) ) ; if ( this . isVerbose ( ) ) System . out . println ( "<STR_LIT>" + this . model . getNumBlocks ( ) + "<STR_LIT>" ) ; BlockArrayList bal = this . model . getBlocks ( ) ; if ( bal == null ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } for ( Iterator < Block > iBlks = bal . iterator ( ) ; iBlks . hasNext ( ) ; ) { Block b = iBlks . next ( ) ; if ( b != null ) { slb = new SLBlock ( this , b ) ; b . setMask ( slb ) ; } else { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } try { b . setNameList ( nl ) ; } catch ( Exception e ) { System . err . println ( "<STR_LIT>" + b . getType ( ) + "<STR_LIT>" + b . getName ( ) + "<STR_LIT>" ) ; } this . slblockList . add ( slb ) ; } for ( Iterator < SLBlock > islb = this . slblockList . iterator ( ) ; islb . hasNext ( ) ; ) { slb = islb . next ( ) ; slb . findChildren ( ) ; Block b = slb . getBlock ( ) ; if ( b == null ) { System . err . println ( "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } if ( ( b instanceof BlockInput ) || ( b instanceof BlockMathConstant ) ) { row = slb . setPosition ( row + <NUM_LIT:1> , <NUM_LIT:1> ) ; } } int numRows = <NUM_LIT:1> ; int numCols = <NUM_LIT:1> ; Iterator < SLBlock > iblk = this . slblockList . iterator ( ) ; while ( iblk . hasNext ( ) ) { slb = iblk . next ( ) ; int theRow = slb . getRow ( ) ; int theCol = slb . getCol ( ) ; if ( theRow > numRows ) numRows = theRow ; if ( theCol > numCols ) numCols = theCol ; } if ( this . isVerbose ( ) ) { System . out . print ( "<STR_LIT>" + numRows + "<STR_LIT>" ) ; System . out . println ( "<STR_LIT:U+0020>" + numCols + "<STR_LIT>" ) ; } this . rows = new ArrayList < SLRowColumnVector > ( numRows + <NUM_LIT:1> ) ; this . cols = new ArrayList < SLRowColumnVector > ( numCols + <NUM_LIT:1> ) ; this . cells = new ArrayList < SLCell > ( numRows * numCols ) ; for ( int i = <NUM_LIT:0> ; i < numRows ; i ++ ) this . rows . add ( i , new SLRowColumnVector ( numCols + <NUM_LIT:1> , true ) ) ; for ( int i = <NUM_LIT:0> ; i < numCols ; i ++ ) this . cols . add ( i , new SLRowColumnVector ( numRows + <NUM_LIT:1> , false ) ) ; iblk = this . slblockList . iterator ( ) ; while ( iblk . hasNext ( ) ) { slb = iblk . next ( ) ; SLCell cell = new SLCell ( slb , this ) ; this . cells . add ( cell ) ; int rowIndex = slb . getRow ( ) - <NUM_LIT:1> ; int colIndex = slb . getCol ( ) - <NUM_LIT:1> ; SLRowColumnVector rowv = this . rows . get ( rowIndex ) ; SLRowColumnVector colv = this . cols . get ( colIndex ) ; rowv . set ( colIndex , cell ) ; colv . set ( rowIndex , cell ) ; } } void setWarnOnClip ( ) { this . warnOnClip = true ; } boolean getWarnOnClip ( ) { return this . warnOnClip ; } void setVerFlag4 ( ) { this . SLversion = <NUM_LIT> ; } boolean getVerFlag4 ( ) { return this . SLversion == <NUM_LIT> ; } void setVerFlag5 ( ) { this . SLversion = <NUM_LIT> ; } boolean getVerFlag5 ( ) { return this . SLversion == <NUM_LIT> ; } void setLibFlag ( ) { this . makeLib = true ; } boolean getLibFlag ( ) { return this . makeLib ; } void setEnabledFlag ( ) { this . makeEnabledSubSys = true ; } boolean getEnabledFlag ( ) { return this . makeEnabledSubSys ; } public int getPadding ( ) { return SLDiagram . padding ; } public int getNumInputs ( ) { return this . model . getNumInputBlocks ( ) ; } public int getNumOutputs ( ) { return this . model . getNumOutputBlocks ( ) ; } public void makeVerbose ( ) { this . verboseFlag = true ; if ( rows != null ) { Iterator < SLRowColumnVector > it = rows . iterator ( ) ; while ( it . hasNext ( ) ) { SLRowColumnVector dude = it . next ( ) ; dude . makeVerbose ( ) ; } } if ( cols != null ) { Iterator < SLRowColumnVector > it = cols . iterator ( ) ; while ( it . hasNext ( ) ) { SLRowColumnVector dude = it . next ( ) ; dude . makeVerbose ( ) ; } } if ( slblockList != null ) { Iterator < SLBlock > it = slblockList . iterator ( ) ; while ( it . hasNext ( ) ) { SLBlock dude = it . next ( ) ; dude . makeVerbose ( ) ; } } } public boolean isVerbose ( ) { return this . verboseFlag ; } public void silence ( ) { this . verboseFlag = false ; if ( rows != null ) { Iterator < SLRowColumnVector > it = rows . iterator ( ) ; while ( it . hasNext ( ) ) { SLRowColumnVector dude = it . next ( ) ; dude . makeVerbose ( ) ; } } if ( cols != null ) { Iterator < SLRowColumnVector > it = cols . iterator ( ) ; while ( it . hasNext ( ) ) { SLRowColumnVector dude = it . next ( ) ; dude . makeVerbose ( ) ; } } if ( slblockList != null ) { Iterator < SLBlock > it = slblockList . iterator ( ) ; while ( it . hasNext ( ) ) { SLBlock dude = it . next ( ) ; dude . makeVerbose ( ) ; } } } public SLCell getCell ( int rowIndex , int colIndex ) { SLRowColumnVector row = this . rows . get ( rowIndex ) ; SLCell theCell = row . get ( colIndex ) ; return theCell ; } public SLCell getCell ( SLBlock b ) { int rowIndex = b . getRow ( ) - <NUM_LIT:1> ; int colIndex = b . getCol ( ) - <NUM_LIT:1> ; return this . getCell ( rowIndex , colIndex ) ; } public SLRowColumnVector getRow ( int index ) { return this . rows . get ( index ) ; } public SLRowColumnVector getCol ( int index ) { return this . cols . get ( index ) ; } public void addInput ( int seqNum , String name ) { if ( seqNum < <NUM_LIT:1> ) { System . err . println ( "<STR_LIT>" + name + "<STR_LIT>" + seqNum + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } while ( inputNames . size ( ) < seqNum ) inputNames . add ( null ) ; this . inputNames . set ( seqNum - <NUM_LIT:1> , name ) ; } public ArrayList < String > getInputNames ( ) { return this . inputNames ; } public void addOutput ( int seqNum , String name ) { if ( seqNum < <NUM_LIT:1> ) { System . err . println ( "<STR_LIT>" + name + "<STR_LIT>" + seqNum + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } while ( outputNames . size ( ) < seqNum ) outputNames . add ( null ) ; this . outputNames . set ( seqNum - <NUM_LIT:1> , name ) ; } public ArrayList < String > getOutputNames ( ) { return this . outputNames ; } public void describeSelf ( PrintStream printer ) { final int width = <NUM_LIT:3> ; printer . println ( ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; printer . print ( "<STR_LIT:U+0020>" ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; for ( int k = <NUM_LIT:0> ; k < width ; k ++ ) printer . print ( "<STR_LIT:U+0020>" ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; for ( int j = <NUM_LIT:0> ; j < cols . size ( ) ; j ++ ) { SLRowColumnVector col = cols . get ( j ) ; printer . print ( col . cableTray . size ( ) ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; for ( int k = <NUM_LIT:0> ; k < width ; k ++ ) printer . print ( "<STR_LIT:U+0020>" ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; } for ( int i = <NUM_LIT:0> ; i < rows . size ( ) ; i ++ ) { SLRowColumnVector row = rows . get ( i ) ; printer . println ( ) ; printer . print ( "<STR_LIT>" ) ; for ( int j = <NUM_LIT:0> ; j < cols . size ( ) ; j ++ ) { SLCell cell = row . get ( j ) ; if ( cell != null ) { SLBlock b = cell . getBlock ( ) ; printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; if ( b == null ) for ( int k = <NUM_LIT:0> ; k < width ; k ++ ) printer . print ( "<STR_LIT:U+0020>" ) ; else { String s = b . getName ( ) ; if ( s . length ( ) < width ) { printer . print ( s ) ; for ( int k = <NUM_LIT:0> ; k < ( width - s . length ( ) ) ; k ++ ) printer . print ( "<STR_LIT:U+0020>" ) ; } else printer . print ( s . substring ( <NUM_LIT:0> , width ) ) ; } } else { printer . print ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; for ( int k = <NUM_LIT:0> ; k < width ; k ++ ) printer . print ( "<STR_LIT:U+0020>" ) ; } printer . print ( "<STR_LIT>" ) ; } printer . print ( "<STR_LIT:n>" + row . cableTray . size ( ) ) ; } printer . println ( ) ; printer . println ( ) ; } public void createModel ( SLFileWriter writer , MatFileWriter mWriter ) throws IOException { for ( int i = <NUM_LIT:0> ; i < rows . size ( ) ; i ++ ) { SLRowColumnVector row = rows . get ( i ) ; for ( int j = <NUM_LIT:0> ; j < cols . size ( ) ; j ++ ) { SLCell cell = row . get ( j ) ; if ( cell != null ) { SLBlock b = cell . getBlock ( ) ; int oldRow = b . getRow ( ) ; int oldCol = b . getCol ( ) ; if ( oldRow != i + <NUM_LIT:1> ) System . err . println ( "<STR_LIT>" + b . getName ( ) + "<STR_LIT:U+0020toU+0020>" + ( i + <NUM_LIT:1> ) + "<STR_LIT>" + oldRow ) ; if ( oldCol != j + <NUM_LIT:1> ) System . err . println ( "<STR_LIT>" + b . getName ( ) + "<STR_LIT:U+0020toU+0020>" + ( j + <NUM_LIT:1> ) + "<STR_LIT>" + oldCol ) ; b . setRowCol ( i + <NUM_LIT:1> , j + <NUM_LIT:1> ) ; } } } int rowOffset = xMargin ; for ( int rowIndex = <NUM_LIT:0> ; rowIndex < this . rows . size ( ) ; rowIndex ++ ) { int rowSize = this . getRow ( rowIndex ) . getSize ( ) ; int y = rowOffset + rowSize / <NUM_LIT:2> ; int colOffset = yMargin ; for ( int colIndex = <NUM_LIT:0> ; colIndex < this . cols . size ( ) ; colIndex ++ ) { int colSize = this . getCol ( colIndex ) . getSize ( ) ; int x = colOffset + colSize / <NUM_LIT:2> ; SLCell theCell = this . getCell ( rowIndex , colIndex ) ; if ( theCell != null ) { SLBlock theBlock = theCell . getBlock ( ) ; if ( theBlock != null ) { theBlock . createM ( writer , x , y ) ; theBlock . writeMat ( mWriter ) ; } } colOffset = colOffset + colSize ; } rowOffset = rowOffset + rowSize ; } SignalArrayList sigs = model . getSignals ( ) ; Iterator < Signal > isig = sigs . iterator ( ) ; while ( isig . hasNext ( ) ) { Signal oldSig = isig . next ( ) ; SLSignal newSig = new SLSignal ( oldSig , this ) ; newSig . createAddLine ( writer ) ; } } } </s>
<s> package gov . nasa . daveml . dave2sl ; public class SLCell { SLDiagram myParent ; SLBlock myBlock ; SLRowColumnVector myRow ; SLRowColumnVector myCol ; public SLCell ( ) { myParent = null ; myBlock = null ; } public SLCell ( SLBlock b , SLDiagram theDiagram ) { this ( ) ; this . myBlock = b ; this . myParent = theDiagram ; } public SLBlock getBlock ( ) { return this . myBlock ; } public int getRowIndex ( ) { return myCol . getOffset ( this ) ; } public int getColIndex ( ) { return myRow . getOffset ( this ) ; } public SLRowColumnVector getRow ( ) { return this . myRow ; } public SLRowColumnVector getCol ( ) { return this . myCol ; } public SLCell previousCellInColumn ( ) { return myParent . getCell ( this . getRowIndex ( ) - <NUM_LIT:1> , this . getColIndex ( ) ) ; } public SLCell previousCellInRow ( ) { return myParent . getCell ( this . getRowIndex ( ) , this . getColIndex ( ) - <NUM_LIT:1> ) ; } public SLCell nextCellInColumn ( ) { return myParent . getCell ( this . getRowIndex ( ) + <NUM_LIT:1> , this . getColIndex ( ) ) ; } public SLCell nextCellInRow ( ) { return myParent . getCell ( this . getRowIndex ( ) , this . getColIndex ( ) + <NUM_LIT:1> ) ; } public void setRow ( SLRowColumnVector theRow ) { this . myRow = theRow ; } public void setCol ( SLRowColumnVector theCol ) { this . myCol = theCol ; } public int getMinWidth ( ) { return this . myBlock . getMDLWidth ( ) + <NUM_LIT:2> * this . myParent . getPadding ( ) ; } public int getMinHeight ( ) { return this . myBlock . getMDLHeight ( ) + this . myParent . getPadding ( ) ; } public int getWidth ( ) { return myCol . getSize ( ) ; } public int getHeight ( ) { return myRow . getSize ( ) ; } public int distToEdge ( ) { return ( this . getWidth ( ) - this . myBlock . getMDLWidth ( ) ) / <NUM_LIT:2> ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import java . util . ArrayList ; @ SuppressWarnings ( "<STR_LIT:serial>" ) public class SLCableTray extends ArrayList < Object > { static int offset = <NUM_LIT:5> ; public SLCableTray ( ) { super ( ) ; } public SLCableTray ( int count ) { super ( count ) ; } public boolean add ( Object theObject ) { if ( ! this . contains ( theObject ) ) return super . add ( theObject ) ; return false ; } public int getSize ( ) { if ( this . size ( ) > <NUM_LIT:0> ) return ( this . size ( ) - <NUM_LIT:1> ) * offset ; else return <NUM_LIT:0> ; } public int getStandoff ( SLSignal theSignal ) { return this . indexOf ( theSignal ) * offset ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import java . util . Vector ; public class SLRowColumnVector { Vector < SLCell > cells ; SLCableTray cableTray ; boolean isRow ; boolean verboseFlag ; public SLRowColumnVector ( int numCells , boolean asRow ) { int numTrays = <NUM_LIT:5> ; this . cells = new Vector < SLCell > ( numCells ) ; this . cells . setSize ( numCells ) ; this . cableTray = new SLCableTray ( numTrays ) ; this . isRow = asRow ; this . verboseFlag = false ; } public void set ( int offset , SLCell cell ) { if ( offset > this . cells . size ( ) ) this . cells . setSize ( offset ) ; this . cells . set ( offset , cell ) ; if ( this . isRow ) cell . setRow ( this ) ; else cell . setCol ( this ) ; } public SLCell get ( int offset ) { if ( offset > this . cells . size ( ) ) return null ; return this . cells . get ( offset ) ; } public int getOffset ( SLCell theCell ) { return cells . indexOf ( theCell ) ; } public int getSize ( ) { int theSize = this . getSizeNoTray ( ) + this . cableTray . getSize ( ) ; return theSize ; } public int getSizeNoTray ( ) { int mySize = <NUM_LIT:0> ; int cellSize = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < cells . size ( ) ; i ++ ) { SLCell theCell = cells . get ( i ) ; if ( theCell != null ) { if ( this . isRow ) cellSize = ( cells . get ( i ) ) . getMinHeight ( ) ; else cellSize = ( cells . get ( i ) ) . getMinWidth ( ) ; if ( cellSize > mySize ) mySize = cellSize ; } } return mySize ; } public SLCableTray getTray ( ) { return this . cableTray ; } public Integer addToTray ( SLSignal theSignal ) { this . cableTray . add ( theSignal ) ; int theOffset = this . cableTray . indexOf ( theSignal ) ; return new Integer ( theOffset ) ; } public void makeVerbose ( ) { this . verboseFlag = true ; } public boolean isVerbose ( ) { return this . verboseFlag ; } public void silence ( ) { this . verboseFlag = false ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import gov . nasa . daveml . dave . * ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . io . Writer ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . HashSet ; public class SLBlock { SLDiagram ourDiagram ; Block block ; BlockArrayList children ; int rowDepthOfChildren ; int myRow ; int myCol ; int mdlHeight ; int mdlWidth ; int xPad ; int yPad ; HashSet < String > writtenTables ; boolean verboseFlag ; public SLBlock ( ) { this . myRow = <NUM_LIT:0> ; this . myCol = <NUM_LIT:0> ; this . children = new BlockArrayList ( <NUM_LIT:10> ) ; this . rowDepthOfChildren = <NUM_LIT:0> ; this . writtenTables = new HashSet < String > ( <NUM_LIT:10> ) ; this . verboseFlag = false ; } public SLBlock ( SLDiagram diagram , Block b ) { this ( ) ; this . ourDiagram = diagram ; this . block = b ; mdlHeight = <NUM_LIT:30> ; mdlWidth = <NUM_LIT:30> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:0> ; if ( b instanceof BlockBP ) { mdlHeight = <NUM_LIT> ; mdlWidth = <NUM_LIT> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:0> ; } else if ( b instanceof BlockFuncTable ) { mdlHeight = <NUM_LIT> ; mdlWidth = <NUM_LIT> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:0> ; } else if ( b instanceof BlockInput ) { mdlHeight = <NUM_LIT> ; mdlWidth = <NUM_LIT:30> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:8> ; } else if ( b instanceof BlockOutput ) { mdlHeight = <NUM_LIT> ; mdlWidth = <NUM_LIT:30> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:0> ; } else if ( b instanceof BlockMathConstant ) { mdlHeight = <NUM_LIT:30> ; mdlWidth = <NUM_LIT> ; xPad = <NUM_LIT:0> ; yPad = <NUM_LIT:0> ; } int numInputs = this . block . numInputs ( ) ; if ( numInputs > <NUM_LIT:1> ) { int minHt = <NUM_LIT:24> + <NUM_LIT:15> * ( numInputs - <NUM_LIT:1> ) ; if ( minHt > mdlHeight ) mdlHeight = minHt ; } } public void createM ( SLFileWriter writer , int x , int y ) throws IOException { if ( this . block instanceof BlockBP ) { writeMforBP ( writer , x , y ) ; } else if ( this . block instanceof BlockFuncTable ) { writeMforBFT ( writer , x , y ) ; } else if ( this . block instanceof BlockInput ) { writeMforIn ( writer , x , y ) ; } else if ( this . block instanceof BlockMathAbs ) { writeMforAbs ( writer , x , y ) ; } else if ( this . block instanceof BlockMathConstant ) { writeMforConst ( writer , x , y ) ; } else if ( this . block instanceof BlockMathFunction ) { writeMforFunc ( writer , x , y ) ; } else if ( this . block instanceof BlockMathMinus ) { writeMforMinus ( writer , x , y ) ; } else if ( this . block instanceof BlockMathMinmax ) { writeMforMinmax ( writer , x , y ) ; } else if ( this . block instanceof BlockMathProduct ) { writeMforMult ( writer , x , y ) ; } else if ( this . block instanceof BlockMathRelation ) { writeMforRelation ( writer , x , y ) ; } else if ( this . block instanceof BlockMathSum ) { writeMforSum ( writer , x , y ) ; } else if ( this . block instanceof BlockMathSwitch ) { writeMforSwitch ( writer , x , y ) ; } else if ( this . block instanceof BlockOutput ) { writeMforOut ( writer , x , y ) ; } else if ( this . block instanceof BlockLimiter ) { writeMforLimit ( writer , x , y ) ; } else { writer . writeln ( "<STR_LIT>" ) ; writer . writeln ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; writer . writeln ( "<STR_LIT>" + this . block . getType ( ) + "<STR_LIT>" ) ; writer . writeln ( "<STR_LIT>" + this . block . getType ( ) + "<STR_LIT>" + this . block . getName ( ) + "<STR_LIT>" ) ; writer . writeln ( "<STR_LIT>" ) ; System . err . println ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; } } public void writeMforLimit ( SLFileWriter writer , int x , int y ) throws IOException { BlockLimiter bl = ( BlockLimiter ) this . getBlock ( ) ; String lowerLim = "<STR_LIT>" ; String upperLim = "<STR_LIT>" ; if ( bl . hasLowerLimit ( ) ) lowerLim = Double . toString ( bl . getLowerLimit ( ) ) ; if ( bl . hasUpperLimit ( ) ) upperLim = Double . toString ( bl . getUpperLimit ( ) ) ; String paramString = "<STR_LIT>" + "<STR_LIT>" + lowerLim + "<STR_LIT>" + upperLim + "<STR_LIT>" + "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforBP ( SLFileWriter writer , int x , int y ) throws IOException { String blockType = "<STR_LIT>" ; String paramString = "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBlock ( blockType , this . getName ( ) , paramString ) ; writer . writeln ( "<STR_LIT>" + ourDiagram . model . getName ( ) + "<STR_LIT>" + MDLNameList . convertToMDLString ( this . getName ( ) ) + "<STR_LIT>" ) ; String maskValues = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; if ( this . ourDiagram . getWarnOnClip ( ) ) maskValues += "<STR_LIT>" ; else maskValues += "<STR_LIT>" ; maskValues += "<STR_LIT:}>" ; writer . setParam ( this . getName ( ) , "<STR_LIT>" , maskValues ) ; writer . writeln ( "<STR_LIT>" ) ; } public void writeMforBFT ( SLFileWriter writer , int x , int y ) throws IOException { BlockFuncTable bft = ( BlockFuncTable ) this . getBlock ( ) ; bft . reorderInputsForMDL ( ) ; FuncTable ft = bft . getFunctionTableDef ( ) ; int numDim = ft . numDim ( ) ; String blockType = "<STR_LIT>" ; String paramString = "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBlock ( blockType , this . getName ( ) , paramString ) ; String tableName = ourDiagram . model . getName ( ) + "<STR_LIT>" + MDLNameList . convertToMDLString ( ft . getGTID ( ) ) ; String maskValues = "<STR_LIT:{>" ; if ( numDim > <NUM_LIT:4> ) maskValues += "<STR_LIT>" ; else maskValues += "<STR_LIT:'>" + numDim + "<STR_LIT>" ; maskValues += "<STR_LIT:'>" + numDim + "<STR_LIT>" + "<STR_LIT:'>" + tableName + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; if ( this . ourDiagram . getWarnOnClip ( ) ) maskValues += "<STR_LIT>" ; else maskValues += "<STR_LIT>" ; maskValues += "<STR_LIT>" ; writer . setParam ( this . getName ( ) , "<STR_LIT>" , maskValues ) ; } public void writeMforIn ( SLFileWriter writer , int x , int y ) throws IOException { BlockInput bin = ( BlockInput ) this . getBlock ( ) ; int seqNumber = bin . getSeqNumber ( ) ; String blockName = this . getName ( ) ; ourDiagram . addInput ( seqNumber , blockName ) ; writer . addBuiltInBlock ( "<STR_LIT>" , blockName , this . createPositionString ( x , y ) ) ; } public void writeMforOut ( SLFileWriter writer , int x , int y ) throws IOException { BlockOutput bout = ( BlockOutput ) this . getBlock ( ) ; int seqNumber = bout . getSeqNumber ( ) ; String blockName = this . getName ( ) ; ourDiagram . addOutput ( seqNumber , blockName ) ; writer . addBuiltInBlock ( "<STR_LIT>" , blockName , this . createPositionString ( x , y ) ) ; } public void writeMforAbs ( SLFileWriter writer , int x , int y ) throws IOException { writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , this . createPositionString ( x , y ) ) ; } public void writeMforConst ( SLFileWriter writer , int x , int y ) throws IOException { BlockMathConstant bconst = ( BlockMathConstant ) this . getBlock ( ) ; String myValue = bconst . getValueAsString ( ) ; String paramString = "<STR_LIT>" + myValue + "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforFunc ( SLFileWriter writer , int x , int y ) throws IOException { BlockMathFunction bmf = ( BlockMathFunction ) this . getBlock ( ) ; String funcType = bmf . getFuncType ( ) ; String blockType ; String operatorType ; if ( funcType . equals ( "<STR_LIT>" ) ) { blockType = "<STR_LIT>" ; operatorType = "<STR_LIT>" ; } else if ( funcType . equals ( "<STR_LIT>" ) ) { blockType = "<STR_LIT>" ; operatorType = "<STR_LIT>" ; } else if ( funcType . equals ( "<STR_LIT>" ) ) { blockType = "<STR_LIT>" ; operatorType = "<STR_LIT>" ; } else { blockType = "<STR_LIT>" ; operatorType = funcType ; if ( funcType . equals ( "<STR_LIT>" ) ) operatorType = "<STR_LIT>" ; if ( funcType . equals ( "<STR_LIT>" ) ) operatorType = "<STR_LIT>" ; if ( funcType . equals ( "<STR_LIT>" ) ) operatorType = "<STR_LIT>" ; } String paramString = "<STR_LIT>" + "<STR_LIT>" + operatorType + "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( blockType , this . getName ( ) , paramString ) ; } public void writeMforMinus ( SLFileWriter writer , int x , int y ) throws IOException { String paramString ; int numArgs = this . block . numInputs ( ) ; if ( numArgs == <NUM_LIT:1> ) { paramString = "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } if ( numArgs == <NUM_LIT:2> ) { paramString = "<STR_LIT>" ; paramString += this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } } public void writeMforMinmax ( SLFileWriter writer , int x , int y ) throws IOException { String paramString ; BlockMathMinmax bmm = ( BlockMathMinmax ) this . block ; int numArgs = bmm . numInputs ( ) ; if ( numArgs == <NUM_LIT:1> ) { paramString = "<STR_LIT>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } if ( numArgs >= <NUM_LIT:2> ) { paramString = this . createPositionString ( x , y ) ; paramString += "<STR_LIT>" + bmm . getFuncType ( ) + "<STR_LIT:'>" ; paramString += "<STR_LIT>" + numArgs + "<STR_LIT:'>" ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } } public void writeMforMult ( SLFileWriter writer , int x , int y ) throws IOException { BlockMathProduct bmp = ( BlockMathProduct ) this . getBlock ( ) ; String blockType = bmp . getBlockType ( ) ; String inputs ; if ( blockType . equals ( "<STR_LIT>" ) ) inputs = "<STR_LIT:'>" + this . getBlock ( ) . numInputs ( ) + "<STR_LIT:'>" ; else inputs = "<STR_LIT>" ; String paramString = "<STR_LIT>" + "<STR_LIT>" + inputs + "<STR_LIT:U+002C>" + this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforRelation ( SLFileWriter writer , int x , int y ) throws IOException { BlockMathRelation bmr = ( BlockMathRelation ) this . getBlock ( ) ; String relationOp = bmr . getRelationOp ( ) ; String paramString = this . createPositionString ( x , y ) + "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; if ( relationOp . equals ( "<STR_LIT>" ) ) paramString += "<STR_LIT>" ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforSum ( SLFileWriter writer , int x , int y ) throws IOException { String signs = "<STR_LIT>" ; for ( int i = <NUM_LIT:0> ; i < this . getBlock ( ) . numInputs ( ) ; i ++ ) signs = signs + "<STR_LIT:+>" ; String paramString = "<STR_LIT>" + signs + "<STR_LIT>" ; paramString += this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforNode ( SLFileWriter writer , int x , int y ) throws IOException { String paramString = "<STR_LIT>" ; paramString += this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } public void writeMforSwitch ( SLFileWriter writer , int x , int y ) throws IOException { String paramString = "<STR_LIT>" ; paramString += this . createPositionString ( x , y ) ; writer . addBuiltInBlock ( "<STR_LIT>" , this . getName ( ) , paramString ) ; } String createPositionString ( int x , int y ) throws IOException { int x0 = x - this . mdlWidth / <NUM_LIT:2> + this . xPad ; int y0 = y - this . mdlHeight / <NUM_LIT:2> + this . yPad ; String paramLine = "<STR_LIT>" + x0 + "<STR_LIT:U+002C>" + y0 + "<STR_LIT:U+002C>" + ( x0 + this . mdlWidth ) + "<STR_LIT:U+002C>" + ( y0 + this . mdlHeight ) + "<STR_LIT:]>" ; return paramLine ; } public void writeMat ( MatFileWriter writer ) throws IOException { if ( this . block instanceof BlockFuncTable ) { BlockFuncTable bft = ( BlockFuncTable ) this . block ; FuncTable ft = bft . getFunctionTableDef ( ) ; String tableName = MDLNameList . convertToMDLString ( ft . getGTID ( ) ) ; if ( ! this . writtenTables . contains ( tableName ) ) { writer . writeln ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; writer . writeMatrix ( ourDiagram . model . getName ( ) + "<STR_LIT>" + tableName , ft . getValues ( ) , ft . getDimensions ( ) ) ; this . writtenTables . add ( tableName ) ; } else { writer . writeln ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" + tableName + "<STR_LIT>" ) ; } } else if ( this . block instanceof BlockBP ) { BreakpointSet bpSet = ( ( BlockBP ) this . getBlock ( ) ) . getBPset ( ) ; writer . writeln ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; writer . writeln ( ourDiagram . model . getName ( ) + "<STR_LIT>" + MDLNameList . convertToMDLString ( this . getName ( ) ) + "<STR_LIT>" + bpSet . values ( ) + "<STR_LIT>" ) ; } else { writer . writeln ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; } } public int getRow ( ) { return this . myRow ; } public int getCol ( ) { return this . myCol ; } public String getName ( ) { return this . block . getName ( ) ; } public int getMDLWidth ( ) { return this . mdlWidth ; } public int getMDLHeight ( ) { return this . mdlHeight ; } public void makeVerbose ( ) { this . verboseFlag = true ; if ( this . block != null ) this . block . makeVerbose ( ) ; } public boolean isVerbose ( ) { return this . verboseFlag ; } public void silence ( ) { this . verboseFlag = false ; if ( this . block != null ) this . block . silence ( ) ; } public Block getBlock ( ) { return this . block ; } public void findChildren ( ) { this . findChildren ( "<STR_LIT:U+0020>" ) ; } private void findChildren ( String prefix ) { Signal sig = null ; BlockArrayList blks ; Block kid ; if ( children . size ( ) == <NUM_LIT:0> ) { if ( this . isVerbose ( ) ) { System . out . println ( "<STR_LIT>" + this . block . getName ( ) + "<STR_LIT>" ) ; } sig = this . block . getOutput ( ) ; if ( sig != null ) { blks = sig . getDests ( ) ; if ( blks == null ) { System . err . println ( "<STR_LIT>" + this . block . getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } else { for ( Iterator < Block > iBlk = blks . iterator ( ) ; iBlk . hasNext ( ) ; ) { kid = iBlk . next ( ) ; children . add ( kid ) ; SLBlock kidSLBlock = ( SLBlock ) kid . getMask ( ) ; if ( kidSLBlock == null ) { System . err . println ( "<STR_LIT>" + getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } kidSLBlock . findChildren ( prefix + "<STR_LIT:U+0020>" ) ; } } } } } public int setPosition ( int minimumRow , int minimumCol , String prefix ) { Block kid = null ; if ( this . myRow == <NUM_LIT:0> ) this . myRow = minimumRow ; if ( minimumCol > this . myCol ) this . myCol = minimumCol ; this . rowDepthOfChildren = myRow ; int offset = <NUM_LIT:0> ; for ( Iterator < ? > ikid = children . iterator ( ) ; ikid . hasNext ( ) ; ) { kid = ( Block ) ikid . next ( ) ; SLBlock kidSLBlock = ( SLBlock ) kid . getMask ( ) ; if ( kidSLBlock == null ) { System . err . println ( "<STR_LIT>" + kid . getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } int returnedRow = kidSLBlock . setPosition ( this . rowDepthOfChildren + offset , this . myCol + <NUM_LIT:1> , ( prefix + "<STR_LIT:U+0020>" ) ) ; if ( this . rowDepthOfChildren < returnedRow ) this . rowDepthOfChildren = returnedRow ; offset = <NUM_LIT:1> ; } if ( myRow > this . rowDepthOfChildren ) return myRow ; else return this . rowDepthOfChildren ; } public int setPosition ( int minRow , int minCol ) { return setPosition ( minRow , minCol , "<STR_LIT:U+0020>" ) ; } public void setRowCol ( int theRow , int theCol ) { myRow = theRow ; myCol = theCol ; return ; } public int findChildrensFarthestColumn ( ) { Block kid = null ; int farthest = this . myCol ; for ( Iterator < Block > ikid = children . iterator ( ) ; ikid . hasNext ( ) ; ) { kid = ikid . next ( ) ; SLBlock kidSLBlock = ( SLBlock ) kid . getMask ( ) ; if ( kidSLBlock == null ) { System . err . println ( "<STR_LIT>" + kid . getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } int kidsCol = kidSLBlock . findChildrensFarthestColumn ( ) ; if ( kidsCol > farthest ) farthest = kidsCol ; } return farthest ; } public int findChildrensDeepestRow ( ) { Block kid = null ; int deepest = this . myRow ; for ( Iterator < Block > ikid = children . iterator ( ) ; ikid . hasNext ( ) ; ) { kid = ikid . next ( ) ; SLBlock kidSLBlock = ( SLBlock ) kid . getMask ( ) ; if ( kidSLBlock == null ) { System . err . println ( "<STR_LIT>" + kid . getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } int kidsRow = kidSLBlock . findChildrensDeepestRow ( ) ; if ( kidsRow > deepest ) deepest = kidsRow ; } return deepest ; } public static int printTable ( Writer writer , ArrayList < Double > table , int [ ] dims , int startIndex ) throws IOException { int offset ; int i ; switch ( dims . length ) { case <NUM_LIT:0> : return <NUM_LIT:0> ; case <NUM_LIT:1> : for ( i = <NUM_LIT:0> ; i < dims [ <NUM_LIT:0> ] ; i ++ ) { Double theValue = table . get ( i + startIndex ) ; writer . write ( theValue . toString ( ) ) ; if ( i < dims [ <NUM_LIT:0> ] - <NUM_LIT:1> ) writer . write ( "<STR_LIT:U+002CU+0020>" ) ; } return i ; case <NUM_LIT:2> : for ( i = <NUM_LIT:0> ; i < dims [ <NUM_LIT:0> ] ; i ++ ) { int [ ] newDims = new int [ <NUM_LIT:1> ] ; newDims [ <NUM_LIT:0> ] = dims [ <NUM_LIT:1> ] ; offset = printTable ( writer , table , newDims , startIndex ) ; if ( i < dims [ <NUM_LIT:0> ] - <NUM_LIT:1> ) writer . write ( "<STR_LIT:U+002CU+0020>" ) ; writer . write ( "<STR_LIT:n>" ) ; startIndex = startIndex + offset ; } return startIndex ; default : for ( i = <NUM_LIT:0> ; i < dims [ <NUM_LIT:0> ] ; i ++ ) { int [ ] newDims = new int [ <NUM_LIT:1> ] ; newDims [ <NUM_LIT:0> ] = dims [ <NUM_LIT:1> ] ; offset = printTable ( writer , table , newDims , startIndex ) ; if ( i < dims [ <NUM_LIT:0> ] - <NUM_LIT:1> ) writer . write ( "<STR_LIT:U+002CU+0020>" ) ; writer . write ( "<STR_LIT:n>" ) ; startIndex = startIndex + offset ; } return startIndex ; } } public static void printTable ( ArrayList < Double > table , int [ ] dims ) throws IOException { OutputStreamWriter osw = new OutputStreamWriter ( System . out ) ; printTable ( osw , table , dims , <NUM_LIT:0> ) ; } public static void printTable ( Writer writer , ArrayList < Double > table , int [ ] dims ) throws IOException { printTable ( writer , table , dims , <NUM_LIT:0> ) ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import gov . nasa . daveml . dave . Block ; import gov . nasa . daveml . dave . BlockArrayList ; import gov . nasa . daveml . dave . Signal ; import java . util . ArrayList ; import java . util . Iterator ; import java . io . IOException ; public class SLSignal extends Signal { SLDiagram parentDiagram ; SLCell sourceCell ; SLCell destCell ; ArrayList < SLBranch > branches ; SLLineSegment path ; public SLSignal ( ) { super ( ) ; if ( this . isVerbose ( ) ) System . out . println ( "<STR_LIT>" ) ; this . parentDiagram = null ; this . sourceCell = null ; this . branches = new ArrayList < SLBranch > ( <NUM_LIT:10> ) ; this . path = null ; } public SLSignal ( Signal oldSignal , SLDiagram theParentDiagram ) { super ( oldSignal ) ; if ( this . isVerbose ( ) ) System . out . println ( "<STR_LIT>" + oldSignal . getName ( ) ) ; this . parentDiagram = theParentDiagram ; if ( this . getSource ( ) != null ) { Block b = this . getSource ( ) ; SLBlock slb = ( SLBlock ) b . getMask ( ) ; if ( slb == null ) { System . err . println ( "<STR_LIT>" + b . getName ( ) + "<STR_LIT>" ) ; System . exit ( <NUM_LIT:0> ) ; } this . sourceCell = this . parentDiagram . getCell ( slb ) ; } else { System . err . println ( "<STR_LIT>" + this . getName ( ) ) ; } this . branches = new ArrayList < SLBranch > ( <NUM_LIT:10> ) ; this . path = null ; } public SLDiagram getDiagram ( ) { return this . parentDiagram ; } public void describeBranches ( ) { if ( ! this . isVerbose ( ) ) return ; System . out . println ( ) ; if ( this . path == null ) { if ( this . branches == null ) { System . err . println ( "<STR_LIT>" + this . getName ( ) + "<STR_LIT>" ) ; return ; } else { System . out . print ( "<STR_LIT>" + getName ( ) ) ; if ( this . branches . size ( ) <= <NUM_LIT:1> ) { System . out . println ( "<STR_LIT>" + this . sourceCell . getBlock ( ) . getName ( ) + "<STR_LIT>" + this . sourceCell . getRowIndex ( ) + "<STR_LIT:U+002C>" + this . sourceCell . getColIndex ( ) + "<STR_LIT>" ) ; if ( this . destCell != null ) System . out . println ( "<STR_LIT>" + this . destCell . getBlock ( ) . getName ( ) + "<STR_LIT>" + this . destCell . getRowIndex ( ) + "<STR_LIT:U+002C>" + this . destCell . getColIndex ( ) + "<STR_LIT:]>" ) ; } else { System . out . println ( "<STR_LIT>" + this . branches . size ( ) + "<STR_LIT>" + this . sourceCell . getBlock ( ) . getName ( ) + "<STR_LIT>" + this . sourceCell . getRowIndex ( ) + "<STR_LIT:U+002C>" + this . sourceCell . getColIndex ( ) + "<STR_LIT>" ) ; } Iterator < SLBranch > ib = this . branches . iterator ( ) ; while ( ib . hasNext ( ) ) { SLLineSegment ls = null ; SLBranch list = ib . next ( ) ; Iterator < SLLineSegment > iline = list . iterator ( ) ; while ( iline . hasNext ( ) ) ls = iline . next ( ) ; SLCell destination = ls . getDestCell ( ) ; System . out . println ( "<STR_LIT>" + destination . getBlock ( ) . getName ( ) + "<STR_LIT>" + destination . getRowIndex ( ) + "<STR_LIT:U+002C>" + destination . getColIndex ( ) + "<STR_LIT>" ) ; iline = list . iterator ( ) ; boolean first = true ; while ( iline . hasNext ( ) ) { if ( first ) { first = false ; System . out . print ( "<STR_LIT>" ) ; } else System . out . print ( "<STR_LIT>" ) ; ls = iline . next ( ) ; ls . describe ( ) ; } } } } else { if ( this . isVerbose ( ) ) this . path . describe ( ) ; } } public void describePath ( ) { if ( ! this . isVerbose ( ) ) return ; System . out . println ( ) ; System . out . print ( "<STR_LIT>" + getName ( ) + "<STR_LIT>" + this . sourceCell . getBlock ( ) . getName ( ) + "<STR_LIT>" + this . sourceCell . getRowIndex ( ) + "<STR_LIT:U+002C>" + this . sourceCell . getColIndex ( ) + "<STR_LIT>" ) ; if ( path == null ) { System . out . println ( "<STR_LIT>" + this . destCell . getBlock ( ) . getName ( ) + "<STR_LIT>" + this . destCell . getRowIndex ( ) + "<STR_LIT:U+002C>" + this . destCell . getColIndex ( ) + "<STR_LIT>" ) ; } else { System . out . println ( "<STR_LIT:U+0020toU+0020>" + this . getDests ( ) . size ( ) + "<STR_LIT>" ) ; this . path . describe ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; } } public void createAddLine ( SLFileWriter writer ) throws IOException { BlockArrayList dests = this . getDests ( ) ; ArrayList < Integer > destPorts = this . getDestPortNumbers ( ) ; Iterator < Block > id = dests . iterator ( ) ; Iterator < Integer > ip = destPorts . iterator ( ) ; while ( id . hasNext ( ) ) { Integer destPort = ip . next ( ) ; Block destBlock = id . next ( ) ; writer . addLine ( this . getSource ( ) . getName ( ) , this . getSourcePort ( ) , destBlock . getName ( ) , destPort , this . getName ( ) ) ; } } } </s>
<s> package gov . nasa . daveml . dave2sl ; import java . util . ArrayList ; import java . util . Iterator ; import java . io . IOException ; public class SLLineSegment { SLSignal parentSignal ; boolean isHorizSeg ; int [ ] coord ; int trayOffset ; SLCell destCell ; SLLineSegment nextSeg ; SLBranch branches ; public SLLineSegment ( ) { parentSignal = null ; isHorizSeg = false ; coord = new int [ <NUM_LIT:5> ] ; trayOffset = <NUM_LIT:0> ; destCell = null ; nextSeg = null ; branches = new SLBranch ( <NUM_LIT:5> ) ; } public SLLineSegment ( SLSignal signal , int hTray , int start , int end ) { this ( ) ; isHorizSeg = true ; parentSignal = signal ; coord [ <NUM_LIT:0> ] = hTray ; coord [ <NUM_LIT:1> ] = start ; coord [ <NUM_LIT:2> ] = end ; coord [ <NUM_LIT:3> ] = <NUM_LIT:0> ; coord [ <NUM_LIT:4> ] = <NUM_LIT:0> ; } public SLLineSegment ( SLSignal signal , int vTray , int start , int end , int startPortNumber , int destPortNumber ) { this ( ) ; parentSignal = signal ; coord [ <NUM_LIT:0> ] = vTray ; coord [ <NUM_LIT:1> ] = start ; coord [ <NUM_LIT:2> ] = end ; coord [ <NUM_LIT:3> ] = startPortNumber ; coord [ <NUM_LIT:4> ] = destPortNumber ; } public boolean isHoriz ( ) { return isHorizSeg ; } public boolean isVert ( ) { return ! isHorizSeg ; } public void setDestPort ( int thePort ) { coord [ <NUM_LIT:4> ] = thePort ; } public void setDestCell ( SLCell theDest ) { this . destCell = theDest ; } public void setNextSeg ( SLLineSegment next ) { this . nextSeg = next ; } public void setTrayOffset ( ) { } private void setStart ( int start ) { coord [ <NUM_LIT:1> ] = start ; } private void setSourcePort ( int port ) { coord [ <NUM_LIT:3> ] = port ; } public int getTray ( ) { return coord [ <NUM_LIT:0> ] ; } public int getTrayOffset ( ) { return trayOffset ; } public int getStart ( ) { return coord [ <NUM_LIT:1> ] ; } public int getEnd ( ) { return coord [ <NUM_LIT:2> ] ; } public int getSourcePort ( ) { return coord [ <NUM_LIT:3> ] ; } public int getDestPort ( ) { return coord [ <NUM_LIT:4> ] ; } public ArrayList < SLLineSegment > getBranches ( ) { return branches ; } public int numBranches ( ) { return branches . size ( ) ; } public void addBranch ( SLLineSegment newBranch ) { this . branches . add ( newBranch ) ; } public SLCell getDestCell ( ) { return this . destCell ; } public void subtract ( SLLineSegment predecessor ) { if ( ( predecessor . isHoriz ( ) != this . isHoriz ( ) ) || ( predecessor . getStart ( ) != this . getStart ( ) ) || ( predecessor . getSourcePort ( ) != this . getSourcePort ( ) ) || ( predecessor . getTray ( ) != this . getTray ( ) ) || ( predecessor . getTrayOffset ( ) != this . getTrayOffset ( ) ) ) System . err . println ( "<STR_LIT>" ) ; else { if ( parentSignal . isVerbose ( ) ) this . describe ( "<STR_LIT>" ) ; this . setStart ( predecessor . getEnd ( ) ) ; this . setSourcePort ( predecessor . getDestPort ( ) ) ; if ( parentSignal . isVerbose ( ) ) this . describe ( "<STR_LIT>" ) ; } return ; } public int calcLength ( ) { SLSignal sig = this . parentSignal ; SLDiagram d = sig . getDiagram ( ) ; int start = this . getStart ( ) ; int end = this . getEnd ( ) ; int p = this . getSourcePort ( ) ; int q = this . getDestPort ( ) ; int length = <NUM_LIT:0> ; if ( this . isVert ( ) ) { int dir = <NUM_LIT:1> ; if ( end < start ) dir = - <NUM_LIT:1> ; if ( end == start ) { if ( ( p == <NUM_LIT:0> ) && ( q > <NUM_LIT:0> ) ) dir = - <NUM_LIT:1> ; if ( ( q == <NUM_LIT:0> ) && ( p > <NUM_LIT:0> ) ) dir = <NUM_LIT:1> ; if ( ( p > <NUM_LIT:0> ) && ( q > <NUM_LIT:0> ) ) if ( q > p ) dir = - <NUM_LIT:1> ; else dir = <NUM_LIT:1> ; } for ( int i = start + dir ; i * dir <= dir * ( end - dir ) ; i = i + dir ) { length = length + ( d . getRow ( i ) ) . getSize ( ) ; } if ( ( end > start ) && ( q == <NUM_LIT:0> ) ) length = length + ( d . getRow ( end ) ) . getSize ( ) ; boolean adjacent = ( ( end == start ) && ( p != <NUM_LIT:0> ) && ( q != <NUM_LIT:0> ) ) ; if ( ! adjacent ) { if ( p != <NUM_LIT:0> ) { SLCell theCell = d . getCell ( start , this . getTray ( ) ) ; if ( theCell == null ) theCell = d . getCell ( start , this . getTray ( ) + <NUM_LIT:1> ) ; int offset = theCell . getHeight ( ) / <NUM_LIT:2> ; length = length + offset ; } else if ( end != start ) length = length + ( d . getRow ( start ) ) . getSize ( ) ; if ( q != <NUM_LIT:0> ) { SLCell theCell = d . getCell ( end , this . getTray ( ) + <NUM_LIT:1> ) ; if ( theCell == null ) theCell = d . getCell ( end , this . getTray ( ) ) ; int offset = theCell . getHeight ( ) / <NUM_LIT:2> ; length = length + offset ; } else { } } length = dir * length ; } else { for ( int i = start + <NUM_LIT:1> ; i <= ( end - <NUM_LIT:2> ) ; i ++ ) length = length + ( d . getCol ( i ) ) . getSize ( ) ; length = length + ( d . getCol ( end - <NUM_LIT:1> ) ) . getSizeNoTray ( ) ; SLRowColumnVector startCol = d . getCol ( start ) ; SLCableTray startTray = startCol . getTray ( ) ; int standoff = startTray . getStandoff ( sig ) ; length = length - standoff ; SLRowColumnVector endCol = d . getCol ( end - <NUM_LIT:1> ) ; SLCableTray endTray = endCol . getTray ( ) ; standoff = endTray . getStandoff ( sig ) ; length = length + standoff ; } return length ; } public void describe ( ) { this . describe ( "<STR_LIT>" ) ; } public void describe ( String indent ) { System . out . print ( indent ) ; if ( this . isHoriz ( ) ) System . out . print ( "<STR_LIT>" + this . getTray ( ) + "<STR_LIT:+>" + this . getTrayOffset ( ) + "<STR_LIT:U+002C>" + this . getStart ( ) + "<STR_LIT>" + this . getTray ( ) + "<STR_LIT:U+002C>" + this . getEnd ( ) + "<STR_LIT:]>" ) ; else System . out . print ( "<STR_LIT>" + this . getStart ( ) + "<STR_LIT:U+002C>" + this . getTray ( ) + "<STR_LIT:+>" + this . getTrayOffset ( ) + "<STR_LIT:U+002C>" + this . getSourcePort ( ) + "<STR_LIT>" + this . getEnd ( ) + "<STR_LIT:U+002C>" + this . getTray ( ) + "<STR_LIT:+>" + this . getTrayOffset ( ) + "<STR_LIT:U+002C>" + this . getDestPort ( ) + "<STR_LIT:]>" ) ; System . out . print ( "<STR_LIT:U+0020(>" ) ; if ( this . nextSeg != null ) System . out . print ( "<STR_LIT:S>" ) ; else System . out . print ( "<STR_LIT:U+0020>" ) ; if ( this . branches . size ( ) > <NUM_LIT:0> ) System . out . print ( "<STR_LIT:B>" ) ; else System . out . print ( "<STR_LIT:U+0020>" ) ; if ( this . destCell != null ) System . out . print ( "<STR_LIT>" ) ; else System . out . print ( "<STR_LIT>" ) ; if ( this . destCell == null ) if ( this . nextSeg == null ) if ( this . branches . size ( ) == <NUM_LIT:0> ) System . out . println ( "<STR_LIT>" ) ; else { System . out . println ( "<STR_LIT>" + this . branches . size ( ) + "<STR_LIT>" ) ; Iterator < SLLineSegment > it = this . branches . iterator ( ) ; while ( it . hasNext ( ) ) { SLLineSegment ls = it . next ( ) ; ls . describe ( indent + "<STR_LIT:U+0020U+0020>" ) ; } } else { System . out . println ( "<STR_LIT>" ) ; this . nextSeg . describe ( indent + "<STR_LIT:U+0020U+0020>" ) ; } else { System . out . print ( "<STR_LIT>" + destCell . getBlock ( ) . getName ( ) + "<STR_LIT:'>" ) ; if ( this . nextSeg == null ) if ( this . branches . size ( ) == <NUM_LIT:0> ) { System . out . println ( "<STR_LIT:.>" ) ; } else { System . out . println ( "<STR_LIT>" + this . branches . size ( ) + "<STR_LIT>" ) ; Iterator < SLLineSegment > it = this . branches . iterator ( ) ; while ( it . hasNext ( ) ) { SLLineSegment ls = it . next ( ) ; ls . describe ( indent + "<STR_LIT:U+0020U+0020>" ) ; } } else { System . out . println ( "<STR_LIT>" ) ; this . nextSeg . describe ( indent + "<STR_LIT:U+0020U+0020>" ) ; } } } public void createAddLine ( SLFileWriter writer , String indent , boolean ptsEntered ) throws IOException { boolean hasBranched = false ; int length = this . calcLength ( ) ; if ( length != <NUM_LIT:0> ) { if ( ptsEntered ) writer . write ( "<STR_LIT:;U+0020>" ) ; if ( this . isHoriz ( ) ) writer . write ( this . calcLength ( ) + "<STR_LIT>" ) ; else writer . write ( "<STR_LIT>" + this . calcLength ( ) ) ; if ( this . nextSeg != null ) { this . nextSeg . createAddLine ( writer , indent + "<STR_LIT:U+0020U+0020>" , true ) ; return ; } } writer . writeln ( "<STR_LIT:]>" ) ; if ( this . branches . size ( ) != <NUM_LIT:0> ) { hasBranched = true ; Iterator < SLLineSegment > ib = this . branches . iterator ( ) ; while ( ib . hasNext ( ) ) { SLLineSegment ls = ib . next ( ) ; writer . writeln ( indent + "<STR_LIT>" ) ; writer . write ( indent + "<STR_LIT>" ) ; ls . createAddLine ( writer , indent + "<STR_LIT:U+0020U+0020>" , false ) ; writer . writeln ( indent + "<STR_LIT:}>" ) ; } } if ( this . destCell == null ) if ( ! hasBranched ) { System . err . println ( "<STR_LIT>" + this . parentSignal . getName ( ) + "<STR_LIT>" ) ; return ; } else { return ; } else { if ( hasBranched ) writer . writeln ( indent + "<STR_LIT>" ) ; SLBlock destBlock = destCell . getBlock ( ) ; if ( destBlock == null ) { System . err . println ( "<STR_LIT>" + this . parentSignal . getName ( ) + "<STR_LIT>" ) ; return ; } int destPort = this . getDestPort ( ) ; if ( destPort == <NUM_LIT:0> ) System . err . println ( "<STR_LIT>" + this . parentSignal . getName ( ) + "<STR_LIT>" ) ; writer . write ( indent ) ; if ( hasBranched ) writer . write ( "<STR_LIT:U+0020U+0020>" ) ; writer . writeln ( "<STR_LIT>" + destBlock . getName ( ) + "<STR_LIT:\">" ) ; writer . write ( indent ) ; if ( hasBranched ) writer . write ( "<STR_LIT:U+0020U+0020>" ) ; writer . writeln ( "<STR_LIT>" + destPort ) ; if ( hasBranched ) writer . writeln ( indent + "<STR_LIT:}>" ) ; } } } </s>
<s> package gov . nasa . daveml . dave2sl ; import java . util . ArrayList ; import java . util . Iterator ; @ SuppressWarnings ( "<STR_LIT:serial>" ) public class SLPathList extends ArrayList < SLBranch > { public SLPathList ( ) { super ( ) ; } public SLPathList ( int size ) { super ( size ) ; } public boolean add ( SLBranch branch ) { super . add ( branch ) ; return true ; } public void merge ( SLPathList otherList ) { Iterator < SLBranch > it = otherList . iterator ( ) ; while ( it . hasNext ( ) ) { this . add ( it . next ( ) ) ; } } public void describe ( ) { System . out . println ( "<STR_LIT>" + this . size ( ) + "<STR_LIT>" ) ; int i = <NUM_LIT:1> ; Iterator < SLBranch > it = this . iterator ( ) ; while ( it . hasNext ( ) ) { System . out . println ( "<STR_LIT>" + i + "<STR_LIT::U+0020>" ) ; ArrayList < ? > a = ( ArrayList < ? > ) it . next ( ) ; Iterator < ? > ait = a . iterator ( ) ; while ( ait . hasNext ( ) ) { SLLineSegment ls = ( SLLineSegment ) ait . next ( ) ; ls . describe ( "<STR_LIT:U+0020U+0020>" ) ; } i ++ ; } System . out . println ( ) ; } } </s>
<s> package gov . nasa . daveml . dave2sl ; import java . util . ArrayList ; public class SLBranch extends ArrayList < SLLineSegment > { public SLBranch ( int i ) { super ( i ) ; } private static final long serialVersionUID = - <NUM_LIT> ; } </s>