repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/LicenseTransactionJoinImpl.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/License.java
// public interface License extends BaseEntity {
//
// // Methods for working with properties
//
// String getName();
//
// void setName(String name);
//
// BigDecimal getPrice();
//
// void setPrice(BigDecimal price);
//
// Currency getCurrency();
//
// void setCurrency(Currency currency);
//
// Boolean getHidden();
//
// void setHidden(Boolean hidden);
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getLicenseProperties();
//
// // Methods for interacting with other entities
//
// Licensee getLicensee();
//
// void setLicensee(Licensee licensee);
//
// LicenseTemplate getLicenseTemplate();
//
// void setLicenseTemplate(LicenseTemplate licenseTemplate);
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/LicenseTransactionJoin.java
// public interface LicenseTransactionJoin extends Serializable {
//
// void setTransaction(final Transaction transaction);
//
// Transaction getTransaction();
//
// void setLicense(final License license);
//
// License getLicense();
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java
// public interface Transaction extends BaseEntity {
//
// // Methods for working with properties
//
// TransactionStatus getStatus();
//
// void setStatus(TransactionStatus status);
//
// TransactionSource getSource();
//
// void setSource(TransactionSource source);
//
// BigDecimal getGrandTotal();
//
// void setGrandTotal(BigDecimal grandTotal);
//
// BigDecimal getDiscount();
//
// void setDiscount(BigDecimal discount);
//
// Currency getCurrency();
//
// void setCurrency(Currency currency);
//
// Date getDateCreated();
//
// void setDateCreated(Date dateCreated);
//
// Date getDateClosed();
//
// void setDateClosed(Date dateClosed);
//
// List<LicenseTransactionJoin> getLicenseTransactionJoins();
//
// void setLicenseTransactionJoins(List<LicenseTransactionJoin> licenseTransactionJoins);
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getTransactionProperties();
//
// }
| import com.labs64.netlicensing.domain.entity.Transaction;
import com.labs64.netlicensing.domain.entity.License;
import com.labs64.netlicensing.domain.entity.LicenseTransactionJoin; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity.impl;
public class LicenseTransactionJoinImpl implements LicenseTransactionJoin {
private Transaction transaction; | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/License.java
// public interface License extends BaseEntity {
//
// // Methods for working with properties
//
// String getName();
//
// void setName(String name);
//
// BigDecimal getPrice();
//
// void setPrice(BigDecimal price);
//
// Currency getCurrency();
//
// void setCurrency(Currency currency);
//
// Boolean getHidden();
//
// void setHidden(Boolean hidden);
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getLicenseProperties();
//
// // Methods for interacting with other entities
//
// Licensee getLicensee();
//
// void setLicensee(Licensee licensee);
//
// LicenseTemplate getLicenseTemplate();
//
// void setLicenseTemplate(LicenseTemplate licenseTemplate);
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/LicenseTransactionJoin.java
// public interface LicenseTransactionJoin extends Serializable {
//
// void setTransaction(final Transaction transaction);
//
// Transaction getTransaction();
//
// void setLicense(final License license);
//
// License getLicense();
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java
// public interface Transaction extends BaseEntity {
//
// // Methods for working with properties
//
// TransactionStatus getStatus();
//
// void setStatus(TransactionStatus status);
//
// TransactionSource getSource();
//
// void setSource(TransactionSource source);
//
// BigDecimal getGrandTotal();
//
// void setGrandTotal(BigDecimal grandTotal);
//
// BigDecimal getDiscount();
//
// void setDiscount(BigDecimal discount);
//
// Currency getCurrency();
//
// void setCurrency(Currency currency);
//
// Date getDateCreated();
//
// void setDateCreated(Date dateCreated);
//
// Date getDateClosed();
//
// void setDateClosed(Date dateClosed);
//
// List<LicenseTransactionJoin> getLicenseTransactionJoins();
//
// void setLicenseTransactionJoins(List<LicenseTransactionJoin> licenseTransactionJoins);
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getTransactionProperties();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/LicenseTransactionJoinImpl.java
import com.labs64.netlicensing.domain.entity.Transaction;
import com.labs64.netlicensing.domain.entity.License;
import com.labs64.netlicensing.domain.entity.LicenseTransactionJoin;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity.impl;
public class LicenseTransactionJoinImpl implements LicenseTransactionJoin {
private Transaction transaction; | private License license; |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionSource.java
// public enum TransactionSource {
//
// /**
// * Shop transaction.
// */
// SHOP,
//
// /**
// * Auto transaction for license create.
// */
// AUTO_LICENSE_CREATE,
//
// /**
// * Auto transaction for license update.
// */
// AUTO_LICENSE_UPDATE,
//
// /**
// * Auto transaction for license delete.
// */
// AUTO_LICENSE_DELETE,
//
// /**
// * Auto transaction for licensee create (with automatic licenses).
// */
// AUTO_LICENSEE_CREATE,
//
// /**
// * Auto transaction for licensee delete with forceCascade.
// */
// AUTO_LICENSEE_DELETE,
//
// /**
// * Transaction for update license during validate
// */
// AUTO_LICENSEE_VALIDATE,
//
// /**
// * Auto transaction for license template delete with forceCascade.
// */
// AUTO_LICENSETEMPLATE_DELETE,
//
// /**
// * Auto transaction for product module delete with forceCascade.
// */
// AUTO_PRODUCTMODULE_DELETE,
//
// /**
// * Auto transaction for product delete with forceCascade.
// */
// AUTO_PRODUCT_DELETE,
//
// /**
// * Auto transaction for transfer licenses between licensee.
// */
// AUTO_LICENSES_TRANSFER,
//
// /**
// * Transaction for update licenses (inactive with PT LM, Subscription).
// */
// SUBSCRIPTION_UPDATE,
//
// /**
// * Transaction for cancel recurring payment.
// */
// CANCEL_RECURRING_PAYMENT
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionStatus.java
// public enum TransactionStatus {
//
// /**
// * Transaction still running.
// */
// PENDING,
//
// /**
// * Transaction is closed.
// */
// CLOSED,
//
// /**
// * Transaction is cancelled.
// */
// CANCELLED
//
// }
| import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.labs64.netlicensing.domain.vo.Currency;
import com.labs64.netlicensing.domain.vo.TransactionSource;
import com.labs64.netlicensing.domain.vo.TransactionStatus; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Transaction entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products of a vendor) that identifies the transaction. This number is
* always generated by NetLicensing.
* <p>
* <b>active</b> - always true for transactions
* <p>
* <b>status</b> - see {@link TransactionStatus}
* <p>
* <b>source</b> - see {@link TransactionSource}
* <p>
* <b>grandTotal</b> - grand total for SHOP transaction (see source).
* <p>
* <b>discount</b> - discount for SHOP transaction (see source).
* <p>
* <b>currency</b> - specifies currency for money fields (grandTotal and discount). Check data types to discover which
* currencies are supported.
*/
public interface Transaction extends BaseEntity {
// Methods for working with properties
TransactionStatus getStatus();
void setStatus(TransactionStatus status);
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionSource.java
// public enum TransactionSource {
//
// /**
// * Shop transaction.
// */
// SHOP,
//
// /**
// * Auto transaction for license create.
// */
// AUTO_LICENSE_CREATE,
//
// /**
// * Auto transaction for license update.
// */
// AUTO_LICENSE_UPDATE,
//
// /**
// * Auto transaction for license delete.
// */
// AUTO_LICENSE_DELETE,
//
// /**
// * Auto transaction for licensee create (with automatic licenses).
// */
// AUTO_LICENSEE_CREATE,
//
// /**
// * Auto transaction for licensee delete with forceCascade.
// */
// AUTO_LICENSEE_DELETE,
//
// /**
// * Transaction for update license during validate
// */
// AUTO_LICENSEE_VALIDATE,
//
// /**
// * Auto transaction for license template delete with forceCascade.
// */
// AUTO_LICENSETEMPLATE_DELETE,
//
// /**
// * Auto transaction for product module delete with forceCascade.
// */
// AUTO_PRODUCTMODULE_DELETE,
//
// /**
// * Auto transaction for product delete with forceCascade.
// */
// AUTO_PRODUCT_DELETE,
//
// /**
// * Auto transaction for transfer licenses between licensee.
// */
// AUTO_LICENSES_TRANSFER,
//
// /**
// * Transaction for update licenses (inactive with PT LM, Subscription).
// */
// SUBSCRIPTION_UPDATE,
//
// /**
// * Transaction for cancel recurring payment.
// */
// CANCEL_RECURRING_PAYMENT
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionStatus.java
// public enum TransactionStatus {
//
// /**
// * Transaction still running.
// */
// PENDING,
//
// /**
// * Transaction is closed.
// */
// CLOSED,
//
// /**
// * Transaction is cancelled.
// */
// CANCELLED
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.labs64.netlicensing.domain.vo.Currency;
import com.labs64.netlicensing.domain.vo.TransactionSource;
import com.labs64.netlicensing.domain.vo.TransactionStatus;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Transaction entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products of a vendor) that identifies the transaction. This number is
* always generated by NetLicensing.
* <p>
* <b>active</b> - always true for transactions
* <p>
* <b>status</b> - see {@link TransactionStatus}
* <p>
* <b>source</b> - see {@link TransactionSource}
* <p>
* <b>grandTotal</b> - grand total for SHOP transaction (see source).
* <p>
* <b>discount</b> - discount for SHOP transaction (see source).
* <p>
* <b>currency</b> - specifies currency for money fields (grandTotal and discount). Check data types to discover which
* currencies are supported.
*/
public interface Transaction extends BaseEntity {
// Methods for working with properties
TransactionStatus getStatus();
void setStatus(TransactionStatus status);
| TransactionSource getSource(); |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionSource.java
// public enum TransactionSource {
//
// /**
// * Shop transaction.
// */
// SHOP,
//
// /**
// * Auto transaction for license create.
// */
// AUTO_LICENSE_CREATE,
//
// /**
// * Auto transaction for license update.
// */
// AUTO_LICENSE_UPDATE,
//
// /**
// * Auto transaction for license delete.
// */
// AUTO_LICENSE_DELETE,
//
// /**
// * Auto transaction for licensee create (with automatic licenses).
// */
// AUTO_LICENSEE_CREATE,
//
// /**
// * Auto transaction for licensee delete with forceCascade.
// */
// AUTO_LICENSEE_DELETE,
//
// /**
// * Transaction for update license during validate
// */
// AUTO_LICENSEE_VALIDATE,
//
// /**
// * Auto transaction for license template delete with forceCascade.
// */
// AUTO_LICENSETEMPLATE_DELETE,
//
// /**
// * Auto transaction for product module delete with forceCascade.
// */
// AUTO_PRODUCTMODULE_DELETE,
//
// /**
// * Auto transaction for product delete with forceCascade.
// */
// AUTO_PRODUCT_DELETE,
//
// /**
// * Auto transaction for transfer licenses between licensee.
// */
// AUTO_LICENSES_TRANSFER,
//
// /**
// * Transaction for update licenses (inactive with PT LM, Subscription).
// */
// SUBSCRIPTION_UPDATE,
//
// /**
// * Transaction for cancel recurring payment.
// */
// CANCEL_RECURRING_PAYMENT
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionStatus.java
// public enum TransactionStatus {
//
// /**
// * Transaction still running.
// */
// PENDING,
//
// /**
// * Transaction is closed.
// */
// CLOSED,
//
// /**
// * Transaction is cancelled.
// */
// CANCELLED
//
// }
| import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.labs64.netlicensing.domain.vo.Currency;
import com.labs64.netlicensing.domain.vo.TransactionSource;
import com.labs64.netlicensing.domain.vo.TransactionStatus; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Transaction entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products of a vendor) that identifies the transaction. This number is
* always generated by NetLicensing.
* <p>
* <b>active</b> - always true for transactions
* <p>
* <b>status</b> - see {@link TransactionStatus}
* <p>
* <b>source</b> - see {@link TransactionSource}
* <p>
* <b>grandTotal</b> - grand total for SHOP transaction (see source).
* <p>
* <b>discount</b> - discount for SHOP transaction (see source).
* <p>
* <b>currency</b> - specifies currency for money fields (grandTotal and discount). Check data types to discover which
* currencies are supported.
*/
public interface Transaction extends BaseEntity {
// Methods for working with properties
TransactionStatus getStatus();
void setStatus(TransactionStatus status);
TransactionSource getSource();
void setSource(TransactionSource source);
BigDecimal getGrandTotal();
void setGrandTotal(BigDecimal grandTotal);
BigDecimal getDiscount();
void setDiscount(BigDecimal discount);
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionSource.java
// public enum TransactionSource {
//
// /**
// * Shop transaction.
// */
// SHOP,
//
// /**
// * Auto transaction for license create.
// */
// AUTO_LICENSE_CREATE,
//
// /**
// * Auto transaction for license update.
// */
// AUTO_LICENSE_UPDATE,
//
// /**
// * Auto transaction for license delete.
// */
// AUTO_LICENSE_DELETE,
//
// /**
// * Auto transaction for licensee create (with automatic licenses).
// */
// AUTO_LICENSEE_CREATE,
//
// /**
// * Auto transaction for licensee delete with forceCascade.
// */
// AUTO_LICENSEE_DELETE,
//
// /**
// * Transaction for update license during validate
// */
// AUTO_LICENSEE_VALIDATE,
//
// /**
// * Auto transaction for license template delete with forceCascade.
// */
// AUTO_LICENSETEMPLATE_DELETE,
//
// /**
// * Auto transaction for product module delete with forceCascade.
// */
// AUTO_PRODUCTMODULE_DELETE,
//
// /**
// * Auto transaction for product delete with forceCascade.
// */
// AUTO_PRODUCT_DELETE,
//
// /**
// * Auto transaction for transfer licenses between licensee.
// */
// AUTO_LICENSES_TRANSFER,
//
// /**
// * Transaction for update licenses (inactive with PT LM, Subscription).
// */
// SUBSCRIPTION_UPDATE,
//
// /**
// * Transaction for cancel recurring payment.
// */
// CANCEL_RECURRING_PAYMENT
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/TransactionStatus.java
// public enum TransactionStatus {
//
// /**
// * Transaction still running.
// */
// PENDING,
//
// /**
// * Transaction is closed.
// */
// CLOSED,
//
// /**
// * Transaction is cancelled.
// */
// CANCELLED
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Transaction.java
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.labs64.netlicensing.domain.vo.Currency;
import com.labs64.netlicensing.domain.vo.TransactionSource;
import com.labs64.netlicensing.domain.vo.TransactionStatus;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Transaction entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products of a vendor) that identifies the transaction. This number is
* always generated by NetLicensing.
* <p>
* <b>active</b> - always true for transactions
* <p>
* <b>status</b> - see {@link TransactionStatus}
* <p>
* <b>source</b> - see {@link TransactionSource}
* <p>
* <b>grandTotal</b> - grand total for SHOP transaction (see source).
* <p>
* <b>discount</b> - discount for SHOP transaction (see source).
* <p>
* <b>currency</b> - specifies currency for money fields (grandTotal and discount). Check data types to discover which
* currencies are supported.
*/
public interface Transaction extends BaseEntity {
// Methods for working with properties
TransactionStatus getStatus();
void setStatus(TransactionStatus status);
TransactionSource getSource();
void setSource(TransactionSource source);
BigDecimal getGrandTotal();
void setGrandTotal(BigDecimal grandTotal);
BigDecimal getDiscount();
void setDiscount(BigDecimal discount);
| Currency getCurrency(); |
Labs64/NetLicensingClient-java | NetLicensingClient/src/test/java/com/labs64/netlicensing/service/NetLicensingServiceTest.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
| import javax.ws.rs.GET;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.BeforeClass;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.schema.context.ObjectFactory; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Common integration tests for {@link NetLicensingService}.
*/
public class NetLicensingServiceTest extends BaseServiceTest {
// *** NLIC Tests ***
private static Context context;
@BeforeClass
public static void setup() {
context = createContext();
}
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
// Path: NetLicensingClient/src/test/java/com/labs64/netlicensing/service/NetLicensingServiceTest.java
import javax.ws.rs.GET;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.BeforeClass;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.schema.context.ObjectFactory;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Common integration tests for {@link NetLicensingService}.
*/
public class NetLicensingServiceTest extends BaseServiceTest {
// *** NLIC Tests ***
private static Context context;
@BeforeClass
public static void setup() {
context = createContext();
}
| @Test(expected = RestException.class) |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/License.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
| import com.labs64.netlicensing.domain.vo.Currency;
import java.math.BigDecimal;
import java.util.Map; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* License entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products/licensees of a vendor) that identifies the license. Vendor can
* assign this number when creating a license or let NetLicensing generate one. Read-only after corresponding creation
* transaction status is set to closed.
* <p>
* <b>name</b> - Name for the licensed item. Set from license template on creation, if not specified explicitly.
* <p>
* <b>active</b> - If set to false, the license is disabled. License can be re-enabled, but as long as it is disabled,
* the license is excluded from the validation process.
* <p>
* <b>price</b> - price for the license. If more than 0, it must always be accompanied by the currency specification.
* Read-only, set from license template on creation.
* <p>
* <b>currency</b> - specifies currency for the license price. Check data types to discover which currencies are
* supported. Read-only, set from license template on creation.
* <p>
* <b>hidden</b> - If set to true, this license is not shown in NetLicensing Shop as purchased license. Set from license
* template on creation, if not specified explicitly.
* <p>
* Arbitrary additional user properties of string type may be associated with each license. The name of user property
* must not be equal to any of the fixed property names listed above and must be none of <b>id, licenseeNumber,
* licenseTemplateNumber</b>. See {@link com.labs64.netlicensing.schema.context.Property} for details.
*/
public interface License extends BaseEntity {
// Methods for working with properties
String getName();
void setName(String name);
BigDecimal getPrice();
void setPrice(BigDecimal price);
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Currency.java
// public enum Currency {
//
// NONE(""),
//
// EUR("EUR"),
//
// USD("USD");
//
// private final String value;
//
// /**
// * Instantiates a new currency.
// *
// * @param currency
// * currency value
// */
// Currency(final String currency) {
// value = currency;
// }
//
// /**
// * Get enum value.
// *
// * @return enum value
// */
// public String value() {
// return value;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// return value;
// }
//
// /**
// * Parse currency value to {@link Currency} enum.
// *
// * @param value
// * currency value
// * @return {@link Currency} enum object or throws {@link IllegalArgumentException} if no corresponding
// * {@link Currency} enum object found
// */
// public static Currency parseValue(final String value) {
// for (final Currency currency : Currency.values()) {
// if (currency.value.equalsIgnoreCase(value)) {
// return currency;
// }
// }
// if ((value != null) && StringUtils.isBlank(value)) {
// return NONE;
// }
// throw new IllegalArgumentException(value);
// }
//
// /**
// * Parse currency value to {@link Currency} enum, nothrow version.
// *
// * @param value
// * licenseType value as string
// * @return {@link Currency} enum object or {@code null} if argument doesn't match any of the enum values
// */
// public static Currency parseValueSafe(final String value) {
// try {
// return parseValue(value);
// } catch (final IllegalArgumentException e) {
// return null;
// }
// }
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/License.java
import com.labs64.netlicensing.domain.vo.Currency;
import java.math.BigDecimal;
import java.util.Map;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* License entity used internally by NetLicensing.
* <p>
* Properties visible via NetLicensing API:
* <p>
* <b>number</b> - Unique number (across all products/licensees of a vendor) that identifies the license. Vendor can
* assign this number when creating a license or let NetLicensing generate one. Read-only after corresponding creation
* transaction status is set to closed.
* <p>
* <b>name</b> - Name for the licensed item. Set from license template on creation, if not specified explicitly.
* <p>
* <b>active</b> - If set to false, the license is disabled. License can be re-enabled, but as long as it is disabled,
* the license is excluded from the validation process.
* <p>
* <b>price</b> - price for the license. If more than 0, it must always be accompanied by the currency specification.
* Read-only, set from license template on creation.
* <p>
* <b>currency</b> - specifies currency for the license price. Check data types to discover which currencies are
* supported. Read-only, set from license template on creation.
* <p>
* <b>hidden</b> - If set to true, this license is not shown in NetLicensing Shop as purchased license. Set from license
* template on creation, if not specified explicitly.
* <p>
* Arbitrary additional user properties of string type may be associated with each license. The name of user property
* must not be equal to any of the fixed property names listed above and must be none of <b>id, licenseeNumber,
* licenseTemplateNumber</b>. See {@link com.labs64.netlicensing.schema.context.Property} for details.
*/
public interface License extends BaseEntity {
// Methods for working with properties
String getName();
void setName(String name);
BigDecimal getPrice();
void setPrice(BigDecimal price);
| Currency getCurrency(); |
Labs64/NetLicensingClient-java | NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/utils/ConsoleWriter.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Page.java
// public interface Page<Entity> extends Iterable<Entity> {
//
// /**
// * Returns the number of the current page. Is always non-negative.
// *
// * @return the number of the current page.
// */
// int getPageNumber();
//
// /**
// * Returns the number of elements on the page.
// *
// * @return the number of elements on the page.
// */
// int getItemsNumber();
//
// /**
// * Returns the number of total pages.
// *
// * @return the number of total pages
// */
// int getTotalPages();
//
// /**
// * Returns the total amount of elements.
// *
// * @return the total amount of elements
// */
// long getTotalItems();
//
// /**
// * Returns if there is a next page exists.
// *
// * @return true if there is a next page exists, otherwise false.
// */
// boolean hasNext();
//
// /**
// * Return container content.
// *
// * @return container content
// */
// List<Entity> getContent();
//
// /**
// * Returns if there is a content exists.
// *
// * @return true if there is a content exists, otherwise false
// */
// boolean hasContent();
//
// }
| import com.labs64.netlicensing.domain.vo.Page;
import static java.lang.System.out; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.utils;
/**
* Utility class for writing to console
*/
public class ConsoleWriter {
public void writeMessage(final String msg) {
out.println(msg);
out.println();
}
public void writeException(final String msg, final Exception ex) {
out.println(msg);
ex.printStackTrace();
out.println();
}
public void writeObject(final String msg, final Object obj) {
out.println(msg);
out.println(obj);
out.println();
}
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Page.java
// public interface Page<Entity> extends Iterable<Entity> {
//
// /**
// * Returns the number of the current page. Is always non-negative.
// *
// * @return the number of the current page.
// */
// int getPageNumber();
//
// /**
// * Returns the number of elements on the page.
// *
// * @return the number of elements on the page.
// */
// int getItemsNumber();
//
// /**
// * Returns the number of total pages.
// *
// * @return the number of total pages
// */
// int getTotalPages();
//
// /**
// * Returns the total amount of elements.
// *
// * @return the total amount of elements
// */
// long getTotalItems();
//
// /**
// * Returns if there is a next page exists.
// *
// * @return true if there is a next page exists, otherwise false.
// */
// boolean hasNext();
//
// /**
// * Return container content.
// *
// * @return container content
// */
// List<Entity> getContent();
//
// /**
// * Returns if there is a content exists.
// *
// * @return true if there is a content exists, otherwise false
// */
// boolean hasContent();
//
// }
// Path: NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/utils/ConsoleWriter.java
import com.labs64.netlicensing.domain.vo.Page;
import static java.lang.System.out;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.utils;
/**
* Utility class for writing to console
*/
public class ConsoleWriter {
public void writeMessage(final String msg) {
out.println(msg);
out.println();
}
public void writeException(final String msg, final Exception ex) {
out.println(msg);
ex.printStackTrace();
out.println();
}
public void writeObject(final String msg, final Object obj) {
out.println(msg);
out.println(obj);
out.println();
}
| public void writePage(final String msg, final Page<?> page) { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProviderJersey.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
| import java.util.Map;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
* Low level REST client implementation.
* <p>
* This will also log each request in INFO level.
*/
public class RestProviderJersey extends AbstractRestProvider {
private static final MediaType[] DEFAULT_ACCEPT_TYPES = { MediaType.APPLICATION_XML_TYPE };
private static Client client;
private final String basePath;
private class JerseyDefaultConfig implements RestProvider.Configuration {
@Override
public String getUserAgent() {
return "NetLicensing/Java " + System.getProperty("java.version") + " (https://netlicensing.io)";
}
@Override
public boolean isLoggingEnabled() {
return true;
}
}
/**
* @param basePath
* base provider path
*/
public RestProviderJersey(final String basePath) {
this.basePath = basePath;
configure(new JerseyDefaultConfig());
}
/*
* @see com.labs64.netlicensing.provider.RestProvider#call(java.lang.String, java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
@Override
public <REQ, RES> RestResponse<RES> call(final String httpMethod, final String urlTemplate, final REQ request,
final Class<RES> responseType, | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProviderJersey.java
import java.util.Map;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
* Low level REST client implementation.
* <p>
* This will also log each request in INFO level.
*/
public class RestProviderJersey extends AbstractRestProvider {
private static final MediaType[] DEFAULT_ACCEPT_TYPES = { MediaType.APPLICATION_XML_TYPE };
private static Client client;
private final String basePath;
private class JerseyDefaultConfig implements RestProvider.Configuration {
@Override
public String getUserAgent() {
return "NetLicensing/Java " + System.getProperty("java.version") + " (https://netlicensing.io)";
}
@Override
public boolean isLoggingEnabled() {
return true;
}
}
/**
* @param basePath
* base provider path
*/
public RestProviderJersey(final String basePath) {
this.basePath = basePath;
configure(new JerseyDefaultConfig());
}
/*
* @see com.labs64.netlicensing.provider.RestProvider#call(java.lang.String, java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
@Override
public <REQ, RES> RestResponse<RES> call(final String httpMethod, final String urlTemplate, final REQ request,
final Class<RES> responseType, | final Map<String, Object> queryParams) throws RestException { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProviderJersey.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
| import java.util.Map;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication; | synchronized (RestProviderJersey.class) {
if (client == null) {
client = ClientBuilder.newClient(new ClientConfig());
if (configuration.isLoggingEnabled()) {
//TODO: enable logging for jersey 2.26
//client.register(new LoggingFilter());
}
}
}
}
return client;
}
/**
* Get the RESTful client target
*
* @param basePath
* base provider path
* @return RESTful client target
*/
private WebTarget getTarget(final String basePath) {
return getClient(getConfiguration()).target(basePath);
}
/**
* @param target
* target object, to which the authentication headers will be added
* @param auth
* an object providing the authentication info
*/ | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProviderJersey.java
import java.util.Map;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
synchronized (RestProviderJersey.class) {
if (client == null) {
client = ClientBuilder.newClient(new ClientConfig());
if (configuration.isLoggingEnabled()) {
//TODO: enable logging for jersey 2.26
//client.register(new LoggingFilter());
}
}
}
}
return client;
}
/**
* Get the RESTful client target
*
* @param basePath
* base provider path
* @return RESTful client target
*/
private WebTarget getTarget(final String basePath) {
return getClient(getConfiguration()).target(basePath);
}
/**
* @param target
* target object, to which the authentication headers will be added
* @param auth
* an object providing the authentication info
*/ | private void addAuthHeaders(final WebTarget target, final Authentication auth) { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/util/SignatureUtils.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/BadSignatureException.java
// public class BadSignatureException extends NetLicensingException {
//
// private static final long serialVersionUID = -506669705393514519L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public BadSignatureException(final String msg) {
// super(msg);
// }
//
// }
| import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import com.helger.xmldsig.XMLDSigValidationResult;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.BadSignatureException;
import com.labs64.netlicensing.schema.context.Netlicensing; | package com.labs64.netlicensing.util;
public class SignatureUtils {
/**
* Cleanse public key; replace CRLF and strip key headers
* @param publicKey
* @return cleansed public key
*/
public static String cleansePublicKey(final String publicKey) {
if (publicKey == null) {
return publicKey;
} else {
return publicKey.replaceAll("\\n|\\r", "").replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "");
}
}
/**
* Read public key from the byte array
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final byte[] publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
final byte[] publicKeyByte = Base64.getDecoder().decode(publicKey);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyByte);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* Read public key from the string
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final String publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return readPublicKey(publicKey.getBytes());
}
/**
* Verify response signature.
* @param context
* @param response
* @throws BadSignatureException
*/ | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/BadSignatureException.java
// public class BadSignatureException extends NetLicensingException {
//
// private static final long serialVersionUID = -506669705393514519L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public BadSignatureException(final String msg) {
// super(msg);
// }
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/util/SignatureUtils.java
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import com.helger.xmldsig.XMLDSigValidationResult;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.BadSignatureException;
import com.labs64.netlicensing.schema.context.Netlicensing;
package com.labs64.netlicensing.util;
public class SignatureUtils {
/**
* Cleanse public key; replace CRLF and strip key headers
* @param publicKey
* @return cleansed public key
*/
public static String cleansePublicKey(final String publicKey) {
if (publicKey == null) {
return publicKey;
} else {
return publicKey.replaceAll("\\n|\\r", "").replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "");
}
}
/**
* Read public key from the byte array
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final byte[] publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
final byte[] publicKeyByte = Base64.getDecoder().decode(publicKey);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyByte);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* Read public key from the string
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final String publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return readPublicKey(publicKey.getBytes());
}
/**
* Verify response signature.
* @param context
* @param response
* @throws BadSignatureException
*/ | public static void check(final Context context, final Netlicensing response) throws BadSignatureException { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/util/SignatureUtils.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/BadSignatureException.java
// public class BadSignatureException extends NetLicensingException {
//
// private static final long serialVersionUID = -506669705393514519L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public BadSignatureException(final String msg) {
// super(msg);
// }
//
// }
| import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import com.helger.xmldsig.XMLDSigValidationResult;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.BadSignatureException;
import com.labs64.netlicensing.schema.context.Netlicensing; | package com.labs64.netlicensing.util;
public class SignatureUtils {
/**
* Cleanse public key; replace CRLF and strip key headers
* @param publicKey
* @return cleansed public key
*/
public static String cleansePublicKey(final String publicKey) {
if (publicKey == null) {
return publicKey;
} else {
return publicKey.replaceAll("\\n|\\r", "").replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "");
}
}
/**
* Read public key from the byte array
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final byte[] publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
final byte[] publicKeyByte = Base64.getDecoder().decode(publicKey);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyByte);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* Read public key from the string
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final String publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return readPublicKey(publicKey.getBytes());
}
/**
* Verify response signature.
* @param context
* @param response
* @throws BadSignatureException
*/ | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/BadSignatureException.java
// public class BadSignatureException extends NetLicensingException {
//
// private static final long serialVersionUID = -506669705393514519L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public BadSignatureException(final String msg) {
// super(msg);
// }
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/util/SignatureUtils.java
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import com.helger.xmldsig.XMLDSigValidationResult;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.exception.BadSignatureException;
import com.labs64.netlicensing.schema.context.Netlicensing;
package com.labs64.netlicensing.util;
public class SignatureUtils {
/**
* Cleanse public key; replace CRLF and strip key headers
* @param publicKey
* @return cleansed public key
*/
public static String cleansePublicKey(final String publicKey) {
if (publicKey == null) {
return publicKey;
} else {
return publicKey.replaceAll("\\n|\\r", "").replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "");
}
}
/**
* Read public key from the byte array
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final byte[] publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
final byte[] publicKeyByte = Base64.getDecoder().decode(publicKey);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyByte);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* Read public key from the string
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey readPublicKey(final String publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return readPublicKey(publicKey.getBytes());
}
/**
* Verify response signature.
* @param context
* @param response
* @throws BadSignatureException
*/ | public static void check(final Context context, final Netlicensing response) throws BadSignatureException { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/schema/converter/ItemToPaymentMethodConverter.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/PaymentMethod.java
// public interface PaymentMethod extends BaseEntity {
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getPaymentMethodProperties();
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/PaymentMethodImpl.java
// public class PaymentMethodImpl extends BaseEntityImpl implements PaymentMethod {
//
// private static final long serialVersionUID = -529417516632266683L;
//
// /**
// * @see BaseEntityImpl#getReservedProps()
// */
// public static List<String> getReservedProps() {
// return BaseEntityImpl.getReservedProps();
// }
//
// @Override
// public Map<String, String> getPaymentMethodProperties() {
// return getProperties();
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/ConversionException.java
// public class ConversionException extends NetLicensingException {
//
// private static final long serialVersionUID = -3798344733724547819L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public ConversionException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public ConversionException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
| import com.labs64.netlicensing.domain.entity.PaymentMethod;
import com.labs64.netlicensing.domain.entity.impl.PaymentMethodImpl;
import com.labs64.netlicensing.exception.ConversionException;
import com.labs64.netlicensing.schema.context.Item;
import com.labs64.netlicensing.schema.context.Property; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.schema.converter;
/**
* Convert {@link Item} entity into {@link PaymentMethod} object.
*/
public class ItemToPaymentMethodConverter extends ItemToEntityBaseConverter<PaymentMethod> {
@Override | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/PaymentMethod.java
// public interface PaymentMethod extends BaseEntity {
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getPaymentMethodProperties();
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/PaymentMethodImpl.java
// public class PaymentMethodImpl extends BaseEntityImpl implements PaymentMethod {
//
// private static final long serialVersionUID = -529417516632266683L;
//
// /**
// * @see BaseEntityImpl#getReservedProps()
// */
// public static List<String> getReservedProps() {
// return BaseEntityImpl.getReservedProps();
// }
//
// @Override
// public Map<String, String> getPaymentMethodProperties() {
// return getProperties();
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/ConversionException.java
// public class ConversionException extends NetLicensingException {
//
// private static final long serialVersionUID = -3798344733724547819L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public ConversionException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public ConversionException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/schema/converter/ItemToPaymentMethodConverter.java
import com.labs64.netlicensing.domain.entity.PaymentMethod;
import com.labs64.netlicensing.domain.entity.impl.PaymentMethodImpl;
import com.labs64.netlicensing.exception.ConversionException;
import com.labs64.netlicensing.schema.context.Item;
import com.labs64.netlicensing.schema.context.Property;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.schema.converter;
/**
* Convert {@link Item} entity into {@link PaymentMethod} object.
*/
public class ItemToPaymentMethodConverter extends ItemToEntityBaseConverter<PaymentMethod> {
@Override | public PaymentMethod convert(final Item source) throws ConversionException { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/schema/converter/ItemToPaymentMethodConverter.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/PaymentMethod.java
// public interface PaymentMethod extends BaseEntity {
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getPaymentMethodProperties();
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/PaymentMethodImpl.java
// public class PaymentMethodImpl extends BaseEntityImpl implements PaymentMethod {
//
// private static final long serialVersionUID = -529417516632266683L;
//
// /**
// * @see BaseEntityImpl#getReservedProps()
// */
// public static List<String> getReservedProps() {
// return BaseEntityImpl.getReservedProps();
// }
//
// @Override
// public Map<String, String> getPaymentMethodProperties() {
// return getProperties();
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/ConversionException.java
// public class ConversionException extends NetLicensingException {
//
// private static final long serialVersionUID = -3798344733724547819L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public ConversionException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public ConversionException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
| import com.labs64.netlicensing.domain.entity.PaymentMethod;
import com.labs64.netlicensing.domain.entity.impl.PaymentMethodImpl;
import com.labs64.netlicensing.exception.ConversionException;
import com.labs64.netlicensing.schema.context.Item;
import com.labs64.netlicensing.schema.context.Property; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.schema.converter;
/**
* Convert {@link Item} entity into {@link PaymentMethod} object.
*/
public class ItemToPaymentMethodConverter extends ItemToEntityBaseConverter<PaymentMethod> {
@Override
public PaymentMethod convert(final Item source) throws ConversionException {
final PaymentMethod target = super.convert(source);
// Custom properties
for (final Property property : source.getProperty()) { | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/PaymentMethod.java
// public interface PaymentMethod extends BaseEntity {
//
// // Methods for working with custom properties
//
// @Deprecated
// Map<String, String> getPaymentMethodProperties();
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/impl/PaymentMethodImpl.java
// public class PaymentMethodImpl extends BaseEntityImpl implements PaymentMethod {
//
// private static final long serialVersionUID = -529417516632266683L;
//
// /**
// * @see BaseEntityImpl#getReservedProps()
// */
// public static List<String> getReservedProps() {
// return BaseEntityImpl.getReservedProps();
// }
//
// @Override
// public Map<String, String> getPaymentMethodProperties() {
// return getProperties();
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/ConversionException.java
// public class ConversionException extends NetLicensingException {
//
// private static final long serialVersionUID = -3798344733724547819L;
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public ConversionException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>ConversionException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public ConversionException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/schema/converter/ItemToPaymentMethodConverter.java
import com.labs64.netlicensing.domain.entity.PaymentMethod;
import com.labs64.netlicensing.domain.entity.impl.PaymentMethodImpl;
import com.labs64.netlicensing.exception.ConversionException;
import com.labs64.netlicensing.schema.context.Item;
import com.labs64.netlicensing.schema.context.Property;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.schema.converter;
/**
* Convert {@link Item} entity into {@link PaymentMethod} object.
*/
public class ItemToPaymentMethodConverter extends ItemToEntityBaseConverter<PaymentMethod> {
@Override
public PaymentMethod convert(final Item source) throws ConversionException {
final PaymentMethod target = super.convert(source);
// Custom properties
for (final Property property : source.getProperty()) { | if (!PaymentMethodImpl.getReservedProps().contains(property.getName())) { |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Token.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/ITokenType.java
// public interface ITokenType {
//
// String name();
//
// }
| import com.labs64.netlicensing.domain.vo.ITokenType;
import java.util.Date;
import java.util.Map; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Token entity used internally by NetLicensing.
*/
public interface Token extends BaseEntity {
// Methods for working with properties
String getVendorNumber();
void setVendorNumber(String vendorNumber);
Date getExpirationTime();
void setExpirationTime(Date expirationTime);
| // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/ITokenType.java
// public interface ITokenType {
//
// String name();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/entity/Token.java
import com.labs64.netlicensing.domain.vo.ITokenType;
import java.util.Date;
import java.util.Map;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.entity;
/**
* Token entity used internally by NetLicensing.
*/
public interface Token extends BaseEntity {
// Methods for working with properties
String getVendorNumber();
void setVendorNumber(String vendorNumber);
Date getExpirationTime();
void setExpirationTime(Date expirationTime);
| ITokenType getTokenType(); |
Labs64/NetLicensingClient-java | NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/demo/NetLicensingClientDemo.java | // Path: NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/examples/NetLicensingExample.java
// public interface NetLicensingExample {
//
// void execute();
//
// }
| import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.labs64.netlicensing.examples.NetLicensingExample; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.demo;
public class NetLicensingClientDemo {
public static void main(final String[] args) {
final Options options = new Options();
options.addOption("l", false, "list available examples");
options.addOption("r", true, "run specified example");
final CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (final ParseException e) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar netlicensing-client-demo.jar <option>", options);
return;
}
if (cmd.hasOption("l")) {
System.out.println("Available examples:");
AllExamples.list.forEach((key, val) -> {
System.out.println(" " + key);
});
return;
}
String exampleToRun = cmd.getOptionValue("r");
if (exampleToRun == null) {
exampleToRun = AllExamples.list.keySet().iterator().next();
}
if (AllExamples.list.containsKey(exampleToRun)) { | // Path: NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/examples/NetLicensingExample.java
// public interface NetLicensingExample {
//
// void execute();
//
// }
// Path: NetLicensingClient-demo/src/main/java/com/labs64/netlicensing/demo/NetLicensingClientDemo.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.labs64.netlicensing.examples.NetLicensingExample;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.demo;
public class NetLicensingClientDemo {
public static void main(final String[] args) {
final Options options = new Options();
options.addOption("l", false, "list available examples");
options.addOption("r", true, "run specified example");
final CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (final ParseException e) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar netlicensing-client-demo.jar <option>", options);
return;
}
if (cmd.hasOption("l")) {
System.out.println("Available examples:");
AllExamples.list.forEach((key, val) -> {
System.out.println(" " + key);
});
return;
}
String exampleToRun = cmd.getOptionValue("r");
if (exampleToRun == null) {
exampleToRun = AllExamples.list.keySet().iterator().next();
}
if (AllExamples.list.containsKey(exampleToRun)) { | NetLicensingExample ex; |
Labs64/NetLicensingClient-java | NetLicensingClient/src/test/java/com/labs64/netlicensing/service/SecurityTest.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/SecurityMode.java
// public enum SecurityMode {
//
// BASIC_AUTHENTICATION, APIKEY_IDENTIFICATION, ANONYMOUS_IDENTIFICATION
//
// }
| import java.util.Base64;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.domain.vo.SecurityMode;
import com.labs64.netlicensing.schema.context.Info;
import com.labs64.netlicensing.schema.context.Netlicensing;
import com.labs64.netlicensing.schema.context.ObjectFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Tests for checking the ability to connect to services using different security modes
*/
public class SecurityTest extends BaseServiceTest {
// *** NLIC Tests ***
@Test
public void testBasicAuthentication() throws Exception { | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/SecurityMode.java
// public enum SecurityMode {
//
// BASIC_AUTHENTICATION, APIKEY_IDENTIFICATION, ANONYMOUS_IDENTIFICATION
//
// }
// Path: NetLicensingClient/src/test/java/com/labs64/netlicensing/service/SecurityTest.java
import java.util.Base64;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.domain.vo.SecurityMode;
import com.labs64.netlicensing.schema.context.Info;
import com.labs64.netlicensing.schema.context.Netlicensing;
import com.labs64.netlicensing.schema.context.ObjectFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Tests for checking the ability to connect to services using different security modes
*/
public class SecurityTest extends BaseServiceTest {
// *** NLIC Tests ***
@Test
public void testBasicAuthentication() throws Exception { | final Context context = new Context() |
Labs64/NetLicensingClient-java | NetLicensingClient/src/test/java/com/labs64/netlicensing/service/SecurityTest.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/SecurityMode.java
// public enum SecurityMode {
//
// BASIC_AUTHENTICATION, APIKEY_IDENTIFICATION, ANONYMOUS_IDENTIFICATION
//
// }
| import java.util.Base64;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.domain.vo.SecurityMode;
import com.labs64.netlicensing.schema.context.Info;
import com.labs64.netlicensing.schema.context.Netlicensing;
import com.labs64.netlicensing.schema.context.ObjectFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Tests for checking the ability to connect to services using different security modes
*/
public class SecurityTest extends BaseServiceTest {
// *** NLIC Tests ***
@Test
public void testBasicAuthentication() throws Exception {
final Context context = new Context()
.setBaseUrl(BASE_URL) | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Context.java
// public class Context extends GenericContext<String> {
//
// private String publicKey;
//
// public Context() {
// super(String.class);
// }
//
// public Context setBaseUrl(final String baseUrl) {
// return (Context) this.setValue(Constants.BASE_URL, baseUrl);
// }
//
// public String getBaseUrl() {
// return getValue(Constants.BASE_URL);
// }
//
// public Context setUsername(final String username) {
// return (Context) this.setValue(Constants.USERNAME, username);
// }
//
// public String getUsername() {
// return getValue(Constants.USERNAME);
// }
//
// public Context setPassword(final String password) {
// return (Context) this.setValue(Constants.PASSWORD, password);
// }
//
// public String getPassword() {
// return getValue(Constants.PASSWORD);
// }
//
// public Context setApiKey(final String apiKey) {
// return (Context) this.setValue(Constants.Token.API_KEY, apiKey);
// }
//
// public String getApiKey() {
// return getValue(Constants.Token.API_KEY);
// }
//
// public Context setSecurityMode(final SecurityMode securityMode) {
// return (Context) this.setValue(Constants.SECURITY_MODE, securityMode.toString());
// }
//
// public SecurityMode getSecurityMode() {
// final String securityMode = getValue(Constants.SECURITY_MODE);
// return securityMode != null ? SecurityMode.valueOf(securityMode) : null;
// }
//
// public Context setVendorNumber(final String vendorNumber) {
// return (Context) this.setValue(Constants.Vendor.VENDOR_NUMBER, vendorNumber);
// }
//
// public String getVendorNumber() {
// return getValue(Constants.Vendor.VENDOR_NUMBER);
// }
//
// /**
// * Add public key to be used for validate signed NetLicensing response.
// *
// * @param publicKey
// * client publicKey.
// */
// public void setPublicKey(final String publicKey) {
// this.publicKey = publicKey;
// }
//
// public String getPublicKey() {
// return publicKey;
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/SecurityMode.java
// public enum SecurityMode {
//
// BASIC_AUTHENTICATION, APIKEY_IDENTIFICATION, ANONYMOUS_IDENTIFICATION
//
// }
// Path: NetLicensingClient/src/test/java/com/labs64/netlicensing/service/SecurityTest.java
import java.util.Base64;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.domain.vo.SecurityMode;
import com.labs64.netlicensing.schema.context.Info;
import com.labs64.netlicensing.schema.context.Netlicensing;
import com.labs64.netlicensing.schema.context.ObjectFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.service;
/**
* Tests for checking the ability to connect to services using different security modes
*/
public class SecurityTest extends BaseServiceTest {
// *** NLIC Tests ***
@Test
public void testBasicAuthentication() throws Exception {
final Context context = new Context()
.setBaseUrl(BASE_URL) | .setSecurityMode(SecurityMode.BASIC_AUTHENTICATION) |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProvider.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
| import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
import java.util.Map; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
*/
public interface RestProvider {
public interface Configuration {
String getUserAgent();
boolean isLoggingEnabled();
}
/**
* Helper method for performing REST requests with optional REST parameter map.
* <p>
* This method has a long list of parameters. It is only intended for internal use.
*
* @param method
* the HTTP method to be used, i.e. GET, PUT, POST.
* @param urlTemplate
* the REST URL urlTemplate.
* @param request
* optional: The request body to be sent to the server. May be null.
* @param responseType
* optional: expected response type. In case no responseType body is expected, responseType may be null.
* @param queryParams
* optional: The REST query parameters values. May be null.
* @param <REQ>
* type of the request entity
* @param <RES>
* type of the responseType entity
* @return the responseType entity received from the server, or null if responseType is null.
*/
<REQ, RES> RestResponse<RES> call(String method, String urlTemplate, REQ request, Class<RES> responseType, | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProvider.java
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
import java.util.Map;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
*/
public interface RestProvider {
public interface Configuration {
String getUserAgent();
boolean isLoggingEnabled();
}
/**
* Helper method for performing REST requests with optional REST parameter map.
* <p>
* This method has a long list of parameters. It is only intended for internal use.
*
* @param method
* the HTTP method to be used, i.e. GET, PUT, POST.
* @param urlTemplate
* the REST URL urlTemplate.
* @param request
* optional: The request body to be sent to the server. May be null.
* @param responseType
* optional: expected response type. In case no responseType body is expected, responseType may be null.
* @param queryParams
* optional: The REST query parameters values. May be null.
* @param <REQ>
* type of the request entity
* @param <RES>
* type of the responseType entity
* @return the responseType entity received from the server, or null if responseType is null.
*/
<REQ, RES> RestResponse<RES> call(String method, String urlTemplate, REQ request, Class<RES> responseType, | Map<String, Object> queryParams) throws RestException; |
Labs64/NetLicensingClient-java | NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProvider.java | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
| import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
import java.util.Map; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
*/
public interface RestProvider {
public interface Configuration {
String getUserAgent();
boolean isLoggingEnabled();
}
/**
* Helper method for performing REST requests with optional REST parameter map.
* <p>
* This method has a long list of parameters. It is only intended for internal use.
*
* @param method
* the HTTP method to be used, i.e. GET, PUT, POST.
* @param urlTemplate
* the REST URL urlTemplate.
* @param request
* optional: The request body to be sent to the server. May be null.
* @param responseType
* optional: expected response type. In case no responseType body is expected, responseType may be null.
* @param queryParams
* optional: The REST query parameters values. May be null.
* @param <REQ>
* type of the request entity
* @param <RES>
* type of the responseType entity
* @return the responseType entity received from the server, or null if responseType is null.
*/
<REQ, RES> RestResponse<RES> call(String method, String urlTemplate, REQ request, Class<RES> responseType,
Map<String, Object> queryParams) throws RestException;
/**
* @param username
* username used for authentication
* @param password
* password used for authentication
* @return authenticated RESTful provider
*/
RestProvider authenticate(String username, String password);
/**
* @param token
* token used for authentication
* @return authenticated RESTful provider
*/
RestProvider authenticate(String token);
/**
* @param authentication
* {@link Authentication} object
* @return authenticated RESTful provider
*/ | // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/exception/RestException.java
// public class RestException extends NetLicensingException {
//
// private static final long serialVersionUID = -3863879794574523844L;
//
// /**
// * Construct a <code>RestException</code> with the specified detail message.
// *
// * @param msg
// * the detail message
// */
// public RestException(final String msg) {
// super(msg);
// }
//
// /**
// * Construct a <code>RestException</code> with the specified detail message and cause exception.
// *
// * @param msg
// * the detail message
// * @param cause
// * the cause exception
// */
// public RestException(final String msg, final Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java
// public interface Authentication {
//
// String getUsername();
//
// String getPassword();
//
// }
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/RestProvider.java
import com.labs64.netlicensing.exception.RestException;
import com.labs64.netlicensing.provider.auth.Authentication;
import java.util.Map;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.provider;
/**
*/
public interface RestProvider {
public interface Configuration {
String getUserAgent();
boolean isLoggingEnabled();
}
/**
* Helper method for performing REST requests with optional REST parameter map.
* <p>
* This method has a long list of parameters. It is only intended for internal use.
*
* @param method
* the HTTP method to be used, i.e. GET, PUT, POST.
* @param urlTemplate
* the REST URL urlTemplate.
* @param request
* optional: The request body to be sent to the server. May be null.
* @param responseType
* optional: expected response type. In case no responseType body is expected, responseType may be null.
* @param queryParams
* optional: The REST query parameters values. May be null.
* @param <REQ>
* type of the request entity
* @param <RES>
* type of the responseType entity
* @return the responseType entity received from the server, or null if responseType is null.
*/
<REQ, RES> RestResponse<RES> call(String method, String urlTemplate, REQ request, Class<RES> responseType,
Map<String, Object> queryParams) throws RestException;
/**
* @param username
* username used for authentication
* @param password
* password used for authentication
* @return authenticated RESTful provider
*/
RestProvider authenticate(String username, String password);
/**
* @param token
* token used for authentication
* @return authenticated RESTful provider
*/
RestProvider authenticate(String token);
/**
* @param authentication
* {@link Authentication} object
* @return authenticated RESTful provider
*/ | RestProvider authenticate(Authentication authentication); |
matthewcmead/sleet | src/main/java/sleet/generators/IdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/id/IdType.java
// public interface IdType<T, E extends IdError> {
// public T getId();
//
// public E getError();
//
// public int getNumBitsInId();
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.id.IdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators;
public interface IdGenerator<T extends IdType<?, ?>> {
public void beginIdSession(Properties config) throws SleetException;
public void checkSessionValidity() throws SleetException;
public void endIdSession() throws SleetException;
| // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/id/IdType.java
// public interface IdType<T, E extends IdError> {
// public T getId();
//
// public E getError();
//
// public int getNumBitsInId();
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/IdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.id.IdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators;
public interface IdGenerator<T extends IdType<?, ?>> {
public void beginIdSession(Properties config) throws SleetException;
public void checkSessionValidity() throws SleetException;
public void endIdSession() throws SleetException;
| public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException; |
matthewcmead/sleet | src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
| // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
| private LongId value = null; |
matthewcmead/sleet | src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override | public void beginIdSession(Properties config) throws SleetException { |
matthewcmead/sleet | src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.value != null) { | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.value != null) { | throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()"); |
matthewcmead/sleet | src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.value != null) {
throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()");
}
String valueStr = config.getProperty(FIXED_LONG_VALUE_KEY);
if (valueStr == null) { | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.fixed;
public class FixedLongIdGenerator implements IdGenerator<LongIdType> {
public static final String FIXED_LONG_VALUE_KEY = "fixed.long.value";
public static final String FIXED_BITS_IN_ID_KEY = "fixed.bits.in.value";
private LongId value = null;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.value != null) {
throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()");
}
String valueStr = config.getProperty(FIXED_LONG_VALUE_KEY);
if (valueStr == null) { | throw new GeneratorConfigException("Missing value for fixed long id generation, must be specified in configuration properties key \"" + FIXED_LONG_VALUE_KEY + "\"."); |
matthewcmead/sleet | src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState; | String bitsStr = config.getProperty(FIXED_BITS_IN_ID_KEY);
if (bitsStr == null) {
throw new GeneratorConfigException("Missing number of bits for the fixed value, must be specified in configuration properties key \"" + FIXED_BITS_IN_ID_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \"" + FIXED_BITS_IN_ID_KEY + "\" must be a long.");
}
if ((1L << bits) - 1L < value) {
throw new GeneratorConfigException("Specified value of " + value + " exceeds the capacity of the number of bits specified (" + bits + ").");
}
this.value = new LongId(value, null, bits);
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.value = null;
}
@Override | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/fixed/FixedLongIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.state.IdState;
String bitsStr = config.getProperty(FIXED_BITS_IN_ID_KEY);
if (bitsStr == null) {
throw new GeneratorConfigException("Missing number of bits for the fixed value, must be specified in configuration properties key \"" + FIXED_BITS_IN_ID_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \"" + FIXED_BITS_IN_ID_KEY + "\" must be a long.");
}
if ((1L << bits) - 1L < value) {
throw new GeneratorConfigException("Specified value of " + value + " exceeds the capacity of the number of bits specified (" + bits + ").");
}
this.value = new LongId(value, null, bits);
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.value = null;
}
@Override | public LongIdType getId(List<IdState<?, ?>> states) throws SleetException { |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override | public void beginIdSession(Properties config) throws SleetException { |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.maxSequenceValue != -1) { | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.maxSequenceValue != -1) { | throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()"); |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.maxSequenceValue != -1) {
throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()");
}
String bitsStr = config.getProperty(BITS_IN_SEQUENCE_KEY);
if (bitsStr == null) { | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.maxSequenceValue != -1) {
throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()");
}
String bitsStr = config.getProperty(BITS_IN_SEQUENCE_KEY);
if (bitsStr == null) { | throw new GeneratorConfigException("Missing number of bits for the sequence value, must be specified in configuration properties key \"" |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | String bitsStr = config.getProperty(BITS_IN_SEQUENCE_KEY);
if (bitsStr == null) {
throw new GeneratorConfigException("Missing number of bits for the sequence value, must be specified in configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\" must be a long.");
}
this.bits = bits;
this.maxSequenceValue = (1L << bits) - 1L;
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
String bitsStr = config.getProperty(BITS_IN_SEQUENCE_KEY);
if (bitsStr == null) {
throw new GeneratorConfigException("Missing number of bits for the sequence value, must be specified in configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\" must be a long.");
}
this.bits = bits;
this.maxSequenceValue = (1L << bits) - 1L;
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override | public LongIdType getId(List<IdState<?, ?>> states) throws SleetException { |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | throw new GeneratorConfigException("Missing number of bits for the sequence value, must be specified in configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\" must be a long.");
}
this.bits = bits;
this.maxSequenceValue = (1L << bits) - 1L;
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override
public LongIdType getId(List<IdState<?, ?>> states) throws SleetException {
validateSessionStarted(); | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
throw new GeneratorConfigException("Missing number of bits for the sequence value, must be specified in configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\".");
}
int bits = -1;
try {
bits = Integer.valueOf(bitsStr);
} catch (NumberFormatException e) {
throw new GeneratorConfigException("Failed to parse number of bits from value \"" + bitsStr + "\". The value for configuration properties key \""
+ BITS_IN_SEQUENCE_KEY + "\" must be a long.");
}
this.bits = bits;
this.maxSequenceValue = (1L << bits) - 1L;
}
@Override
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override
public LongIdType getId(List<IdState<?, ?>> states) throws SleetException {
validateSessionStarted(); | TimeIdType timeIdType = null; |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
| import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override
public LongIdType getId(List<IdState<?, ?>> states) throws SleetException {
validateSessionStarted();
TimeIdType timeIdType = null;
for (IdState<?, ?> state : states) {
if (state.getId() instanceof TimeIdType) {
if (timeIdType == null) {
timeIdType = (TimeIdType) state.getId();
} else {
throw new TimeDependencyException(this.getClass().getName() + " depends on there being a single preceeding TimeIdType id, but found at least two.");
}
}
}
if (timeIdType == null) {
throw new TimeDependencyException(this.getClass().getName() + " depends on there being a single preceeding TimeIdType id, but found none.");
}
long currentTimeValue = timeIdType.getId();
long returnValue = -1;
if (currentTimeValue < this.lastTimeValue) { | // Path: src/main/java/sleet/SleetException.java
// public class SleetException extends Exception {
//
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -404982431470350032L;
//
// public SleetException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SleetException(String message) {
// super(message);
// }
//
// public SleetException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorConfigException.java
// public class GeneratorConfigException extends GeneratorException {
// /**
// * generated by eclipse
// */
// private static final long serialVersionUID = -2894157024668803650L;
//
// public GeneratorConfigException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorConfigException(String message) {
// super(message);
// }
//
// public GeneratorConfigException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/GeneratorSessionException.java
// public class GeneratorSessionException extends GeneratorException {
// /**
// * generated by eclipse
// */
//
// private static final long serialVersionUID = -5663201042060915360L;
//
// public GeneratorSessionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GeneratorSessionException(String message) {
// super(message);
// }
//
// public GeneratorSessionException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: src/main/java/sleet/generators/IdGenerator.java
// public interface IdGenerator<T extends IdType<?, ?>> {
// public void beginIdSession(Properties config) throws SleetException;
//
// public void checkSessionValidity() throws SleetException;
//
// public void endIdSession() throws SleetException;
//
// public IdType<?, ?> getId(List<IdState<?, ?>> states) throws SleetException;
// }
//
// Path: src/main/java/sleet/id/LongId.java
// public class LongId implements LongIdType {
// private final long value;
// private final int numBits;
// private final IdError error;
//
// public LongId(long value, IdError error, int numBits) {
// this.value = value;
// this.error = error;
// this.numBits = numBits;
// }
//
// @Override
// public Long getId() {
// return this.value;
// }
//
// @Override
// public IdError getError() {
// return this.error;
// }
//
// @Override
// public int getNumBitsInId() {
// return this.numBits;
// }
//
// }
//
// Path: src/main/java/sleet/id/LongIdType.java
// public interface LongIdType extends IdType<Long, IdError> {
//
// }
//
// Path: src/main/java/sleet/id/TimeIdType.java
// public interface TimeIdType extends IdType<Long, TimeIdError> {
//
// }
//
// Path: src/main/java/sleet/state/IdState.java
// public class IdState<T, E extends IdError> {
// private Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass;
// private IdType<T, E> id;
//
// public IdState(Class<? extends IdGenerator<? extends IdType<T, E>>> generatorClass, IdType<T, E> id) {
// this.generatorClass = generatorClass;
// this.id = id;
// }
//
// public Class<? extends IdGenerator<? extends IdType<T, E>>> getGeneratorClass() {
// return generatorClass;
// }
//
// public IdType<T, E> getId() {
// return id;
// }
// }
// Path: src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java
import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState;
public void checkSessionValidity() throws SleetException {
validateSessionStarted();
}
@Override
public void endIdSession() throws SleetException {
validateSessionStarted();
this.maxSequenceValue = -1;
}
@Override
public LongIdType getId(List<IdState<?, ?>> states) throws SleetException {
validateSessionStarted();
TimeIdType timeIdType = null;
for (IdState<?, ?> state : states) {
if (state.getId() instanceof TimeIdType) {
if (timeIdType == null) {
timeIdType = (TimeIdType) state.getId();
} else {
throw new TimeDependencyException(this.getClass().getName() + " depends on there being a single preceeding TimeIdType id, but found at least two.");
}
}
}
if (timeIdType == null) {
throw new TimeDependencyException(this.getClass().getName() + " depends on there being a single preceeding TimeIdType id, but found none.");
}
long currentTimeValue = timeIdType.getId();
long returnValue = -1;
if (currentTimeValue < this.lastTimeValue) { | return new LongId(-1, new TimeIdReverseSkewError(this.getClass().getName() |
DDTH/ddth-kafka | src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java | // Path: src/main/java/com/github/ddth/kafka/KafkaClient.java
// public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS;
// public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };}
//
// Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java
// public class KafkaTopicPartitionOffset {
// public final String topic;
// public final int partition;
// public final long offset;
//
// public KafkaTopicPartitionOffset(String topic, int partition, long offset) {
// this.topic = topic;
// this.partition = partition;
// this.offset = offset;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// ToStringBuilder tsb = new ToStringBuilder(this);
// tsb.append("topic", topic).append("partition", partition).append("offset", offset);
// return tsb.build();
// }
// }
| import com.github.ddth.kafka.KafkaClient.ProducerType;
import com.github.ddth.kafka.KafkaTopicPartitionOffset;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package com.github.ddth.kafka.internal;
/**
* Helper utility class.
*
* @author Thanh Ba Nguyen <[email protected]>
* @since 1.2.0
*/
public class KafkaHelper {
/**
* Helper method to create a {@link ExecutorService} instance (internal use).
*
* @param es
* @return
*/
public static ExecutorService createExecutorServiceIfNull(ExecutorService es) {
if (es == null) {
int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4);
es = Executors.newFixedThreadPool(numThreads);
}
return es;
}
/**
* Helper method to shutdown a {@link ExecutorService} instance (internal use).
*
* @param es
*/
public static void destroyExecutorService(ExecutorService es) {
if (es != null) {
es.shutdownNow();
}
}
/**
* Seek to a specified offset.
*
* @param consumer
* @param tpo
* @return {@code true} if the consumer has subscribed to the specified
* topic/partition, {@code false} otherwise.
* @since 1.3.2
*/ | // Path: src/main/java/com/github/ddth/kafka/KafkaClient.java
// public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS;
// public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };}
//
// Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java
// public class KafkaTopicPartitionOffset {
// public final String topic;
// public final int partition;
// public final long offset;
//
// public KafkaTopicPartitionOffset(String topic, int partition, long offset) {
// this.topic = topic;
// this.partition = partition;
// this.offset = offset;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// ToStringBuilder tsb = new ToStringBuilder(this);
// tsb.append("topic", topic).append("partition", partition).append("offset", offset);
// return tsb.build();
// }
// }
// Path: src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java
import com.github.ddth.kafka.KafkaClient.ProducerType;
import com.github.ddth.kafka.KafkaTopicPartitionOffset;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package com.github.ddth.kafka.internal;
/**
* Helper utility class.
*
* @author Thanh Ba Nguyen <[email protected]>
* @since 1.2.0
*/
public class KafkaHelper {
/**
* Helper method to create a {@link ExecutorService} instance (internal use).
*
* @param es
* @return
*/
public static ExecutorService createExecutorServiceIfNull(ExecutorService es) {
if (es == null) {
int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4);
es = Executors.newFixedThreadPool(numThreads);
}
return es;
}
/**
* Helper method to shutdown a {@link ExecutorService} instance (internal use).
*
* @param es
*/
public static void destroyExecutorService(ExecutorService es) {
if (es != null) {
es.shutdownNow();
}
}
/**
* Seek to a specified offset.
*
* @param consumer
* @param tpo
* @return {@code true} if the consumer has subscribed to the specified
* topic/partition, {@code false} otherwise.
* @since 1.3.2
*/ | public static boolean seek(KafkaConsumer<?, ?> consumer, KafkaTopicPartitionOffset tpo) { |
DDTH/ddth-kafka | src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java | // Path: src/main/java/com/github/ddth/kafka/KafkaClient.java
// public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS;
// public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };}
//
// Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java
// public class KafkaTopicPartitionOffset {
// public final String topic;
// public final int partition;
// public final long offset;
//
// public KafkaTopicPartitionOffset(String topic, int partition, long offset) {
// this.topic = topic;
// this.partition = partition;
// this.offset = offset;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// ToStringBuilder tsb = new ToStringBuilder(this);
// tsb.append("topic", topic).append("partition", partition).append("offset", offset);
// return tsb.build();
// }
// }
| import com.github.ddth.kafka.KafkaClient.ProducerType;
import com.github.ddth.kafka.KafkaTopicPartitionOffset;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | public static boolean seekToEnd(KafkaConsumer<?, ?> consumer, String topic) {
boolean result = false;
synchronized (consumer) {
Set<TopicPartition> topicParts = consumer.assignment();
if (topicParts != null) {
for (TopicPartition tp : topicParts) {
if (StringUtils.equals(topic, tp.topic())) {
consumer.seekToEnd(Arrays.asList(tp));
/* we want to seek as soon as possible since seekToEnd evaluates lazily,
* invoke position() so that seeking will be committed.
*/
consumer.position(tp);
result = true;
}
}
if (result) {
consumer.commitSync();
}
}
}
return result;
}
/**
* Create a new {@link KafkaProducer} instance, with default configurations.
*
* @param type
* @param bootstrapServers
* @return
*/ | // Path: src/main/java/com/github/ddth/kafka/KafkaClient.java
// public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS;
// public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };}
//
// Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java
// public class KafkaTopicPartitionOffset {
// public final String topic;
// public final int partition;
// public final long offset;
//
// public KafkaTopicPartitionOffset(String topic, int partition, long offset) {
// this.topic = topic;
// this.partition = partition;
// this.offset = offset;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// ToStringBuilder tsb = new ToStringBuilder(this);
// tsb.append("topic", topic).append("partition", partition).append("offset", offset);
// return tsb.build();
// }
// }
// Path: src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java
import com.github.ddth.kafka.KafkaClient.ProducerType;
import com.github.ddth.kafka.KafkaTopicPartitionOffset;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public static boolean seekToEnd(KafkaConsumer<?, ?> consumer, String topic) {
boolean result = false;
synchronized (consumer) {
Set<TopicPartition> topicParts = consumer.assignment();
if (topicParts != null) {
for (TopicPartition tp : topicParts) {
if (StringUtils.equals(topic, tp.topic())) {
consumer.seekToEnd(Arrays.asList(tp));
/* we want to seek as soon as possible since seekToEnd evaluates lazily,
* invoke position() so that seeking will be committed.
*/
consumer.position(tp);
result = true;
}
}
if (result) {
consumer.commitSync();
}
}
}
return result;
}
/**
* Create a new {@link KafkaProducer} instance, with default configurations.
*
* @param type
* @param bootstrapServers
* @return
*/ | public static KafkaProducer<String, byte[]> createKafkaProducer(ProducerType type, String bootstrapServers) { |
jGleitz/JUnit-KIT | src/test/OutputFileWriter.java | // Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
| import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import test.framework.FrameworkException; | for (TestMethod testMethod : classMap.values()) {
String indicator = "<span class=\"successIndicator "
+ ((testMethod.success) ? "succeeded" : "failed") + "\" title=\""
+ ((testMethod.success) ? "success" : "fail") + "\">" + CIRCLE_SVG + "</span>";
write(new String[] {
"<div class=\"testMethod closed\" id=\"" + id + "\">",
"<h4 onclick=\"toggleMethod(" + id + ");\"><span class=\"opener\">" + TRIANGLE_SVG
+ "</span>" + testMethod.name + indicator + "</h4>",
"<div class=\"sessions\">"
}, outputWriter);
for (String[] session : testMethod.sessions) {
write(session, outputWriter);
}
if (!testMethod.success) {
write(testMethod.failureHTML, outputWriter);
}
write(new String[] {
"</div>",
"</div>"
}, outputWriter);
id++;
}
write(new String[] {
"</div>"
}, outputWriter);
}
write(inputFiles(), outputWriter);
write(tail(), outputWriter);
outputWriter.close();
} catch (FileNotFoundException e) { | // Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
// Path: src/test/OutputFileWriter.java
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import test.framework.FrameworkException;
for (TestMethod testMethod : classMap.values()) {
String indicator = "<span class=\"successIndicator "
+ ((testMethod.success) ? "succeeded" : "failed") + "\" title=\""
+ ((testMethod.success) ? "success" : "fail") + "\">" + CIRCLE_SVG + "</span>";
write(new String[] {
"<div class=\"testMethod closed\" id=\"" + id + "\">",
"<h4 onclick=\"toggleMethod(" + id + ");\"><span class=\"opener\">" + TRIANGLE_SVG
+ "</span>" + testMethod.name + indicator + "</h4>",
"<div class=\"sessions\">"
}, outputWriter);
for (String[] session : testMethod.sessions) {
write(session, outputWriter);
}
if (!testMethod.success) {
write(testMethod.failureHTML, outputWriter);
}
write(new String[] {
"</div>",
"</div>"
}, outputWriter);
id++;
}
write(new String[] {
"</div>"
}, outputWriter);
}
write(inputFiles(), outputWriter);
write(tail(), outputWriter);
outputWriter.close();
} catch (FileNotFoundException e) { | throw new FrameworkException("We cannot generate an output file, as we're unable to write the file " |
jGleitz/JUnit-KIT | src/test/mocking/MockCompiler.java | // Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
| import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import test.framework.FrameworkException; | package test.mocking;
/**
* Helper class to compile a {@link MockerJavaSourceFile}.
*
* @author Joshua Gleitze
* @version 1.0
* @since 04.02.2015
*/
public abstract class MockCompiler {
private static final File cacheFile = new File(".serialization/mockCompilerCache.ser");
private static Map<String, MockerJavaClassFile> cache = getCache();
private static final JavaCompiler compiler = getJavaCompiler();
private static final MockCompilerFileManager fileManager = new MockCompilerFileManager(
compiler.getStandardFileManager(null, null, null));
private static String OS = null;
/**
* Compiles the source code provided in {@code sourceFile}. The compiler will run silent. If an error occurs while
* compiling, the compiler's error text will be provided with the exception.
*
* @param sourceFile
* The {@link MockerJavaSourceFile} to compile
* @return the {@link MockerJavaClassFile} containing the compiled java byte code
* @throws FrameworkException
* if an error occurs while compiling. The exception will contain the compiler's error text.
*/
public static MockerJavaClassFile compile(MockerJavaSourceFile sourceFile) {
// check if this version of the class is already cached
if (!cache.containsKey(sourceFile.getName()) || !cache.get(sourceFile.getName()).isFromSourceFile(sourceFile)) {
// will contain the compiler's error output
final Writer errorWriter = new StringWriter();
// creates the compilation task, runs it and returns the result
final boolean compilationSuccessful = compiler.getTask(errorWriter, fileManager, null, null, null,
Arrays.asList(sourceFile)).call();
if (!compilationSuccessful) { | // Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
// Path: src/test/mocking/MockCompiler.java
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import test.framework.FrameworkException;
package test.mocking;
/**
* Helper class to compile a {@link MockerJavaSourceFile}.
*
* @author Joshua Gleitze
* @version 1.0
* @since 04.02.2015
*/
public abstract class MockCompiler {
private static final File cacheFile = new File(".serialization/mockCompilerCache.ser");
private static Map<String, MockerJavaClassFile> cache = getCache();
private static final JavaCompiler compiler = getJavaCompiler();
private static final MockCompilerFileManager fileManager = new MockCompilerFileManager(
compiler.getStandardFileManager(null, null, null));
private static String OS = null;
/**
* Compiles the source code provided in {@code sourceFile}. The compiler will run silent. If an error occurs while
* compiling, the compiler's error text will be provided with the exception.
*
* @param sourceFile
* The {@link MockerJavaSourceFile} to compile
* @return the {@link MockerJavaClassFile} containing the compiled java byte code
* @throws FrameworkException
* if an error occurs while compiling. The exception will contain the compiler's error text.
*/
public static MockerJavaClassFile compile(MockerJavaSourceFile sourceFile) {
// check if this version of the class is already cached
if (!cache.containsKey(sourceFile.getName()) || !cache.get(sourceFile.getName()).isFromSourceFile(sourceFile)) {
// will contain the compiler's error output
final Writer errorWriter = new StringWriter();
// creates the compilation task, runs it and returns the result
final boolean compilationSuccessful = compiler.getTask(errorWriter, fileManager, null, null, null,
Arrays.asList(sourceFile)).call();
if (!compilationSuccessful) { | throw new FrameworkException("Unable to compile " + sourceFile.getName() + ":\n\n" |
jGleitz/JUnit-KIT | src/sheet6/c_bookDatabase/subtests/CompleteSearchScenarioTest.java | // Path: src/test/Input.java
// public class Input {
// private static HashMap<String, String[]> filesMap = new HashMap<>();
// private static HashMap<String[], String> reverseFileMap = new HashMap<>();
//
// /**
// * This class is not meant to be instantiated.
// */
// private Input() {
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(String... lines) {
// String fileName;
// if (!Input.reverseFileMap.containsKey(lines)) {
// fileName = UUID.randomUUID().toString() + ".txt";
// File file = new File(fileName);
// BufferedWriter outputWriter = null;
// try {
// outputWriter = new BufferedWriter(new FileWriter(file));
// for (String line : lines) {
// outputWriter.write(line);
// outputWriter.newLine();
// }
// outputWriter.flush();
// outputWriter.close();
// file.deleteOnExit();
// } catch (IOException e) {
// fail("The test was unable to create a test file. That's a shame!");
// }
//
// Input.filesMap.put(fileName, lines);
// Input.reverseFileMap.put(lines, fileName);
// } else {
// fileName = Input.reverseFileMap.get(lines);
// }
// return fileName;
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(Collection<String> lines) {
// String[] linesArray = new String[lines.size()];
// Iterator<String> iterator = lines.iterator();
// for (int i = 0; iterator.hasNext(); i++) {
// linesArray[i] = iterator.next();
// }
// return getFile(linesArray);
// }
//
// /**
// * A message giving information about the input file used in a test.
// *
// * @param filePath
// * The command line arguments the main method was called with during the test. The file message will read
// * the file name in the second argument and output the contents of the file its pointing to.
// * @return A text representing the input file
// */
// public static String fileMessage(String filePath) {
// String result = "";
// if (filesMap.containsKey(filePath)) {
// result = "\n with the following input file:\n\n" + arrayToLines(filesMap.get(filePath)) + "\n\n";
// }
// return result;
// }
//
// /**
// * @return The paths to all generated input files.
// */
// public static List<String> getAllFilePaths() {
// return new LinkedList<String>(filesMap.keySet());
// }
//
// /**
// * @param filePath
// * The path of a generated input file.
// * @return The lines of the input file that was given the path {@code filePath}, {@code null} if there is no such
// * file.
// */
// public static String[] getFileContentOf(String filePath) {
// return filesMap.get(filePath);
// }
//
// public static boolean isFile(String fileName) {
// return filesMap.containsKey(fileName);
// }
//
// /**
// * Converts an Array of Strings into a String where each array element is represented as one line.
// *
// * @param lines
// * The array to process
// * @return the array as lines.
// */
// public static String arrayToLines(String[] lines) {
// String result = "";
// for (String line : lines) {
// if (result != "") {
// result += "\n";
// }
// result += line;
// }
// return result;
// }
//
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hamcrest.Matcher;
import org.junit.Test;
import test.Input; |
queries = new String[] {
"creator=ralf_reussner",
"year=2006",
"AND(creator=ralf_reussner,year=2006)",
"OR(creator=ralf_reussner,year=2006)",
"isbn=12345"
};
// @formatter:off
expectedResultMatchers = getMatchers(
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,false"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,true"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,false"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,true"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
startsWith("Error,")
);
// @formatter:on
| // Path: src/test/Input.java
// public class Input {
// private static HashMap<String, String[]> filesMap = new HashMap<>();
// private static HashMap<String[], String> reverseFileMap = new HashMap<>();
//
// /**
// * This class is not meant to be instantiated.
// */
// private Input() {
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(String... lines) {
// String fileName;
// if (!Input.reverseFileMap.containsKey(lines)) {
// fileName = UUID.randomUUID().toString() + ".txt";
// File file = new File(fileName);
// BufferedWriter outputWriter = null;
// try {
// outputWriter = new BufferedWriter(new FileWriter(file));
// for (String line : lines) {
// outputWriter.write(line);
// outputWriter.newLine();
// }
// outputWriter.flush();
// outputWriter.close();
// file.deleteOnExit();
// } catch (IOException e) {
// fail("The test was unable to create a test file. That's a shame!");
// }
//
// Input.filesMap.put(fileName, lines);
// Input.reverseFileMap.put(lines, fileName);
// } else {
// fileName = Input.reverseFileMap.get(lines);
// }
// return fileName;
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(Collection<String> lines) {
// String[] linesArray = new String[lines.size()];
// Iterator<String> iterator = lines.iterator();
// for (int i = 0; iterator.hasNext(); i++) {
// linesArray[i] = iterator.next();
// }
// return getFile(linesArray);
// }
//
// /**
// * A message giving information about the input file used in a test.
// *
// * @param filePath
// * The command line arguments the main method was called with during the test. The file message will read
// * the file name in the second argument and output the contents of the file its pointing to.
// * @return A text representing the input file
// */
// public static String fileMessage(String filePath) {
// String result = "";
// if (filesMap.containsKey(filePath)) {
// result = "\n with the following input file:\n\n" + arrayToLines(filesMap.get(filePath)) + "\n\n";
// }
// return result;
// }
//
// /**
// * @return The paths to all generated input files.
// */
// public static List<String> getAllFilePaths() {
// return new LinkedList<String>(filesMap.keySet());
// }
//
// /**
// * @param filePath
// * The path of a generated input file.
// * @return The lines of the input file that was given the path {@code filePath}, {@code null} if there is no such
// * file.
// */
// public static String[] getFileContentOf(String filePath) {
// return filesMap.get(filePath);
// }
//
// public static boolean isFile(String fileName) {
// return filesMap.containsKey(fileName);
// }
//
// /**
// * Converts an Array of Strings into a String where each array element is represented as one line.
// *
// * @param lines
// * The array to process
// * @return the array as lines.
// */
// public static String arrayToLines(String[] lines) {
// String result = "";
// for (String line : lines) {
// if (result != "") {
// result += "\n";
// }
// result += line;
// }
// return result;
// }
//
// }
// Path: src/sheet6/c_bookDatabase/subtests/CompleteSearchScenarioTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hamcrest.Matcher;
import org.junit.Test;
import test.Input;
queries = new String[] {
"creator=ralf_reussner",
"year=2006",
"AND(creator=ralf_reussner,year=2006)",
"OR(creator=ralf_reussner,year=2006)",
"isbn=12345"
};
// @formatter:off
expectedResultMatchers = getMatchers(
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,false"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,true"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,false"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
is("creator=galileocomputing,title=java_ist_auch_eine_insel,year=unknown,false"),
is("creator=unknown,title=grundkursprogrammieren_in_java,year=2007,true"),
is("creator=ralf_reussner,title=unknown,year=2006,true"),
startsWith("Error,")
);
// @formatter:on
| multiLineTest(searchForAll(queries), expectedResultMatchers, "0.5", Input.getFile(file)); |
jGleitz/JUnit-KIT | src/test/InteractiveConsoleTest.java | // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
| allCommands[commands.length] = "quit";
return allCommands;
}
protected static String joinAsNumberedLines(String[] strings) {
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (resultBuilder.length() > 0) {
resultBuilder.append(System.lineSeparator());
}
resultBuilder.append("[");
resultBuilder.append(i + 1);
resultBuilder.append("] ");
resultBuilder.append(strings[i]);
}
return resultBuilder.toString();
}
protected static String joinOnePerLine(String[] strings) {
StringBuilder resultBuilder = new StringBuilder();
for (String string : strings) {
if (resultBuilder.length() > 0) {
resultBuilder.append(System.lineSeparator());
}
resultBuilder.append(string);
}
return resultBuilder.toString();
}
protected static final Run quit() {
| // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
// Path: src/test/InteractiveConsoleTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
allCommands[commands.length] = "quit";
return allCommands;
}
protected static String joinAsNumberedLines(String[] strings) {
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (resultBuilder.length() > 0) {
resultBuilder.append(System.lineSeparator());
}
resultBuilder.append("[");
resultBuilder.append(i + 1);
resultBuilder.append("] ");
resultBuilder.append(strings[i]);
}
return resultBuilder.toString();
}
protected static String joinOnePerLine(String[] strings) {
StringBuilder resultBuilder = new StringBuilder();
for (String string : strings) {
if (resultBuilder.length() > 0) {
resultBuilder.append(System.lineSeparator());
}
resultBuilder.append(string);
}
return resultBuilder.toString();
}
protected static final Run quit() {
| return new NoOutputRun("quit");
|
jGleitz/JUnit-KIT | src/test/InteractiveConsoleTest.java | // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
| * Gets called before each test run. Sets the allowed system exit status to {@link SystemExitStatus#WITH_0}.
* Override this method if you wish to have another default system exit status.
* <p>
* <i>Deprecated. Please use {@link #setAllowedSystemExitStatus(SystemExitStatus)} and
* {@link #setExpectedSystemExitStatus(SystemExitStatus)}.
*/
@Deprecated
@Before
public void defaultSystemExitStatus() {
TestObject.allowSystemExit(SystemExitStatus.WITH_0);
}
/**
* Checks the exit status of a tested method. Has to be called after call to a {@link TestObject} run method.
*
* @param commands
* The commands that were run on the interactive console.
* @param args0
* The arguments the main method was called with in the test run.
* @throws IllegalStateException
* If {@link #initSystemExitStatusCheck()} has not been called before the test run.
*/
protected final void checkSystemExitStatus(String[] commands, String[] args0) {
if (!newSystemExitStatusCeckInited) {
throw new IllegalStateException("The new way of system exit status checking has not been inited yet!");
}
if (allowedExitStatus != null || expectedExitStatus != null) {
Integer actualStatus = TestObject.getLastMethodsSystemExitStatus();
if (expectedExitStatus != null) {
assertThat(consoleMessage(commands, args0) + "\nWrong system exit status!", actualStatus,
| // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
// Path: src/test/InteractiveConsoleTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
* Gets called before each test run. Sets the allowed system exit status to {@link SystemExitStatus#WITH_0}.
* Override this method if you wish to have another default system exit status.
* <p>
* <i>Deprecated. Please use {@link #setAllowedSystemExitStatus(SystemExitStatus)} and
* {@link #setExpectedSystemExitStatus(SystemExitStatus)}.
*/
@Deprecated
@Before
public void defaultSystemExitStatus() {
TestObject.allowSystemExit(SystemExitStatus.WITH_0);
}
/**
* Checks the exit status of a tested method. Has to be called after call to a {@link TestObject} run method.
*
* @param commands
* The commands that were run on the interactive console.
* @param args0
* The arguments the main method was called with in the test run.
* @throws IllegalStateException
* If {@link #initSystemExitStatusCheck()} has not been called before the test run.
*/
protected final void checkSystemExitStatus(String[] commands, String[] args0) {
if (!newSystemExitStatusCeckInited) {
throw new IllegalStateException("The new way of system exit status checking has not been inited yet!");
}
if (allowedExitStatus != null || expectedExitStatus != null) {
Integer actualStatus = TestObject.getLastMethodsSystemExitStatus();
if (expectedExitStatus != null) {
assertThat(consoleMessage(commands, args0) + "\nWrong system exit status!", actualStatus,
| suits(expectedExitStatus, true));
|
jGleitz/JUnit-KIT | src/test/InteractiveConsoleTest.java | // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
| * class does not necessary have to call {@code System.exit}.
*/
protected final void setExpectedSystemExitStatus(SystemExitStatus status) {
expectedExitStatus = status;
}
/**
* @param s
* A String.
* @return An Array containing {@code s} as only element.
*/
protected String[] wrapInArray(String s) {
return new String[] {
s
};
}
/**
* Returns either the timeout set in the configuration or the default timeout returned by
* {@link #getDefaultTimeoutMs()}.
*
* @return The timeout to use for this test class.
*/
private final Timeout getTimeout() {
String systemProperty = System.getProperty("timeout");
if (systemProperty != null) {
int sysTimeout = 0;
try {
sysTimeout = Integer.parseInt(systemProperty);
} catch (NumberFormatException e) {
| // Path: src/test/KitMatchers.java
// public static Matcher<Integer> suits(final SystemExitStatus systemExitStatus, final boolean mandatory) {
// return new BaseMatcher<Integer>() {
//
// @Override
// public boolean matches(final Object testObject) {
// Integer status = (Integer) testObject;
// return systemExitStatus.matches(status, mandatory);
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(systemExitStatus.toString());
// }
//
// @Override
// public void describeMismatch(final Object item, final Description description) {
// if (item == null) {
// description.appendText("was no call to System.exit at all");
// } else {
// description.appendText("was System.exit(" + item + ")");
// }
// }
// };
// }
//
// Path: src/test/framework/FrameworkException.java
// public class FrameworkException extends RuntimeException {
// private static final long serialVersionUID = 2221405766881026986L;
// private static final String GIT_HUB_POINTER = "This is a serious issue. But we'd like to help solve this!\n"
// + "Please report what happened on GitHub. Create a new issue at:\n"
// + "https://github.com/jGleitz/JUnit-KIT/issues";
//
// /**
// * New Framework Exception.
// *
// * @param message
// * Detailed error description
// */
// public FrameworkException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// String details = super.getMessage();
// return details + "\n\n" + GIT_HUB_POINTER;
// }
// }
//
// Path: src/test/runs/NoOutputRun.java
// public class NoOutputRun extends ExactRun {
//
// /**
// * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested
// * class.
// */
// public NoOutputRun(String command) {
// super(command, "no output at all", new LinkedList<Matcher<String>>());
// }
//
// /**
// * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested
// * class. Use only to test errors before the first command.
// */
// public NoOutputRun() {
// this(null);
// }
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
// Path: src/test/InteractiveConsoleTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static test.KitMatchers.suits;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import test.framework.FrameworkException;
import test.runs.NoOutputRun;
import test.runs.Run;
* class does not necessary have to call {@code System.exit}.
*/
protected final void setExpectedSystemExitStatus(SystemExitStatus status) {
expectedExitStatus = status;
}
/**
* @param s
* A String.
* @return An Array containing {@code s} as only element.
*/
protected String[] wrapInArray(String s) {
return new String[] {
s
};
}
/**
* Returns either the timeout set in the configuration or the default timeout returned by
* {@link #getDefaultTimeoutMs()}.
*
* @return The timeout to use for this test class.
*/
private final Timeout getTimeout() {
String systemProperty = System.getProperty("timeout");
if (systemProperty != null) {
int sysTimeout = 0;
try {
sysTimeout = Integer.parseInt(systemProperty);
} catch (NumberFormatException e) {
| throw new FrameworkException("The timeout set in the configuration cannot be parsed into an integer!");
|
jGleitz/JUnit-KIT | src/test/runs/LineRun.java | // Path: src/test/KitMatchers.java
// public static Matcher<String[]> hasExcactlyThatMuch(final int count, final String[] outputDescription) {
// return hasExcactlyThatMuch(count, outputDescription, null);
// }
| import static test.KitMatchers.hasExcactlyThatMuch;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.hamcrest.Matcher; | package test.runs;
/**
* A test run for matching the method's whole output for one command line by line. All calls to
* {@code Terminal.printLine} will be merged into one String, each call separated by {@code \n}, and can then be matched
* line by line.
*
* @author Joshua Gleitze
* @version 1.0
*/
public class LineRun implements Run {
private String command;
private List<Matcher<String>> expectedResults;
/**
* Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output
* matches {@code expectedResults} line by line.
*
* @param command
* The command to run
* @param expectedResults
* The matchers describing the desired output
*/
public LineRun(String command, List<Matcher<String>> expectedResults) {
this.command = command;
this.expectedResults = expectedResults;
}
/**
* Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output
* matches {@code expectedResults} line by line.
*
* @param command
* The command to run
* @param expectedResults
* The matchers describing the desired output
*/
@SafeVarargs
public LineRun(String command, Matcher<String>... expectedResults) {
this(command, Arrays.asList(expectedResults));
}
/**
* Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the
* merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.
*
* @param expectedResults
* The matchers describing the desired output
*/
public LineRun(List<Matcher<String>> expectedResults) {
this(null, expectedResults);
}
/**
* Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the
* merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.
*
* @param expectedResults
* The matchers describing the desired output
*/
@SafeVarargs
public LineRun(Matcher<String>... expectedResults) {
this(null, expectedResults);
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#getCommand()
*/
@Override
public String getCommand() {
return this.command;
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#check(java.lang.String[], java.lang.String)
*/
@Override
public void check(String[] testedClassOutput, String errorMessage) {
Iterator<Matcher<String>> expectedIterator = expectedResults.iterator();
String[] outputLines = mergedOutputLines(testedClassOutput);
String overallErrorMessage = errorMessage + "\nYour output:\n" + mergedOutput(testedClassOutput); | // Path: src/test/KitMatchers.java
// public static Matcher<String[]> hasExcactlyThatMuch(final int count, final String[] outputDescription) {
// return hasExcactlyThatMuch(count, outputDescription, null);
// }
// Path: src/test/runs/LineRun.java
import static test.KitMatchers.hasExcactlyThatMuch;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.hamcrest.Matcher;
package test.runs;
/**
* A test run for matching the method's whole output for one command line by line. All calls to
* {@code Terminal.printLine} will be merged into one String, each call separated by {@code \n}, and can then be matched
* line by line.
*
* @author Joshua Gleitze
* @version 1.0
*/
public class LineRun implements Run {
private String command;
private List<Matcher<String>> expectedResults;
/**
* Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output
* matches {@code expectedResults} line by line.
*
* @param command
* The command to run
* @param expectedResults
* The matchers describing the desired output
*/
public LineRun(String command, List<Matcher<String>> expectedResults) {
this.command = command;
this.expectedResults = expectedResults;
}
/**
* Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output
* matches {@code expectedResults} line by line.
*
* @param command
* The command to run
* @param expectedResults
* The matchers describing the desired output
*/
@SafeVarargs
public LineRun(String command, Matcher<String>... expectedResults) {
this(command, Arrays.asList(expectedResults));
}
/**
* Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the
* merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.
*
* @param expectedResults
* The matchers describing the desired output
*/
public LineRun(List<Matcher<String>> expectedResults) {
this(null, expectedResults);
}
/**
* Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the
* merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.
*
* @param expectedResults
* The matchers describing the desired output
*/
@SafeVarargs
public LineRun(Matcher<String>... expectedResults) {
this(null, expectedResults);
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#getCommand()
*/
@Override
public String getCommand() {
return this.command;
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#check(java.lang.String[], java.lang.String)
*/
@Override
public void check(String[] testedClassOutput, String errorMessage) {
Iterator<Matcher<String>> expectedIterator = expectedResults.iterator();
String[] outputLines = mergedOutputLines(testedClassOutput);
String overallErrorMessage = errorMessage + "\nYour output:\n" + mergedOutput(testedClassOutput); | assertThat(overallErrorMessage, outputLines, hasExcactlyThatMuch(expectedResults.size(), new String[] { |
jGleitz/JUnit-KIT | src/final2/subtests/PrintTest.java | // Path: src/test/Input.java
// public class Input {
// private static HashMap<String, String[]> filesMap = new HashMap<>();
// private static HashMap<String[], String> reverseFileMap = new HashMap<>();
//
// /**
// * This class is not meant to be instantiated.
// */
// private Input() {
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(String... lines) {
// String fileName;
// if (!Input.reverseFileMap.containsKey(lines)) {
// fileName = UUID.randomUUID().toString() + ".txt";
// File file = new File(fileName);
// BufferedWriter outputWriter = null;
// try {
// outputWriter = new BufferedWriter(new FileWriter(file));
// for (String line : lines) {
// outputWriter.write(line);
// outputWriter.newLine();
// }
// outputWriter.flush();
// outputWriter.close();
// file.deleteOnExit();
// } catch (IOException e) {
// fail("The test was unable to create a test file. That's a shame!");
// }
//
// Input.filesMap.put(fileName, lines);
// Input.reverseFileMap.put(lines, fileName);
// } else {
// fileName = Input.reverseFileMap.get(lines);
// }
// return fileName;
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(Collection<String> lines) {
// String[] linesArray = new String[lines.size()];
// Iterator<String> iterator = lines.iterator();
// for (int i = 0; iterator.hasNext(); i++) {
// linesArray[i] = iterator.next();
// }
// return getFile(linesArray);
// }
//
// /**
// * A message giving information about the input file used in a test.
// *
// * @param filePath
// * The command line arguments the main method was called with during the test. The file message will read
// * the file name in the second argument and output the contents of the file its pointing to.
// * @return A text representing the input file
// */
// public static String fileMessage(String filePath) {
// String result = "";
// if (filesMap.containsKey(filePath)) {
// result = "\n with the following input file:\n\n" + arrayToLines(filesMap.get(filePath)) + "\n\n";
// }
// return result;
// }
//
// /**
// * @return The paths to all generated input files.
// */
// public static List<String> getAllFilePaths() {
// return new LinkedList<String>(filesMap.keySet());
// }
//
// /**
// * @param filePath
// * The path of a generated input file.
// * @return The lines of the input file that was given the path {@code filePath}, {@code null} if there is no such
// * file.
// */
// public static String[] getFileContentOf(String filePath) {
// return filesMap.get(filePath);
// }
//
// public static boolean isFile(String fileName) {
// return filesMap.containsKey(fileName);
// }
//
// /**
// * Converts an Array of Strings into a String where each array element is represented as one line.
// *
// * @param lines
// * The array to process
// * @return the array as lines.
// */
// public static String arrayToLines(String[] lines) {
// String result = "";
// for (String line : lines) {
// if (result != "") {
// result += "\n";
// }
// result += line;
// }
// return result;
// }
//
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
| import org.junit.Test;
import test.Input;
import test.runs.Run; | package final2.subtests;
/**
* Checks the {@code print} command without running any other commands. Asserts that {@code print} works, which is
* crucial for other tests to work.
*
* @author Joshua Gleitze
*/
public class PrintTest extends LangtonSubtest {
@Test
public void correctInputFilePrintTest() {
String[][] inputFiles = {
PUBLIC_PRAKTOMAT_TEST_FILE_1,
PUBLIC_PRAKTOMAT_TEST_FILE_2,
PUBLIC_PRAKTOMAT_TEST_FILE_3,
PUBLIC_PRAKTOMAT_TEST_FILE_4,
TASK_SHEET_INPUT_FILE_1,
TASK_SHEET_INPUT_FILE_2
};
| // Path: src/test/Input.java
// public class Input {
// private static HashMap<String, String[]> filesMap = new HashMap<>();
// private static HashMap<String[], String> reverseFileMap = new HashMap<>();
//
// /**
// * This class is not meant to be instantiated.
// */
// private Input() {
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(String... lines) {
// String fileName;
// if (!Input.reverseFileMap.containsKey(lines)) {
// fileName = UUID.randomUUID().toString() + ".txt";
// File file = new File(fileName);
// BufferedWriter outputWriter = null;
// try {
// outputWriter = new BufferedWriter(new FileWriter(file));
// for (String line : lines) {
// outputWriter.write(line);
// outputWriter.newLine();
// }
// outputWriter.flush();
// outputWriter.close();
// file.deleteOnExit();
// } catch (IOException e) {
// fail("The test was unable to create a test file. That's a shame!");
// }
//
// Input.filesMap.put(fileName, lines);
// Input.reverseFileMap.put(lines, fileName);
// } else {
// fileName = Input.reverseFileMap.get(lines);
// }
// return fileName;
// }
//
// /**
// * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created
// * before.
// *
// * @param lines
// * The lines to print in the file.
// * @return path to a file containing {@code lines}
// */
// public static String getFile(Collection<String> lines) {
// String[] linesArray = new String[lines.size()];
// Iterator<String> iterator = lines.iterator();
// for (int i = 0; iterator.hasNext(); i++) {
// linesArray[i] = iterator.next();
// }
// return getFile(linesArray);
// }
//
// /**
// * A message giving information about the input file used in a test.
// *
// * @param filePath
// * The command line arguments the main method was called with during the test. The file message will read
// * the file name in the second argument and output the contents of the file its pointing to.
// * @return A text representing the input file
// */
// public static String fileMessage(String filePath) {
// String result = "";
// if (filesMap.containsKey(filePath)) {
// result = "\n with the following input file:\n\n" + arrayToLines(filesMap.get(filePath)) + "\n\n";
// }
// return result;
// }
//
// /**
// * @return The paths to all generated input files.
// */
// public static List<String> getAllFilePaths() {
// return new LinkedList<String>(filesMap.keySet());
// }
//
// /**
// * @param filePath
// * The path of a generated input file.
// * @return The lines of the input file that was given the path {@code filePath}, {@code null} if there is no such
// * file.
// */
// public static String[] getFileContentOf(String filePath) {
// return filesMap.get(filePath);
// }
//
// public static boolean isFile(String fileName) {
// return filesMap.containsKey(fileName);
// }
//
// /**
// * Converts an Array of Strings into a String where each array element is represented as one line.
// *
// * @param lines
// * The array to process
// * @return the array as lines.
// */
// public static String arrayToLines(String[] lines) {
// String result = "";
// for (String line : lines) {
// if (result != "") {
// result += "\n";
// }
// result += line;
// }
// return result;
// }
//
// }
//
// Path: src/test/runs/Run.java
// public interface Run {
//
// /**
// * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if
// * it doesn't.
// *
// * @param testedClassOutput
// * The output of the tested class for this run. One String represents one call to
// * {@code Terminal.printLine}.
// * @param errorMessage
// * The message that will be reported to {@link org.junit.Assert#fail(String)} or
// * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}
// * @throws RunFailedException
// * If {@code testedClassOutput} does not fulfil this test run's expected output.
// */
// public void check(String[] testedClassOutput, String errorMessage);
//
// /**
// * @return The command that is to be run on the interactive console for this test run.
// */
// public String getCommand();
//
// /**
// * @return A String describing what this test run expects the tested class to print.
// */
// public String getExpectedDescription();
// }
// Path: src/final2/subtests/PrintTest.java
import org.junit.Test;
import test.Input;
import test.runs.Run;
package final2.subtests;
/**
* Checks the {@code print} command without running any other commands. Asserts that {@code print} works, which is
* crucial for other tests to work.
*
* @author Joshua Gleitze
*/
public class PrintTest extends LangtonSubtest {
@Test
public void correctInputFilePrintTest() {
String[][] inputFiles = {
PUBLIC_PRAKTOMAT_TEST_FILE_1,
PUBLIC_PRAKTOMAT_TEST_FILE_2,
PUBLIC_PRAKTOMAT_TEST_FILE_3,
PUBLIC_PRAKTOMAT_TEST_FILE_4,
TASK_SHEET_INPUT_FILE_1,
TASK_SHEET_INPUT_FILE_2
};
| runs = new Run[] { |
jGleitz/JUnit-KIT | src/test/runs/ExactRun.java | // Path: src/test/KitMatchers.java
// public static Matcher<String[]> hasExcactlyThatMuch(final int count, final String[] outputDescription) {
// return hasExcactlyThatMuch(count, outputDescription, null);
// }
| import static test.KitMatchers.hasExcactlyThatMuch;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.hamcrest.Matcher; | package test.runs;
/**
* A test run for exact matching. For each expected call to {@code Terminal.printLine}, one matcher has to be provided.
* If {@code n} matchers are provided and the tested class fails to call {@code Terminal.printLine} exactly {@code n}
* times, the run is considered to have failed.
*
* @author Joshua Gleitze
* @version 1.0
*/
public class ExactRun implements Run {
private String command;
private List<Matcher<String>> expectedOutputMatchers;
private String outputDescription;
/**
* Creates a run for the given parameters, without a command. A description of the expected output will
* automatically be created based on {@code expectedOutputMatchers}. Use only to test errors before the first
* command.
*
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(List<Matcher<String>> expectedOutputMatchers) {
this(null, expectedOutputMatchers);
}
/**
* Creates a run for the given parameters. A description of the expected output will automatically be created based
* on {@code expectedOutputMatchers}.
*
* @param command
* The command to run.
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(String command, List<Matcher<String>> expectedOutputMatchers) {
this(command, null, expectedOutputMatchers);
}
/**
* Creates a run for the given parameters. A description of the expected output will automatically be created based
* on {@code expectedOutputMatchers}.
*
* @param command
* The command to run.
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
@SafeVarargs
public ExactRun(String command, Matcher<String>... expectedOutputMatchers) {
this(command, Arrays.asList(expectedOutputMatchers));
}
/**
* Creates a run for the given parameters.
*
* @param command
* The command to run.
* @param outputDescription
* A description detailing the expected output
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(String command, String outputDescription, List<Matcher<String>> expectedOutputMatchers) {
this.command = command;
this.expectedOutputMatchers = new LinkedList<Matcher<String>>(expectedOutputMatchers);
this.outputDescription = outputDescription;
}
/**
* Creates a run for the given parameters.
*
* @param command
* The command to run.
* @param outputDescription
* A description detailing the expected output
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
@SafeVarargs
public ExactRun(String command, String outputDescription, Matcher<String>... expectedOutputMatchers) {
this(command, outputDescription, Arrays.asList(expectedOutputMatchers));
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#match(java.lang.String[])
*/
@Override
public void check(String[] testedClassOutput, String errorMessage) { | // Path: src/test/KitMatchers.java
// public static Matcher<String[]> hasExcactlyThatMuch(final int count, final String[] outputDescription) {
// return hasExcactlyThatMuch(count, outputDescription, null);
// }
// Path: src/test/runs/ExactRun.java
import static test.KitMatchers.hasExcactlyThatMuch;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.hamcrest.Matcher;
package test.runs;
/**
* A test run for exact matching. For each expected call to {@code Terminal.printLine}, one matcher has to be provided.
* If {@code n} matchers are provided and the tested class fails to call {@code Terminal.printLine} exactly {@code n}
* times, the run is considered to have failed.
*
* @author Joshua Gleitze
* @version 1.0
*/
public class ExactRun implements Run {
private String command;
private List<Matcher<String>> expectedOutputMatchers;
private String outputDescription;
/**
* Creates a run for the given parameters, without a command. A description of the expected output will
* automatically be created based on {@code expectedOutputMatchers}. Use only to test errors before the first
* command.
*
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(List<Matcher<String>> expectedOutputMatchers) {
this(null, expectedOutputMatchers);
}
/**
* Creates a run for the given parameters. A description of the expected output will automatically be created based
* on {@code expectedOutputMatchers}.
*
* @param command
* The command to run.
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(String command, List<Matcher<String>> expectedOutputMatchers) {
this(command, null, expectedOutputMatchers);
}
/**
* Creates a run for the given parameters. A description of the expected output will automatically be created based
* on {@code expectedOutputMatchers}.
*
* @param command
* The command to run.
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
@SafeVarargs
public ExactRun(String command, Matcher<String>... expectedOutputMatchers) {
this(command, Arrays.asList(expectedOutputMatchers));
}
/**
* Creates a run for the given parameters.
*
* @param command
* The command to run.
* @param outputDescription
* A description detailing the expected output
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
public ExactRun(String command, String outputDescription, List<Matcher<String>> expectedOutputMatchers) {
this.command = command;
this.expectedOutputMatchers = new LinkedList<Matcher<String>>(expectedOutputMatchers);
this.outputDescription = outputDescription;
}
/**
* Creates a run for the given parameters.
*
* @param command
* The command to run.
* @param outputDescription
* A description detailing the expected output
* @param expectedOutputMatchers
* The matchers for the expected output. One matcher per expected call to {@code Terminal.printLine}.
*/
@SafeVarargs
public ExactRun(String command, String outputDescription, Matcher<String>... expectedOutputMatchers) {
this(command, outputDescription, Arrays.asList(expectedOutputMatchers));
}
/*
* (non-Javadoc)
*
* @see test.runs.Run#match(java.lang.String[])
*/
@Override
public void check(String[] testedClassOutput, String errorMessage) { | Matcher<String[]> hasCorrectCallNumber = hasExcactlyThatMuch(expectedOutputMatchers.size(), new String[] { |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/RetroShareAndroidProxy.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public enum ConnectionError
// {
// /**
// * No error
// */
// NONE,
//
// /**
// * The IP address of the host could not be determined.
// */
// UnknownHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the remote host cannot be
// * reached because of an intervening firewall, or if an intermediate
// * router is down.
// */
// NoRouteToHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the connection was refused
// * remotely (e.g., no process is listening on the remote address/port).
// */
// ConnectException,
//
// /**
// * Hostkey mismatch, hostkey changed since first connection this can mean that someone is trying to do a Man In The Middle attack
// */
// BadSignatureException,
//
// /**
// * Wrong user name or password
// */
// AuthenticationFailedException,
//
// /**
// * IO Level exception caught sending data
// */
// SEND_ERROR,
//
// /**
// * IO Level exception caught receiving data
// */
// RECEIVE_ERROR,
//
// /**
// * Something is not working but we don't know what/why
// */
// UNKNOWN,
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public class ConnectionEvent
// {
// public RsCtrlService trigger = RsCtrlService.this;
// public ConnectionEventKind kind;
//
// ConnectionEvent(RsCtrlService trig, ConnectionEventKind k)
// {
// trigger = trig;
// kind = k;
// }
//
// ConnectionEvent(ConnectionEventKind k) { kind = k; }
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public interface RsCtrlServiceListener
// {
// /**
// * Callback invoked on all registered listeners each time something happens
// * @param ce a ConnectionEvent containing information about what happened
// */
// public void onConnectionStateChanged(ConnectionEvent ce);
// }
| import org.retroshare.android.RsCtrlService.ConnectionEvent;
import org.retroshare.android.RsCtrlService.RsCtrlServiceListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import org.retroshare.android.RsCtrlService.ConnectionError; | {
for ( RsBund bund : serverBunds.values() )
{
RsServerData sd = bund.server.getServerData();
mDatapack.serverDataMap.put( sd.name, sd );
}
try
{
Log.v(TAG, "trying to save Datapack, Datapack.serverDataMapt=" + mDatapack.serverDataMap);
ObjectOutputStream o = new ObjectOutputStream(openFileOutput( DataPackBaseFileName + Long.toString(Datapack.serialVersionUID), MODE_PRIVATE));
o.writeObject(mDatapack);
}
catch (Exception e) { e.printStackTrace(); }
}
public class RsProxyBinder extends Binder { RetroShareAndroidProxy getService() { return RetroShareAndroidProxy.this; } }
private final IBinder mBinder = new RsProxyBinder();
@Override
public IBinder onBind(Intent arg0) { return mBinder; }
// new new don't delete
public static class HandlerThread extends Handler implements HandlerThreadInterface
{
@Override
public void postToHandlerThread(Runnable r) { post(r); }
}
@Override | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public enum ConnectionError
// {
// /**
// * No error
// */
// NONE,
//
// /**
// * The IP address of the host could not be determined.
// */
// UnknownHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the remote host cannot be
// * reached because of an intervening firewall, or if an intermediate
// * router is down.
// */
// NoRouteToHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the connection was refused
// * remotely (e.g., no process is listening on the remote address/port).
// */
// ConnectException,
//
// /**
// * Hostkey mismatch, hostkey changed since first connection this can mean that someone is trying to do a Man In The Middle attack
// */
// BadSignatureException,
//
// /**
// * Wrong user name or password
// */
// AuthenticationFailedException,
//
// /**
// * IO Level exception caught sending data
// */
// SEND_ERROR,
//
// /**
// * IO Level exception caught receiving data
// */
// RECEIVE_ERROR,
//
// /**
// * Something is not working but we don't know what/why
// */
// UNKNOWN,
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public class ConnectionEvent
// {
// public RsCtrlService trigger = RsCtrlService.this;
// public ConnectionEventKind kind;
//
// ConnectionEvent(RsCtrlService trig, ConnectionEventKind k)
// {
// trigger = trig;
// kind = k;
// }
//
// ConnectionEvent(ConnectionEventKind k) { kind = k; }
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public interface RsCtrlServiceListener
// {
// /**
// * Callback invoked on all registered listeners each time something happens
// * @param ce a ConnectionEvent containing information about what happened
// */
// public void onConnectionStateChanged(ConnectionEvent ce);
// }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RetroShareAndroidProxy.java
import org.retroshare.android.RsCtrlService.ConnectionEvent;
import org.retroshare.android.RsCtrlService.RsCtrlServiceListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import org.retroshare.android.RsCtrlService.ConnectionError;
{
for ( RsBund bund : serverBunds.values() )
{
RsServerData sd = bund.server.getServerData();
mDatapack.serverDataMap.put( sd.name, sd );
}
try
{
Log.v(TAG, "trying to save Datapack, Datapack.serverDataMapt=" + mDatapack.serverDataMap);
ObjectOutputStream o = new ObjectOutputStream(openFileOutput( DataPackBaseFileName + Long.toString(Datapack.serialVersionUID), MODE_PRIVATE));
o.writeObject(mDatapack);
}
catch (Exception e) { e.printStackTrace(); }
}
public class RsProxyBinder extends Binder { RetroShareAndroidProxy getService() { return RetroShareAndroidProxy.this; } }
private final IBinder mBinder = new RsProxyBinder();
@Override
public IBinder onBind(Intent arg0) { return mBinder; }
// new new don't delete
public static class HandlerThread extends Handler implements HandlerThreadInterface
{
@Override
public void postToHandlerThread(Runnable r) { post(r); }
}
@Override | public void onConnectionStateChanged(ConnectionEvent ce) |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/RetroShareAndroidProxy.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public enum ConnectionError
// {
// /**
// * No error
// */
// NONE,
//
// /**
// * The IP address of the host could not be determined.
// */
// UnknownHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the remote host cannot be
// * reached because of an intervening firewall, or if an intermediate
// * router is down.
// */
// NoRouteToHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the connection was refused
// * remotely (e.g., no process is listening on the remote address/port).
// */
// ConnectException,
//
// /**
// * Hostkey mismatch, hostkey changed since first connection this can mean that someone is trying to do a Man In The Middle attack
// */
// BadSignatureException,
//
// /**
// * Wrong user name or password
// */
// AuthenticationFailedException,
//
// /**
// * IO Level exception caught sending data
// */
// SEND_ERROR,
//
// /**
// * IO Level exception caught receiving data
// */
// RECEIVE_ERROR,
//
// /**
// * Something is not working but we don't know what/why
// */
// UNKNOWN,
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public class ConnectionEvent
// {
// public RsCtrlService trigger = RsCtrlService.this;
// public ConnectionEventKind kind;
//
// ConnectionEvent(RsCtrlService trig, ConnectionEventKind k)
// {
// trigger = trig;
// kind = k;
// }
//
// ConnectionEvent(ConnectionEventKind k) { kind = k; }
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public interface RsCtrlServiceListener
// {
// /**
// * Callback invoked on all registered listeners each time something happens
// * @param ce a ConnectionEvent containing information about what happened
// */
// public void onConnectionStateChanged(ConnectionEvent ce);
// }
| import org.retroshare.android.RsCtrlService.ConnectionEvent;
import org.retroshare.android.RsCtrlService.RsCtrlServiceListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import org.retroshare.android.RsCtrlService.ConnectionError; |
// new new don't delete
public static class HandlerThread extends Handler implements HandlerThreadInterface
{
@Override
public void postToHandlerThread(Runnable r) { post(r); }
}
@Override
public void onConnectionStateChanged(ConnectionEvent ce)
{
if( ce.kind == RsCtrlService.ConnectionEventKind.SERVER_DATA_CHANGED ) saveData();
updateNotification();
}
private void updateNotification()
{
int icon;
String tickerText;
String contentTitle=(String) getResources().getText(R.string.app_name);
String contentMessage;
boolean isOnline = false, hasError = false;
for( RsBund bund : serverBunds.values() )
{
if(bund.server.isOnline())
{
isOnline = true;
break;
} | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public enum ConnectionError
// {
// /**
// * No error
// */
// NONE,
//
// /**
// * The IP address of the host could not be determined.
// */
// UnknownHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the remote host cannot be
// * reached because of an intervening firewall, or if an intermediate
// * router is down.
// */
// NoRouteToHostException,
//
// /**
// * Signals that an error occurred while attempting to onConnectButtonPressed a socket
// * to a remote address and port. Typically, the connection was refused
// * remotely (e.g., no process is listening on the remote address/port).
// */
// ConnectException,
//
// /**
// * Hostkey mismatch, hostkey changed since first connection this can mean that someone is trying to do a Man In The Middle attack
// */
// BadSignatureException,
//
// /**
// * Wrong user name or password
// */
// AuthenticationFailedException,
//
// /**
// * IO Level exception caught sending data
// */
// SEND_ERROR,
//
// /**
// * IO Level exception caught receiving data
// */
// RECEIVE_ERROR,
//
// /**
// * Something is not working but we don't know what/why
// */
// UNKNOWN,
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public class ConnectionEvent
// {
// public RsCtrlService trigger = RsCtrlService.this;
// public ConnectionEventKind kind;
//
// ConnectionEvent(RsCtrlService trig, ConnectionEventKind k)
// {
// trigger = trig;
// kind = k;
// }
//
// ConnectionEvent(ConnectionEventKind k) { kind = k; }
// }
//
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsCtrlService.java
// public interface RsCtrlServiceListener
// {
// /**
// * Callback invoked on all registered listeners each time something happens
// * @param ce a ConnectionEvent containing information about what happened
// */
// public void onConnectionStateChanged(ConnectionEvent ce);
// }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/RetroShareAndroidProxy.java
import org.retroshare.android.RsCtrlService.ConnectionEvent;
import org.retroshare.android.RsCtrlService.RsCtrlServiceListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import org.retroshare.android.RsCtrlService.ConnectionError;
// new new don't delete
public static class HandlerThread extends Handler implements HandlerThreadInterface
{
@Override
public void postToHandlerThread(Runnable r) { post(r); }
}
@Override
public void onConnectionStateChanged(ConnectionEvent ce)
{
if( ce.kind == RsCtrlService.ConnectionEventKind.SERVER_DATA_CHANGED ) saveData();
updateNotification();
}
private void updateNotification()
{
int icon;
String tickerText;
String contentTitle=(String) getResources().getText(R.string.app_name);
String contentMessage;
boolean isOnline = false, hasError = false;
for( RsBund bund : serverBunds.values() )
{
if(bund.server.isOnline())
{
isOnline = true;
break;
} | else if(bund.server.getLastConnectionError() != ConnectionError.NONE) hasError = true; |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/ContactMethodChooserActivity.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static final class PgpChatId extends ConversationId
// {
// public String getDestPgpId() { return mPgpId; }
// @Override public ConversationKind getConversationKind(){ return ConversationKind.PGP_CHAT; }
// @Override public boolean equals(Object o)
// {
// if(o == null) return false;
// PgpChatId c1;
// try { c1 = (PgpChatId) o; }
// catch (ClassCastException e) { return false; }
//
// return mPgpId.equalsIgnoreCase(c1.getDestPgpId());
// }
// @Override public int hashCode() { return mPgpId.hashCode(); }
// @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mPgpId); }
//
// public static final Parcelable.Creator<PgpChatId> CREATOR = new Parcelable.Creator<PgpChatId>()
// {
// public PgpChatId createFromParcel(Parcel in) { return PgpChatId.Factory.getPgpChatId(in.readString()); }
// public PgpChatId[] newArray(int size) { return new PgpChatId[size]; }
// };
//
// public static final class Factory
// {
// public static PgpChatId getPgpChatId(String destinationPgpId)
// {
// PgpChatId ret = repository.get(destinationPgpId);
// if(ret == null)
// {
// ret = new PgpChatId(destinationPgpId);
// repository.put(destinationPgpId, ret);
// }
// return ret;
// }
// private static final Map<String, PgpChatId> repository = new WeakHashMap<String, PgpChatId>();
// }
//
// private PgpChatId(String destPgpId) { mPgpId = destPgpId; }
// private final String mPgpId;
// }
| import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import org.retroshare.android.RsConversationService.PgpChatId; | /**
* @license
*
* Copyright (c) 2013 Gioacchino Mazzurco <[email protected]>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.retroshare.android;
public class ContactMethodChooserActivity extends Activity
{
public String TAG() { return "ContactMethodChooserActivity"; }
private String serverName;
private String pgpId;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(TAG(), "onCreate(Bundle savedInstanceState)");
Uri uri = getIntent().getData();
if ( uri != null )
{
String sp[] = uri.getPath().split("/");
serverName = sp[1];
pgpId = sp[2];
Intent i = new Intent(this, ConversationFragmentActivity.class);
i.putExtra(ConversationFragmentActivity.SERVER_NAME_EXTRA_KEY, serverName); | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static final class PgpChatId extends ConversationId
// {
// public String getDestPgpId() { return mPgpId; }
// @Override public ConversationKind getConversationKind(){ return ConversationKind.PGP_CHAT; }
// @Override public boolean equals(Object o)
// {
// if(o == null) return false;
// PgpChatId c1;
// try { c1 = (PgpChatId) o; }
// catch (ClassCastException e) { return false; }
//
// return mPgpId.equalsIgnoreCase(c1.getDestPgpId());
// }
// @Override public int hashCode() { return mPgpId.hashCode(); }
// @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mPgpId); }
//
// public static final Parcelable.Creator<PgpChatId> CREATOR = new Parcelable.Creator<PgpChatId>()
// {
// public PgpChatId createFromParcel(Parcel in) { return PgpChatId.Factory.getPgpChatId(in.readString()); }
// public PgpChatId[] newArray(int size) { return new PgpChatId[size]; }
// };
//
// public static final class Factory
// {
// public static PgpChatId getPgpChatId(String destinationPgpId)
// {
// PgpChatId ret = repository.get(destinationPgpId);
// if(ret == null)
// {
// ret = new PgpChatId(destinationPgpId);
// repository.put(destinationPgpId, ret);
// }
// return ret;
// }
// private static final Map<String, PgpChatId> repository = new WeakHashMap<String, PgpChatId>();
// }
//
// private PgpChatId(String destPgpId) { mPgpId = destPgpId; }
// private final String mPgpId;
// }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/ContactMethodChooserActivity.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import org.retroshare.android.RsConversationService.PgpChatId;
/**
* @license
*
* Copyright (c) 2013 Gioacchino Mazzurco <[email protected]>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.retroshare.android;
public class ContactMethodChooserActivity extends Activity
{
public String TAG() { return "ContactMethodChooserActivity"; }
private String serverName;
private String pgpId;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(TAG(), "onCreate(Bundle savedInstanceState)");
Uri uri = getIntent().getData();
if ( uri != null )
{
String sp[] = uri.getPath().split("/");
serverName = sp[1];
pgpId = sp[2];
Intent i = new Intent(this, ConversationFragmentActivity.class);
i.putExtra(ConversationFragmentActivity.SERVER_NAME_EXTRA_KEY, serverName); | i.putExtra(ConversationFragmentActivity.CONVERSATION_ID_EXTRA_KEY, PgpChatId.Factory.getPgpChatId(pgpId)); |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/ListSearchesActivity.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsSearchService.java
// public interface SearchResponseHandler { public void onSearchResponseReceived(int id); }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.retroshare.android.RsSearchService.SearchResponseHandler;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener; | setContentView(R.layout.activity_listsearches);
editText=(EditText) findViewById(R.id.searchEditText_ListSearchesActivity);
listView=(ListView) findViewById(R.id.searchListView_ListSearchesActivity);
editText.setOnKeyListener(new KeyListener());
adapter=new SearchListAdapterListener(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(adapter);
listView.setOnItemLongClickListener(adapter);
}
private class KeyListener implements OnKeyListener
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN)&(event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
{
Log.v(TAG,"KeyListener.onKey() event.getKeyCode() == KeyEvent.KEYCODE_ENTER");
getConnectedServer().mRsSearchService.sendRequestBasicSearch(editText.getText().toString(), new ResponseHandler());
return true;
}
else return false;
}
}
// needed, because we know dont know the serach id before we received the result | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsSearchService.java
// public interface SearchResponseHandler { public void onSearchResponseReceived(int id); }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/ListSearchesActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.retroshare.android.RsSearchService.SearchResponseHandler;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
setContentView(R.layout.activity_listsearches);
editText=(EditText) findViewById(R.id.searchEditText_ListSearchesActivity);
listView=(ListView) findViewById(R.id.searchListView_ListSearchesActivity);
editText.setOnKeyListener(new KeyListener());
adapter=new SearchListAdapterListener(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(adapter);
listView.setOnItemLongClickListener(adapter);
}
private class KeyListener implements OnKeyListener
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN)&(event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
{
Log.v(TAG,"KeyListener.onKey() event.getKeyCode() == KeyEvent.KEYCODE_ENTER");
getConnectedServer().mRsSearchService.sendRequestBasicSearch(editText.getText().toString(), new ResponseHandler());
return true;
}
else return false;
}
}
// needed, because we know dont know the serach id before we received the result | private class ResponseHandler implements SearchResponseHandler |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/LobbiesListFragment.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static class RsConversationServiceListenerUniqueHandleFactory
// {
// public static Long getNewUniqueHandle()
// {
// Long ret = new Long(System.currentTimeMillis());
// while(repository.contains(ret)) ret = new Long(System.currentTimeMillis() + (long)ret.hashCode());
// repository.add(ret);
// return ret;
// }
// private static final Set<Long> repository = new WeakHashSet<Long>();
// }
| import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.retroshare.android.RsConversationService.RsConversationServiceListenerUniqueHandleFactory;
import rsctrl.chat.Chat; | return fv;
}
@Override public void onAttach(Activity a)
{
super.onAttach(a);
mInflater = a.getLayoutInflater();
}
@Override public void onServiceConnected(ComponentName className, IBinder service)
{
super.onServiceConnected(className, service);
if(mHandler == null) mHandler = new Handler();
mHandler.post(new RequestLobbiesListUpdateRunnable());
}
@Override public void registerRsServicesListeners() { getConnectedServer().mRsConversationService.registerRsConversationServiceListener(lobbiesListAdapter); }
@Override public void unregisterRsServicesListeners() { getConnectedServer().mRsConversationService.unregisterRsConversationServiceListener(lobbiesListAdapter); }
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.lobbies_list_context_menu, menu);
int position = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
Chat.ChatLobbyInfo info = lobbiesList.get(position);
boolean joined = info.getLobbyState().equals(Chat.ChatLobbyInfo.LobbyState.LOBBYSTATE_JOINED);
menu.findItem(R.id.join_lobby_menu_item).setVisible(!joined).setOnMenuItemClickListener(new JoinLobbyMenuItemClickListener(position));
menu.findItem(R.id.leave_lobby_menu_item).setVisible(joined).setOnMenuItemClickListener(new LeaveLobbyMenuItemClickListener(position));
menu.findItem(R.id.lobby_show_details_menu_item).setOnMenuItemClickListener(new ShowLobbyInfoMenuItemClickListener(position));
}
private class LobbiesListAdapter implements ListAdapter, RsConversationService.RsConversationServiceListener, AdapterView.OnItemClickListener
{
/** Implements RsConversationServiceListener */ | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static class RsConversationServiceListenerUniqueHandleFactory
// {
// public static Long getNewUniqueHandle()
// {
// Long ret = new Long(System.currentTimeMillis());
// while(repository.contains(ret)) ret = new Long(System.currentTimeMillis() + (long)ret.hashCode());
// repository.add(ret);
// return ret;
// }
// private static final Set<Long> repository = new WeakHashSet<Long>();
// }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/LobbiesListFragment.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.retroshare.android.RsConversationService.RsConversationServiceListenerUniqueHandleFactory;
import rsctrl.chat.Chat;
return fv;
}
@Override public void onAttach(Activity a)
{
super.onAttach(a);
mInflater = a.getLayoutInflater();
}
@Override public void onServiceConnected(ComponentName className, IBinder service)
{
super.onServiceConnected(className, service);
if(mHandler == null) mHandler = new Handler();
mHandler.post(new RequestLobbiesListUpdateRunnable());
}
@Override public void registerRsServicesListeners() { getConnectedServer().mRsConversationService.registerRsConversationServiceListener(lobbiesListAdapter); }
@Override public void unregisterRsServicesListeners() { getConnectedServer().mRsConversationService.unregisterRsConversationServiceListener(lobbiesListAdapter); }
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.lobbies_list_context_menu, menu);
int position = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
Chat.ChatLobbyInfo info = lobbiesList.get(position);
boolean joined = info.getLobbyState().equals(Chat.ChatLobbyInfo.LobbyState.LOBBYSTATE_JOINED);
menu.findItem(R.id.join_lobby_menu_item).setVisible(!joined).setOnMenuItemClickListener(new JoinLobbyMenuItemClickListener(position));
menu.findItem(R.id.leave_lobby_menu_item).setVisible(joined).setOnMenuItemClickListener(new LeaveLobbyMenuItemClickListener(position));
menu.findItem(R.id.lobby_show_details_menu_item).setOnMenuItemClickListener(new ShowLobbyInfoMenuItemClickListener(position));
}
private class LobbiesListAdapter implements ListAdapter, RsConversationService.RsConversationServiceListener, AdapterView.OnItemClickListener
{
/** Implements RsConversationServiceListener */ | private final Long handle = RsConversationServiceListenerUniqueHandleFactory.getNewUniqueHandle(); |
RetroShare/AndroidClient | RetroShareAndroidIntegration/src/org/retroshare/android/ConversationFragmentActivity.java | // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static abstract class ConversationId implements Parcelable
// {
// abstract public ConversationKind getConversationKind();
// @Override public int describeContents() { return getConversationKind().ordinal(); }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import org.retroshare.android.RsConversationService.ConversationId; | /**
* @license
*
* Copyright (c) 2013 Gioacchino Mazzurco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.retroshare.android;
public class ConversationFragmentActivity extends ProxiedFragmentActivityBase
{
public static final String CONVERSATION_ID_EXTRA_KEY = ConversationFragment.CONVERSATION_ID_EXTRA_KEY;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.factivity_conversation);
onNewIntent(getIntent());
}
| // Path: RetroShareAndroidIntegration/src/org/retroshare/android/RsConversationService.java
// public static abstract class ConversationId implements Parcelable
// {
// abstract public ConversationKind getConversationKind();
// @Override public int describeContents() { return getConversationKind().ordinal(); }
// }
// Path: RetroShareAndroidIntegration/src/org/retroshare/android/ConversationFragmentActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import org.retroshare.android.RsConversationService.ConversationId;
/**
* @license
*
* Copyright (c) 2013 Gioacchino Mazzurco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.retroshare.android;
public class ConversationFragmentActivity extends ProxiedFragmentActivityBase
{
public static final String CONVERSATION_ID_EXTRA_KEY = ConversationFragment.CONVERSATION_ID_EXTRA_KEY;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.factivity_conversation);
onNewIntent(getIntent());
}
| private ConversationId lastConversationId; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package com.efoodstore.dao.impl;
@Repository
@Transactional | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package com.efoodstore.dao.impl;
@Repository
@Transactional | public class CartItemDaoImpl implements CartItemDao{ |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartItemDaoImpl implements CartItemDao{
@Autowired
private SessionFactory sessionFactory;
| // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartItemDaoImpl implements CartItemDao{
@Autowired
private SessionFactory sessionFactory;
| public void addCartItem(CartItem cartItem) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartItemDaoImpl implements CartItemDao{
@Autowired
private SessionFactory sessionFactory;
public void addCartItem(CartItem cartItem) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(cartItem);
session.flush();
}
public void removeCartItem (CartItem cartItem) {
Session session = sessionFactory.getCurrentSession();
session.delete(cartItem);
session.flush();
}
| // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartItemDaoImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartItemDaoImpl implements CartItemDao{
@Autowired
private SessionFactory sessionFactory;
public void addCartItem(CartItem cartItem) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(cartItem);
session.flush();
}
public void removeCartItem (CartItem cartItem) {
Session session = sessionFactory.getCurrentSession();
session.delete(cartItem);
session.flush();
}
| public void removeAllCartItems(Cart cart) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired | private CustomerOrderDao customerOrderDao; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired | private CartService cartService; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
| // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
| public void addCustomerOrder(CustomerOrder customerOrder) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
public void addCustomerOrder(CustomerOrder customerOrder) {
customerOrderDao.addCustomerOrder(customerOrder);
}
public double getCustomerOrderGrandTotal(int cartId) {
double grandTotal=0; | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
public void addCustomerOrder(CustomerOrder customerOrder) {
customerOrderDao.addCustomerOrder(customerOrder);
}
public double getCustomerOrderGrandTotal(int cartId) {
double grandTotal=0; | Cart cart = cartService.getCartById(cartId); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
public void addCustomerOrder(CustomerOrder customerOrder) {
customerOrderDao.addCustomerOrder(customerOrder);
}
public double getCustomerOrderGrandTotal(int cartId) {
double grandTotal=0;
Cart cart = cartService.getCartById(cartId); | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerOrderServiceImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.model.CustomerOrder;
import com.efoodstore.service.CartService;
import com.efoodstore.service.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerOrderServiceImpl implements CustomerOrderService {
@Autowired
private CustomerOrderDao customerOrderDao;
@Autowired
private CartService cartService;
public void addCustomerOrder(CustomerOrder customerOrder) {
customerOrderDao.addCustomerOrder(customerOrder);
}
public double getCustomerOrderGrandTotal(int cartId) {
double grandTotal=0;
Cart cart = cartService.getCartById(cartId); | List<CartItem> cartItems = cart.getCartItems(); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/ProductController.java | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.List; | package com.efoodstore.controller;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/controller/ProductController.java
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.List;
package com.efoodstore.controller;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired | private ProductService productService; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/ProductController.java | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.List; | package com.efoodstore.controller;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("/productList/all")
public String getProducts(Model model) { | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/controller/ProductController.java
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.List;
package com.efoodstore.controller;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("/productList/all")
public String getProducts(Model model) { | List<Product> products = productService.getProductList(); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerDao.java
// public interface CustomerDao {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
| import com.efoodstore.dao.CustomerDao;
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired | // Path: src/main/java/com/efoodstore/dao/CustomerDao.java
// public interface CustomerDao {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerServiceImpl.java
import com.efoodstore.dao.CustomerDao;
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired | private CustomerDao customerDao; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CustomerServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerDao.java
// public interface CustomerDao {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
| import com.efoodstore.dao.CustomerDao;
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerDao customerDao;
| // Path: src/main/java/com/efoodstore/dao/CustomerDao.java
// public interface CustomerDao {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
// Path: src/main/java/com/efoodstore/service/impl/CustomerServiceImpl.java
import com.efoodstore.dao.CustomerDao;
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerDao customerDao;
| public void addCustomer (Customer customer) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CustomerOrderDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.CustomerOrder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; | package com.efoodstore.dao.impl;
@Repository
@Transactional | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/CustomerOrderDaoImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.CustomerOrder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
package com.efoodstore.dao.impl;
@Repository
@Transactional | public class CustomerOrderDaoImpl implements CustomerOrderDao{ |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CustomerOrderDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
| import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.CustomerOrder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CustomerOrderDaoImpl implements CustomerOrderDao{
@Autowired
private SessionFactory sessionFactory;
| // Path: src/main/java/com/efoodstore/dao/CustomerOrderDao.java
// public interface CustomerOrderDao {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// }
//
// Path: src/main/java/com/efoodstore/model/CustomerOrder.java
// @Entity
// public class CustomerOrder implements Serializable{
//
// private static final long serialVersionUID = 2983360377227484514L;
//
// @Id
// @GeneratedValue
// private int customerOrderId;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// private Cart cart;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// private Customer customer;
//
// @OneToOne
// @JoinColumn(name = "billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// public int getCustomerOrderId() {
// return customerOrderId;
// }
//
// public void setCustomerOrderId(int customerOrderId) {
// this.customerOrderId = customerOrderId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/CustomerOrderDaoImpl.java
import com.efoodstore.dao.CustomerOrderDao;
import com.efoodstore.model.CustomerOrder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CustomerOrderDaoImpl implements CustomerOrderDao{
@Autowired
private SessionFactory sessionFactory;
| public void addCustomerOrder(CustomerOrder customerOrder) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/ProductDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
| import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package com.efoodstore.dao.impl;
@Repository
@Transactional | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/ProductDaoImpl.java
import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package com.efoodstore.dao.impl;
@Repository
@Transactional | public class ProductDaoImpl implements ProductDao { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/ProductDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
| import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class ProductDaoImpl implements ProductDao {
@Autowired
private SessionFactory sessionFactory;
| // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
// Path: src/main/java/com/efoodstore/dao/impl/ProductDaoImpl.java
import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class ProductDaoImpl implements ProductDao {
@Autowired
private SessionFactory sessionFactory;
| public Product getProductById (int id) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/CartItemDao.java | // Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
| import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem; | package com.efoodstore.dao;
public interface CartItemDao {
void addCartItem(CartItem cartItem);
void removeCartItem(CartItem cartItem);
| // Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
// Path: src/main/java/com/efoodstore/dao/CartItemDao.java
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
package com.efoodstore.dao;
public interface CartItemDao {
void addCartItem(CartItem cartItem);
void removeCartItem(CartItem cartItem);
| void removeAllCartItems(Cart cart); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/CartController.java | // Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
| import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; | package com.efoodstore.controller;
@Controller
@RequestMapping("/customer/cart")
public class CartController {
@Autowired | // Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
// Path: src/main/java/com/efoodstore/controller/CartController.java
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
package com.efoodstore.controller;
@Controller
@RequestMapping("/customer/cart")
public class CartController {
@Autowired | private CustomerService customerService; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/CartController.java | // Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
| import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; | package com.efoodstore.controller;
@Controller
@RequestMapping("/customer/cart")
public class CartController {
@Autowired
private CustomerService customerService;
@RequestMapping
public String getCart(@AuthenticationPrincipal User activeUser){ | // Path: src/main/java/com/efoodstore/model/Customer.java
// @Entity
// public class Customer implements Serializable{
//
// private static final long serialVersionUID = 5140900014886997914L;
//
// @Id
// @GeneratedValue
// private int customerId;
//
// @NotEmpty (message = "The customer name must not be null.")
// private String customerName;
//
// @NotEmpty (message = "The customer email must not be null.")
// private String customerEmail;
// private String customerPhone;
//
// @NotEmpty (message = "The customer username must not be null.")
// private String username;
//
// @NotEmpty (message = "The customer password must not be null.")
// private String password;
//
// private boolean enabled;
//
// @OneToOne
// @JoinColumn(name="billingAddressId")
// private BillingAddress billingAddress;
//
// @OneToOne
// @JoinColumn(name="shippingAddressId")
// private ShippingAddress shippingAddress;
//
// @OneToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// public int getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(int customerId) {
// this.customerId = customerId;
// }
//
// 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 getCustomerPhone() {
// return customerPhone;
// }
//
// public void setCustomerPhone(String customerPhone) {
// this.customerPhone = customerPhone;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public BillingAddress getBillingAddress() {
// return billingAddress;
// }
//
// public void setBillingAddress(BillingAddress billingAddress) {
// this.billingAddress = billingAddress;
// }
//
// public ShippingAddress getShippingAddress() {
// return shippingAddress;
// }
//
// public void setShippingAddress(ShippingAddress shippingAddress) {
// this.shippingAddress = shippingAddress;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerService.java
// public interface CustomerService {
//
// void addCustomer (Customer customer);
//
// Customer getCustomerById (int customerId);
//
// List<Customer> getAllCustomers();
//
// Customer getCustomerByUsername (String username);
// }
// Path: src/main/java/com/efoodstore/controller/CartController.java
import com.efoodstore.model.Customer;
import com.efoodstore.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
package com.efoodstore.controller;
@Controller
@RequestMapping("/customer/cart")
public class CartController {
@Autowired
private CustomerService customerService;
@RequestMapping
public String getCart(@AuthenticationPrincipal User activeUser){ | Customer customer = customerService.getCustomerByUsername (activeUser.getUsername()); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/CartItemService.java | // Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
| import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem; | package com.efoodstore.service;
public interface CartItemService {
void addCartItem(CartItem cartItem);
void removeCartItem(CartItem cartItem);
| // Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
// Path: src/main/java/com/efoodstore/service/CartItemService.java
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
package com.efoodstore.service;
public interface CartItemService {
void addCartItem(CartItem cartItem);
void removeCartItem(CartItem cartItem);
| void removeAllCartItems(Cart cart); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/ProductServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/service/impl/ProductServiceImpl.java
import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired | private ProductDao productDao; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/ProductServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | package com.efoodstore.service.impl;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
| // Path: src/main/java/com/efoodstore/dao/ProductDao.java
// public interface ProductDao {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
//
// Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/service/impl/ProductServiceImpl.java
import com.efoodstore.dao.ProductDao;
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
package com.efoodstore.service.impl;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
| public Product getProductById (int productId) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/admin/AdminProduct.java | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; | package com.efoodstore.controller.admin;
@Controller
@RequestMapping("/admin")
public class AdminProduct {
private Path path;
@Autowired | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/controller/admin/AdminProduct.java
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
package com.efoodstore.controller.admin;
@Controller
@RequestMapping("/admin")
public class AdminProduct {
private Path path;
@Autowired | private ProductService productService; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/controller/admin/AdminProduct.java | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
| import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; | package com.efoodstore.controller.admin;
@Controller
@RequestMapping("/admin")
public class AdminProduct {
private Path path;
@Autowired
private ProductService productService;
@RequestMapping("/product/addProduct")
public String addProduct(Model model) { | // Path: src/main/java/com/efoodstore/model/Product.java
// @Entity
// public class Product implements Serializable{
//
// private static final long serialVersionUID = -3532377236419382983L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int productId;
//
// @NotEmpty (message = "The product name must not be null.")
//
// private String productName;
// private String productCategory;
// private String productDescription;
//
// @Min(value = 0, message = "The product price must no be less then zero.")
// private double productPrice;
// //private String productCondition;
// private String productStatus;
//
// @Min(value = 0, message = "The product unit must not be less than zero.")
// private int unitInStock;
// private String productManufacturer;
//
// @Transient
// private MultipartFile productImage;
//
//
// @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JsonIgnore
// private List<CartItem> cartItemList;
//
// public int getProductId() {
// return productId;
// }
//
// public void setProductId(int productId) {
// this.productId = productId;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductCategory() {
// return productCategory;
// }
//
// public void setProductCategory(String productCategory) {
// this.productCategory = productCategory;
// }
//
// public String getProductDescription() {
// return productDescription;
// }
//
// public void setProductDescription(String productDescription) {
// this.productDescription = productDescription;
// }
//
// public double getProductPrice() {
// return productPrice;
// }
//
// public void setProductPrice(double productPrice) {
// this.productPrice = productPrice;
// }
//
// // public String getProductCondition() {
// // return productCondition;
// // }
// //
// // public void setProductCondition(String productCondition) {
// // this.productCondition = productCondition;
// // }
//
// public String getProductStatus() {
// return productStatus;
// }
//
// public void setProductStatus(String productStatus) {
// this.productStatus = productStatus;
// }
//
// public int getUnitInStock() {
// return unitInStock;
// }
//
// public void setUnitInStock(int unitInStock) {
// this.unitInStock = unitInStock;
// }
//
// public String getProductManufacturer() {
// return productManufacturer;
// }
//
// public void setProductManufacturer(String productManufacturer) {
// this.productManufacturer = productManufacturer;
// }
//
// public MultipartFile getProductImage() {
// return productImage;
// }
//
// public void setProductImage(MultipartFile productImage) {
// this.productImage = productImage;
// }
//
//
// public List<CartItem> getCartItemList() {
// return cartItemList;
// }
//
// public void setCartItemList(List<CartItem> cartItemList) {
// this.cartItemList = cartItemList;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/ProductService.java
// public interface ProductService {
//
// List<Product> getProductList();
//
// Product getProductById(int id);
//
// void addProduct(Product product);
//
// void editProduct(Product product);
//
// void deleteProduct(Product product);
// }
// Path: src/main/java/com/efoodstore/controller/admin/AdminProduct.java
import com.efoodstore.model.Product;
import com.efoodstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
package com.efoodstore.controller.admin;
@Controller
@RequestMapping("/admin")
public class AdminProduct {
private Path path;
@Autowired
private ProductService productService;
@RequestMapping("/product/addProduct")
public String addProduct(Model model) { | Product product = new Product(); |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired | private CartItemDao cartItemDao; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired
private CartItemDao cartItemDao;
| // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired
private CartItemDao cartItemDao;
| public void addCartItem(CartItem cartItem) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
| import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired
private CartItemDao cartItemDao;
public void addCartItem(CartItem cartItem) {
cartItemDao.addCartItem(cartItem);
}
public void removeCartItem(CartItem cartItem) {
cartItemDao.removeCartItem(cartItem);
}
| // Path: src/main/java/com/efoodstore/dao/CartItemDao.java
// public interface CartItemDao {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
//
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/model/CartItem.java
// @Entity
// public class CartItem implements Serializable{
//
// private static final long serialVersionUID = -904360230041854157L;
//
// @Id
// @GeneratedValue
// private int cartItemId;
//
// @ManyToOne
// @JoinColumn(name = "cartId")
// @JsonIgnore
// private Cart cart;
//
// @ManyToOne
// @JoinColumn(name = "productId")
// private Product product;
//
// private int quantity;
// private double totalPrice;
//
// public int getCartItemId() {
// return cartItemId;
// }
//
// public void setCartItemId(int cartItemId) {
// this.cartItemId = cartItemId;
// }
//
// public Cart getCart() {
// return cart;
// }
//
// public void setCart(Cart cart) {
// this.cart = cart;
// }
//
// public Product getProduct() {
// return product;
// }
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public void setQuantity(int quantity) {
// this.quantity = quantity;
// }
//
// public double getTotalPrice() {
// return totalPrice;
// }
//
// public void setTotalPrice(double totalPrice) {
// this.totalPrice = totalPrice;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartItemService.java
// public interface CartItemService {
//
// void addCartItem(CartItem cartItem);
//
// void removeCartItem(CartItem cartItem);
//
// void removeAllCartItems(Cart cart);
//
// CartItem getCartItemByProductId (int productId);
// }
// Path: src/main/java/com/efoodstore/service/impl/CartItemServiceImpl.java
import com.efoodstore.dao.CartItemDao;
import com.efoodstore.model.Cart;
import com.efoodstore.model.CartItem;
import com.efoodstore.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.efoodstore.service.impl;
@Service
public class CartItemServiceImpl implements CartItemService{
@Autowired
private CartItemDao cartItemDao;
public void addCartItem(CartItem cartItem) {
cartItemDao.addCartItem(cartItem);
}
public void removeCartItem(CartItem cartItem) {
cartItemDao.removeCartItem(cartItem);
}
| public void removeAllCartItems(Cart cart){ |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; | package com.efoodstore.dao.impl;
@Repository
@Transactional | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java
import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
package com.efoodstore.dao.impl;
@Repository
@Transactional | public class CartDaoImpl implements CartDao{ |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartDaoImpl implements CartDao{
@Autowired
private SessionFactory sessionFactory;
@Autowired | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java
import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartDaoImpl implements CartDao{
@Autowired
private SessionFactory sessionFactory;
@Autowired | private CustomerOrderService customerOrderService; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
| import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; | package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartDaoImpl implements CartDao{
@Autowired
private SessionFactory sessionFactory;
@Autowired
private CustomerOrderService customerOrderService;
| // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CustomerOrderService.java
// public interface CustomerOrderService {
//
// void addCustomerOrder(CustomerOrder customerOrder);
//
// double getCustomerOrderGrandTotal(int cartId);
// }
// Path: src/main/java/com/efoodstore/dao/impl/CartDaoImpl.java
import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CustomerOrderService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
package com.efoodstore.dao.impl;
@Repository
@Transactional
public class CartDaoImpl implements CartDao{
@Autowired
private SessionFactory sessionFactory;
@Autowired
private CustomerOrderService customerOrderService;
| public Cart getCartById (int cartId) { |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CartServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
| import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.efoodstore.service.impl;
@Service
public class CartServiceImpl implements CartService {
@Autowired | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
// Path: src/main/java/com/efoodstore/service/impl/CartServiceImpl.java
import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.efoodstore.service.impl;
@Service
public class CartServiceImpl implements CartService {
@Autowired | private CartDao cartDao; |
OliviaLiyuanWei/Foodtastic-e-foodstore-website | src/main/java/com/efoodstore/service/impl/CartServiceImpl.java | // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
| import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.efoodstore.service.impl;
@Service
public class CartServiceImpl implements CartService {
@Autowired
private CartDao cartDao;
| // Path: src/main/java/com/efoodstore/dao/CartDao.java
// public interface CartDao {
//
// Cart getCartById (int cartId);
//
// Cart validate(int cartId) throws IOException;
//
// void update(Cart cart);
// }
//
// Path: src/main/java/com/efoodstore/model/Cart.java
// @Entity
// public class Cart implements Serializable {
//
// private static final long serialVersionUID = 3940548625296145582L;
//
// @Id
// @GeneratedValue
// private int cartId;
//
// @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<CartItem> cartItems;
//
// @OneToOne
// @JoinColumn(name = "customerId")
// @JsonIgnore
// private Customer customer;
//
// private double grandTotal;
//
// public int getCartId() {
// return cartId;
// }
//
// public void setCartId(int cartId) {
// this.cartId = cartId;
// }
//
// public List<CartItem> getCartItems() {
// return cartItems;
// }
//
// public void setCartItems(List<CartItem> cartItems) {
// this.cartItems = cartItems;
// }
//
// public Customer getCustomer() {
// return customer;
// }
//
// public void setCustomer(Customer customer) {
// this.customer = customer;
// }
//
// public double getGrandTotal() {
// return grandTotal;
// }
//
// public void setGrandTotal(double grandTotal) {
// this.grandTotal = grandTotal;
// }
// }
//
// Path: src/main/java/com/efoodstore/service/CartService.java
// public interface CartService {
//
// Cart getCartById (int cartId);
//
// void update(Cart cart);
// }
// Path: src/main/java/com/efoodstore/service/impl/CartServiceImpl.java
import com.efoodstore.dao.CartDao;
import com.efoodstore.model.Cart;
import com.efoodstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.efoodstore.service.impl;
@Service
public class CartServiceImpl implements CartService {
@Autowired
private CartDao cartDao;
| public Cart getCartById(int cartId) { |
jMotif/SAX | src/test/java/net/seninp/jmotif/sax/datastructures/TestFrequencyTableEntry.java | // Path: src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java
// public class FrequencyTableEntry implements Comparable<FrequencyTableEntry> {
//
// private int position;
// private char[] payload;
// private int frequency;
//
// /**
// * Constructor.
// *
// * @param len the length of the string.
// * @param pos the occurrence position.
// */
// public FrequencyTableEntry(int len, int pos) {
// this.payload = new char[len];
// this.frequency = -1;
// this.position = pos;
// }
//
// /**
// * Constructor.
// *
// * @param position the original entry position.
// * @param payload the payload string.
// * @param frequency the frequency.
// */
// public FrequencyTableEntry(Integer position, char[] payload, int frequency) {
// this.position = position;
// this.payload = payload;
// this.frequency = frequency;
// }
//
// /**
// * Get a string payload.
// *
// * @return a string payload.
// */
// public char[] getStr() {
// char[] res = new char[this.payload.length];
// for (int i = 0; i < res.length; i++) {
// res[i] = this.payload[i];
// }
// return res;
// }
//
// /**
// * Set a string payload.
// *
// * @param str the string payload.
// */
// public void setStr(char[] str) {
// this.payload = Arrays.copyOf(str, str.length);
// }
//
// /**
// * Get the observed frequency of the word.
// *
// * @return the observed frequency of the word.
// */
// public int getFrequency() {
// return frequency;
// }
//
// /**
// * Set the observed frequency of the word.
// *
// * @param frequency The frequency to set.
// */
// public void setFrequency(int frequency) {
// this.frequency = frequency;
// }
//
// /**
// * Get the position of the word.
// *
// * @return the position of the word.
// */
// public int getPosition() {
// return position;
// }
//
// /**
// * Set the position of the word.
// *
// * @param position The position to set.
// */
// public void setPosition(int position) {
// this.position = position;
// }
//
// /**
// * Check the complexity of the string.
// *
// * @param complexity If 1 - single letter used, 2 - two or more letters, 3 - 3 or more etc..
// *
// * @return Returns true if complexity conditions are met.
// */
// public boolean isTrivial(Integer complexity) {
// int len = payload.length;
// if ((null == complexity) || (len < 2)) {
// return true;
// }
// else if ((complexity.intValue() > 0) && (len > 2)) {
// Set<Character> seen = new TreeSet<Character>();
// for (int i = 0; i < len; i++) {
// Character c = Character.valueOf(this.payload[i]);
// if (seen.contains(c)) {
// continue;
// }
// else {
// seen.add(c);
// }
// }
// if (complexity.intValue() <= seen.size()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int compareTo(FrequencyTableEntry arg0) {
// if (null == arg0) {
// throw new NullPointerException("Unable to compare with a null object.");
// }
// if (this.frequency > arg0.getFrequency()) {
// return 1;
// }
// else if (this.frequency < arg0.getFrequency()) {
// return -1;
// }
// return 0;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + frequency;
// result = prime * result + Arrays.hashCode(payload);
// return result;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// FrequencyTableEntry other = (FrequencyTableEntry) obj;
// if (frequency != other.frequency) {
// return false;
// }
// if (!Arrays.equals(payload, other.payload)) {
// return false;
// }
// return true;
// }
//
// /**
// * {@inheritDoc}
// */
// public String toString() {
// return "payload: " + String.valueOf(this.payload) + ", frequency: " + this.frequency
// + ", location: " + this.position;
// }
//
// /**
// * Makes the instance copy.
// *
// * @return the object copy (a "clone").
// */
// public FrequencyTableEntry copy() {
// FrequencyTableEntry res = new FrequencyTableEntry(this.position, this.payload, this.frequency);
// return res;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import net.seninp.jmotif.sax.datastructure.FrequencyTableEntry; | package net.seninp.jmotif.sax.datastructures;
/**
* Test frequency table entry.
*
* @author psenin
*
*/
public class TestFrequencyTableEntry {
@Test
public void testFrequencyTableEntryIntInt() {
| // Path: src/main/java/net/seninp/jmotif/sax/datastructure/FrequencyTableEntry.java
// public class FrequencyTableEntry implements Comparable<FrequencyTableEntry> {
//
// private int position;
// private char[] payload;
// private int frequency;
//
// /**
// * Constructor.
// *
// * @param len the length of the string.
// * @param pos the occurrence position.
// */
// public FrequencyTableEntry(int len, int pos) {
// this.payload = new char[len];
// this.frequency = -1;
// this.position = pos;
// }
//
// /**
// * Constructor.
// *
// * @param position the original entry position.
// * @param payload the payload string.
// * @param frequency the frequency.
// */
// public FrequencyTableEntry(Integer position, char[] payload, int frequency) {
// this.position = position;
// this.payload = payload;
// this.frequency = frequency;
// }
//
// /**
// * Get a string payload.
// *
// * @return a string payload.
// */
// public char[] getStr() {
// char[] res = new char[this.payload.length];
// for (int i = 0; i < res.length; i++) {
// res[i] = this.payload[i];
// }
// return res;
// }
//
// /**
// * Set a string payload.
// *
// * @param str the string payload.
// */
// public void setStr(char[] str) {
// this.payload = Arrays.copyOf(str, str.length);
// }
//
// /**
// * Get the observed frequency of the word.
// *
// * @return the observed frequency of the word.
// */
// public int getFrequency() {
// return frequency;
// }
//
// /**
// * Set the observed frequency of the word.
// *
// * @param frequency The frequency to set.
// */
// public void setFrequency(int frequency) {
// this.frequency = frequency;
// }
//
// /**
// * Get the position of the word.
// *
// * @return the position of the word.
// */
// public int getPosition() {
// return position;
// }
//
// /**
// * Set the position of the word.
// *
// * @param position The position to set.
// */
// public void setPosition(int position) {
// this.position = position;
// }
//
// /**
// * Check the complexity of the string.
// *
// * @param complexity If 1 - single letter used, 2 - two or more letters, 3 - 3 or more etc..
// *
// * @return Returns true if complexity conditions are met.
// */
// public boolean isTrivial(Integer complexity) {
// int len = payload.length;
// if ((null == complexity) || (len < 2)) {
// return true;
// }
// else if ((complexity.intValue() > 0) && (len > 2)) {
// Set<Character> seen = new TreeSet<Character>();
// for (int i = 0; i < len; i++) {
// Character c = Character.valueOf(this.payload[i]);
// if (seen.contains(c)) {
// continue;
// }
// else {
// seen.add(c);
// }
// }
// if (complexity.intValue() <= seen.size()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int compareTo(FrequencyTableEntry arg0) {
// if (null == arg0) {
// throw new NullPointerException("Unable to compare with a null object.");
// }
// if (this.frequency > arg0.getFrequency()) {
// return 1;
// }
// else if (this.frequency < arg0.getFrequency()) {
// return -1;
// }
// return 0;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + frequency;
// result = prime * result + Arrays.hashCode(payload);
// return result;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// FrequencyTableEntry other = (FrequencyTableEntry) obj;
// if (frequency != other.frequency) {
// return false;
// }
// if (!Arrays.equals(payload, other.payload)) {
// return false;
// }
// return true;
// }
//
// /**
// * {@inheritDoc}
// */
// public String toString() {
// return "payload: " + String.valueOf(this.payload) + ", frequency: " + this.frequency
// + ", location: " + this.position;
// }
//
// /**
// * Makes the instance copy.
// *
// * @return the object copy (a "clone").
// */
// public FrequencyTableEntry copy() {
// FrequencyTableEntry res = new FrequencyTableEntry(this.position, this.payload, this.frequency);
// return res;
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/sax/datastructures/TestFrequencyTableEntry.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import net.seninp.jmotif.sax.datastructure.FrequencyTableEntry;
package net.seninp.jmotif.sax.datastructures;
/**
* Test frequency table entry.
*
* @author psenin
*
*/
public class TestFrequencyTableEntry {
@Test
public void testFrequencyTableEntryIntInt() {
| final FrequencyTableEntry fe1 = new FrequencyTableEntry(10, 11); |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/datastructure/DoublyLinkedSortedList.java | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
| import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import net.seninp.util.StackTrace; | public MyIterator(DoublyLinkedSortedList<T> doublyLinkedSortedList) {
this.list = doublyLinkedSortedList;
}
@Override
public boolean hasNext() {
if (null == this.current) {
if (this.list.isEmpty()) {
return false;
}
return true;
}
if (null == this.current.next) {
return false;
}
return true;
}
@Override
public T next() {
try {
if (null == current) {
current = this.list.first;
return current.data;
}
current = current.next;
return current.data;
}
catch (Exception e) {
throw new NoSuchElementException( | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
// Path: src/main/java/net/seninp/jmotif/sax/datastructure/DoublyLinkedSortedList.java
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import net.seninp.util.StackTrace;
public MyIterator(DoublyLinkedSortedList<T> doublyLinkedSortedList) {
this.list = doublyLinkedSortedList;
}
@Override
public boolean hasNext() {
if (null == this.current) {
if (this.list.isEmpty()) {
return false;
}
return true;
}
if (null == this.current.next) {
return false;
}
return true;
}
@Override
public T next() {
try {
if (null == current) {
current = this.list.first;
return current.data;
}
current = current.next;
return current.data;
}
catch (Exception e) {
throw new NoSuchElementException( | "There was an exception thrown: " + StackTrace.toString(e)); |
jMotif/SAX | src/test/java/net/seninp/jmotif/sax/datastructures/TestMagicArrayEntry.java | // Path: src/main/java/net/seninp/jmotif/sax/registry/MagicArrayEntry.java
// public class MagicArrayEntry implements Comparable<MagicArrayEntry> {
//
// protected String word;
// protected int freq;
//
// public MagicArrayEntry(String payload, int frequency) {
// this.word = payload;
// this.freq = frequency;
// }
//
// @Override
// public int compareTo(MagicArrayEntry arg0) {
// if (arg0 == null) {
// throw new NullPointerException("Unable to compare with a null object.");
// }
// if (this.freq > arg0.freq) {
// return 1;
// }
// else if (this.freq < arg0.freq) {
// return -1;
// }
// return 0;
// }
//
// public String getStr() {
// return this.word;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + freq;
// result = prime * result + ((word == null) ? 0 : word.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MagicArrayEntry other = (MagicArrayEntry) obj;
// if (freq != other.freq)
// return false;
// if (word == null) {
// if (other.word != null)
// return false;
// }
// else if (!word.equals(other.word))
// return false;
// return true;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import net.seninp.jmotif.sax.registry.MagicArrayEntry; | package net.seninp.jmotif.sax.datastructures;
public class TestMagicArrayEntry {
private static final String PAYLOAD1 = "aaa";
private static final int FREQUENCY1 = 2;
private static final String PAYLOAD2 = "bbb";
private static final int FREQUENCY2 = 7;
@Test
public void testHashCode() { | // Path: src/main/java/net/seninp/jmotif/sax/registry/MagicArrayEntry.java
// public class MagicArrayEntry implements Comparable<MagicArrayEntry> {
//
// protected String word;
// protected int freq;
//
// public MagicArrayEntry(String payload, int frequency) {
// this.word = payload;
// this.freq = frequency;
// }
//
// @Override
// public int compareTo(MagicArrayEntry arg0) {
// if (arg0 == null) {
// throw new NullPointerException("Unable to compare with a null object.");
// }
// if (this.freq > arg0.freq) {
// return 1;
// }
// else if (this.freq < arg0.freq) {
// return -1;
// }
// return 0;
// }
//
// public String getStr() {
// return this.word;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + freq;
// result = prime * result + ((word == null) ? 0 : word.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MagicArrayEntry other = (MagicArrayEntry) obj;
// if (freq != other.freq)
// return false;
// if (word == null) {
// if (other.word != null)
// return false;
// }
// else if (!word.equals(other.word))
// return false;
// return true;
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/sax/datastructures/TestMagicArrayEntry.java
import static org.junit.Assert.*;
import org.junit.Test;
import net.seninp.jmotif.sax.registry.MagicArrayEntry;
package net.seninp.jmotif.sax.datastructures;
public class TestMagicArrayEntry {
private static final String PAYLOAD1 = "aaa";
private static final int FREQUENCY1 = 2;
private static final String PAYLOAD2 = "bbb";
private static final int FREQUENCY2 = 7;
@Test
public void testHashCode() { | MagicArrayEntry entry1 = new MagicArrayEntry(PAYLOAD1, FREQUENCY1); |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/bitmap/BitmapParameters.java | // Path: src/main/java/net/seninp/jmotif/sax/NumerosityReductionStrategy.java
// public enum NumerosityReductionStrategy {
//
// /** No reduction at all - all the words going make it into collection. */
// NONE(0),
//
// /** Exact - the strategy based on the exact string match. */
// EXACT(1),
//
// /** Classic - the Lin's and Keogh's MINDIST based strategy. */
// MINDIST(2);
//
// private final int index;
//
// /**
// * Constructor.
// *
// * @param index The strategy index.
// */
// NumerosityReductionStrategy(int index) {
// this.index = index;
// }
//
// /**
// * Gets the integer index of the instance.
// *
// * @return integer key of the instance.
// */
// public int index() {
// return index;
// }
//
// /**
// * Makes a strategy out of integer. 0 stands for NONE, 1 for EXACT, and 3 for MINDIST.
// *
// * @param value the key value.
// * @return the new Strategy instance.
// */
// public static NumerosityReductionStrategy fromValue(int value) {
// switch (value) {
// case 0:
// return NumerosityReductionStrategy.NONE;
// case 1:
// return NumerosityReductionStrategy.EXACT;
// case 2:
// return NumerosityReductionStrategy.MINDIST;
// default:
// throw new RuntimeException("Unknown index:" + value);
// }
// }
//
// /**
// * {@inheritDoc}
// */
// public String toString() {
// switch (this.index) {
// case 0:
// return "NONE";
// case 1:
// return "EXACT";
// case 2:
// return "MINDIST";
// default:
// throw new RuntimeException("Unknown index:" + this.index);
// }
// }
//
// /**
// * Parse the string value into an instance.
// *
// * @param value the string value.
// * @return new instance.
// */
// public static NumerosityReductionStrategy fromString(String value) {
// if ("none".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.NONE;
// }
// else if ("exact".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.EXACT;
// }
// else if ("mindist".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.MINDIST;
// }
// else {
// throw new RuntimeException("Unknown index:" + value);
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.Parameter;
import net.seninp.jmotif.sax.NumerosityReductionStrategy; | package net.seninp.jmotif.sax.bitmap;
/**
* Parameters accepted by the bitmap printer and their default values.
*
* @author psenin
*
*/
public class BitmapParameters {
// general setup
//
@Parameter
public List<String> parameters = new ArrayList<String>();
@Parameter(names = "--verbose", description = "Level of verbosity")
public Integer verbose = 1;
@Parameter(names = { "--help", "-h" }, help = true)
public boolean help;
// dataset
//
@Parameter(names = { "--data_in", "-d" }, description = "The input file name")
public static String IN_FILE;
// output
//
@Parameter(names = { "--data_out", "-o" }, description = "The output file name")
public static String OUT_FILE = "shingling_out.txt";
@Parameter(names = { "--bitmap_out", "-b" }, description = "The bitmap output file name")
public static String BITMAP_FILE = "my-chart.png";
// discretization parameters
//
@Parameter(names = { "--window_size", "-w" }, description = "Sliding window size")
public static int SAX_WINDOW_SIZE = 30;
@Parameter(names = { "--word_size", "-p" }, description = "PAA word size")
public static int SAX_PAA_SIZE = 6;
@Parameter(names = { "--alphabet_size", "-a" }, description = "SAX alphabet size")
public static int SAX_ALPHABET_SIZE = 4;
@Parameter(names = "--strategy", description = "Numerosity reduction strategy") | // Path: src/main/java/net/seninp/jmotif/sax/NumerosityReductionStrategy.java
// public enum NumerosityReductionStrategy {
//
// /** No reduction at all - all the words going make it into collection. */
// NONE(0),
//
// /** Exact - the strategy based on the exact string match. */
// EXACT(1),
//
// /** Classic - the Lin's and Keogh's MINDIST based strategy. */
// MINDIST(2);
//
// private final int index;
//
// /**
// * Constructor.
// *
// * @param index The strategy index.
// */
// NumerosityReductionStrategy(int index) {
// this.index = index;
// }
//
// /**
// * Gets the integer index of the instance.
// *
// * @return integer key of the instance.
// */
// public int index() {
// return index;
// }
//
// /**
// * Makes a strategy out of integer. 0 stands for NONE, 1 for EXACT, and 3 for MINDIST.
// *
// * @param value the key value.
// * @return the new Strategy instance.
// */
// public static NumerosityReductionStrategy fromValue(int value) {
// switch (value) {
// case 0:
// return NumerosityReductionStrategy.NONE;
// case 1:
// return NumerosityReductionStrategy.EXACT;
// case 2:
// return NumerosityReductionStrategy.MINDIST;
// default:
// throw new RuntimeException("Unknown index:" + value);
// }
// }
//
// /**
// * {@inheritDoc}
// */
// public String toString() {
// switch (this.index) {
// case 0:
// return "NONE";
// case 1:
// return "EXACT";
// case 2:
// return "MINDIST";
// default:
// throw new RuntimeException("Unknown index:" + this.index);
// }
// }
//
// /**
// * Parse the string value into an instance.
// *
// * @param value the string value.
// * @return new instance.
// */
// public static NumerosityReductionStrategy fromString(String value) {
// if ("none".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.NONE;
// }
// else if ("exact".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.EXACT;
// }
// else if ("mindist".equalsIgnoreCase(value)) {
// return NumerosityReductionStrategy.MINDIST;
// }
// else {
// throw new RuntimeException("Unknown index:" + value);
// }
// }
// }
// Path: src/main/java/net/seninp/jmotif/sax/bitmap/BitmapParameters.java
import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.Parameter;
import net.seninp.jmotif.sax.NumerosityReductionStrategy;
package net.seninp.jmotif.sax.bitmap;
/**
* Parameters accepted by the bitmap printer and their default values.
*
* @author psenin
*
*/
public class BitmapParameters {
// general setup
//
@Parameter
public List<String> parameters = new ArrayList<String>();
@Parameter(names = "--verbose", description = "Level of verbosity")
public Integer verbose = 1;
@Parameter(names = { "--help", "-h" }, help = true)
public boolean help;
// dataset
//
@Parameter(names = { "--data_in", "-d" }, description = "The input file name")
public static String IN_FILE;
// output
//
@Parameter(names = { "--data_out", "-o" }, description = "The output file name")
public static String OUT_FILE = "shingling_out.txt";
@Parameter(names = { "--bitmap_out", "-b" }, description = "The bitmap output file name")
public static String BITMAP_FILE = "my-chart.png";
// discretization parameters
//
@Parameter(names = { "--window_size", "-w" }, description = "Sliding window size")
public static int SAX_WINDOW_SIZE = 30;
@Parameter(names = { "--word_size", "-p" }, description = "PAA word size")
public static int SAX_PAA_SIZE = 6;
@Parameter(names = { "--alphabet_size", "-a" }, description = "SAX alphabet size")
public static int SAX_ALPHABET_SIZE = 4;
@Parameter(names = "--strategy", description = "Numerosity reduction strategy") | public static NumerosityReductionStrategy SAX_NR_STRATEGY = NumerosityReductionStrategy.NONE; |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/alphabet/Alphabet.java | // Path: src/main/java/net/seninp/jmotif/sax/SAXException.java
// public class SAXException extends Exception {
//
// /** The default serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Thrown when some problem occurs.
// *
// * @param description The problem description.
// * @param error The previous error.
// */
// public SAXException(String description, Throwable error) {
// super(description, error);
// }
//
// /**
// * Thrown when some problem occurs.
// *
// * @param description The problem description.
// */
// public SAXException(String description) {
// super(description);
// }
//
// }
| import net.seninp.jmotif.sax.SAXException;
| package net.seninp.jmotif.sax.alphabet;
/**
* The Alphabet class template.
*
* @author Pavel Senin.
*
*/
public abstract class Alphabet {
/**
* get the max size of the alphabet.
*
* @return maximum size of the alphabet.
*/
public abstract Integer getMaxSize();
/**
* Get cut intervals corresponding to the alphabet size.
*
* @param size The alphabet size.
* @return cut intervals for the alphabet.
* @throws SAXException if error occurs.
*/
| // Path: src/main/java/net/seninp/jmotif/sax/SAXException.java
// public class SAXException extends Exception {
//
// /** The default serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Thrown when some problem occurs.
// *
// * @param description The problem description.
// * @param error The previous error.
// */
// public SAXException(String description, Throwable error) {
// super(description, error);
// }
//
// /**
// * Thrown when some problem occurs.
// *
// * @param description The problem description.
// */
// public SAXException(String description) {
// super(description);
// }
//
// }
// Path: src/main/java/net/seninp/jmotif/sax/alphabet/Alphabet.java
import net.seninp.jmotif.sax.SAXException;
package net.seninp.jmotif.sax.alphabet;
/**
* The Alphabet class template.
*
* @author Pavel Senin.
*
*/
public abstract class Alphabet {
/**
* get the max size of the alphabet.
*
* @return maximum size of the alphabet.
*/
public abstract Integer getMaxSize();
/**
* Get cut intervals corresponding to the alphabet size.
*
* @param size The alphabet size.
* @return cut intervals for the alphabet.
* @throws SAXException if error occurs.
*/
| public abstract double[] getCuts(Integer size) throws SAXException;
|
jMotif/SAX | src/test/java/net/seninp/jmotif/sax/TestSAXException.java | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
| import static org.junit.Assert.assertTrue;
import org.junit.Test;
import net.seninp.util.StackTrace; | package net.seninp.jmotif.sax;
/**
* Tests the Stack Trace class.
*
* @author Philip Johnson
*/
public class TestSAXException {
/**
* Tests the Exception thrown. Generates an exception, makes the Stack Trace, and checks to see if
* it seems OK.
*/
@Test
public void testStackTrace() {
String trace;
try {
throw new SAXException("Test Exception");
}
catch (Exception e) { | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
// Path: src/test/java/net/seninp/jmotif/sax/TestSAXException.java
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import net.seninp.util.StackTrace;
package net.seninp.jmotif.sax;
/**
* Tests the Stack Trace class.
*
* @author Philip Johnson
*/
public class TestSAXException {
/**
* Tests the Exception thrown. Generates an exception, makes the Stack Trace, and checks to see if
* it seems OK.
*/
@Test
public void testStackTrace() {
String trace;
try {
throw new SAXException("Test Exception");
}
catch (Exception e) { | trace = StackTrace.toString(e); |
jMotif/SAX | src/test/java/net/seninp/jmotif/util/TestStackTrace.java | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
| import static org.junit.Assert.assertTrue;
import org.junit.Test;
import net.seninp.util.StackTrace; | package net.seninp.jmotif.util;
/**
* Tests the Stack Trace class.
*
* @author Philip Johnson
*/
public class TestStackTrace {
/**
* Tests the Stack Tracing. Generates an exception, makes the Stack Trace, and checks to see if it
* seems OK.
*/
@Test
public void testStackTrace() {
String trace;
try {
throw new Exception("Test Exception");
}
catch (Exception e) { | // Path: src/main/java/net/seninp/util/StackTrace.java
// public final class StackTrace {
//
// /** Disable public constructor. */
// private StackTrace() {
// // do nothing
// }
//
// /**
// * Converts the Throwable.getStackTrace to a String representation for logging.
// *
// * @param throwable The Throwable exception.
// * @return A String containing the StackTrace.
// */
// public static String toString(Throwable throwable) {
// StringWriter stringWriter = new StringWriter();
// throwable.printStackTrace(new PrintWriter(stringWriter));
// return stringWriter.toString();
// }
// }
// Path: src/test/java/net/seninp/jmotif/util/TestStackTrace.java
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import net.seninp.util.StackTrace;
package net.seninp.jmotif.util;
/**
* Tests the Stack Trace class.
*
* @author Philip Johnson
*/
public class TestStackTrace {
/**
* Tests the Stack Tracing. Generates an exception, makes the Stack Trace, and checks to see if it
* seems OK.
*/
@Test
public void testStackTrace() {
String trace;
try {
throw new Exception("Test Exception");
}
catch (Exception e) { | trace = StackTrace.toString(e); |
jMotif/SAX | src/test/java/net/seninp/jmotif/sax/datastructures/TestMotifRecord.java | // Path: src/main/java/net/seninp/jmotif/sax/motif/MotifRecord.java
// public class MotifRecord {
//
// private int location;
// private TreeSet<Integer> occurrences;
//
// /**
// * Constructor.
// *
// * @param motifLiocation the motif location.
// * @param motifOccurrences occurrence locations.
// */
// public MotifRecord(int motifLiocation, ArrayList<Integer> motifOccurrences) {
// this.location = motifLiocation;
// this.occurrences = new TreeSet<Integer>();
// this.occurrences.addAll(motifOccurrences);
// }
//
// /**
// * The location setter.
// *
// * @param location the motif location.
// */
// public void setLocation(int location) {
// this.location = location;
// }
//
// /**
// * The location getter.
// *
// * @return the motif location.
// */
// public int getLocation() {
// return location;
// }
//
// /**
// * Gets the occurrence frequency.
// *
// * @return the motif occurrence frequency (itself isnt included).
// */
// public int getFrequency() {
// return this.occurrences.size();
// }
//
// /**
// * The occurrences array (copy) getter.
// *
// * @return motif occurrences.
// */
// public ArrayList<Integer> getOccurrences() {
// ArrayList<Integer> res = new ArrayList<Integer>(this.occurrences.size());
// for (Integer e : this.occurrences) {
// res.add(e);
// }
// return res;
// }
//
// /**
// * The location setter.
// *
// * @param newLocation the motif location.
// */
// public void add(int newLocation) {
// if (!this.occurrences.contains(newLocation)) {
// this.occurrences.add(newLocation);
// }
// }
//
// @Override
// public String toString() {
// return "MotifRecord [location=" + this.location + ", freq=" + this.occurrences.size()
// + ", occurrences=" + occurrences + "]";
// }
//
// public boolean isEmpty() {
// return occurrences.isEmpty();
// }
//
// }
| import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import org.junit.Test;
import net.seninp.jmotif.sax.motif.MotifRecord; | package net.seninp.jmotif.sax.datastructures;
public class TestMotifRecord {
@Test
public void testMotifRecord() { | // Path: src/main/java/net/seninp/jmotif/sax/motif/MotifRecord.java
// public class MotifRecord {
//
// private int location;
// private TreeSet<Integer> occurrences;
//
// /**
// * Constructor.
// *
// * @param motifLiocation the motif location.
// * @param motifOccurrences occurrence locations.
// */
// public MotifRecord(int motifLiocation, ArrayList<Integer> motifOccurrences) {
// this.location = motifLiocation;
// this.occurrences = new TreeSet<Integer>();
// this.occurrences.addAll(motifOccurrences);
// }
//
// /**
// * The location setter.
// *
// * @param location the motif location.
// */
// public void setLocation(int location) {
// this.location = location;
// }
//
// /**
// * The location getter.
// *
// * @return the motif location.
// */
// public int getLocation() {
// return location;
// }
//
// /**
// * Gets the occurrence frequency.
// *
// * @return the motif occurrence frequency (itself isnt included).
// */
// public int getFrequency() {
// return this.occurrences.size();
// }
//
// /**
// * The occurrences array (copy) getter.
// *
// * @return motif occurrences.
// */
// public ArrayList<Integer> getOccurrences() {
// ArrayList<Integer> res = new ArrayList<Integer>(this.occurrences.size());
// for (Integer e : this.occurrences) {
// res.add(e);
// }
// return res;
// }
//
// /**
// * The location setter.
// *
// * @param newLocation the motif location.
// */
// public void add(int newLocation) {
// if (!this.occurrences.contains(newLocation)) {
// this.occurrences.add(newLocation);
// }
// }
//
// @Override
// public String toString() {
// return "MotifRecord [location=" + this.location + ", freq=" + this.occurrences.size()
// + ", occurrences=" + occurrences + "]";
// }
//
// public boolean isEmpty() {
// return occurrences.isEmpty();
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/sax/datastructures/TestMotifRecord.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import org.junit.Test;
import net.seninp.jmotif.sax.motif.MotifRecord;
package net.seninp.jmotif.sax.datastructures;
public class TestMotifRecord {
@Test
public void testMotifRecord() { | MotifRecord mr = new MotifRecord(1, new ArrayList<Integer>()); |
jMotif/SAX | src/test/java/net/seninp/jmotif/sax/datastructures/TestSAXRecord.java | // Path: src/main/java/net/seninp/jmotif/sax/datastructure/SAXRecord.java
// public class SAXRecord implements Comparable<SAXRecord> {
//
// /** The payload. */
// private char[] saxString;
//
// /** The index of occurrences in the raw sequence. */
// private HashSet<Integer> occurrences;
//
// /** Disable the constructor. */
// @SuppressWarnings("unused")
// private SAXRecord() {
// super();
// }
//
// /**
// * The allowed constructor.
// *
// * @param str the payload value.
// * @param idx the occurrence index.
// */
// public SAXRecord(char[] str, int idx) {
// super();
// this.saxString = str.clone();
// this.occurrences = new HashSet<Integer>();
// this.addIndex(idx);
// }
//
// /**
// * Adds an index.
// *
// * @param idx The index to add.
// */
// public void addIndex(int idx) {
// // if (!(this.occurrences.contains(idx))) {
// this.occurrences.add(idx);
// // }
// }
//
// /**
// * Removes a single index.
// *
// * @param idx The index to remove.
// */
// public void removeIndex(Integer idx) {
// this.occurrences.remove(idx);
// }
//
// /**
// * Gets the payload of the structure.
// *
// * @return The string.
// */
// public char[] getPayload() {
// return this.saxString;
// }
//
// /**
// * Get all indexes.
// *
// * @return all indexes.
// */
// public Set<Integer> getIndexes() {
// return this.occurrences;
// }
//
// /**
// * This comparator compares entries by the length of the entries array - i.e. by the total
// * frequency of entry occurrence.
// *
// * @param o an entry to compare with.
// * @return results of comparison.
// */
// @Override
// public int compareTo(SAXRecord o) {
// int a = this.occurrences.size();
// int b = o.getIndexes().size();
// if (a == b) {
// return 0;
// }
// else if (a > b) {
// return 1;
// }
// return -1;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object o) {
// if (o instanceof SAXRecord) {
// SAXRecord other = (SAXRecord) o;
// if (Arrays.equals(other.getPayload(), this.saxString)
// && (other.getIndexes().size() == this.occurrences.size())) {
// for (Integer e : this.occurrences) {
// if (!other.getIndexes().contains(e)) {
// return false;
// }
// }
// return true;
// }
// }
// return false;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// int hash = 7;
// int num0 = 0;
// if (null == this.saxString || 0 == this.saxString.length) {
// num0 = 32;
// }
// else {
// for (int i = 0; i < this.saxString.length; i++) {
// num0 = num0 + Character.getNumericValue(this.saxString[i]);
// }
// }
//
// int num1 = 0;
// if (this.occurrences.isEmpty()) {
// num1 = 17;
// }
// else {
// for (Integer i : this.occurrences) {
// num1 = num1 + i;
// }
// }
//
// hash = num0 + hash * num1;
// return hash;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.saxString).append(" -> ").append(occurrences.toString());
// return sb.toString();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.junit.Test;
import net.seninp.jmotif.sax.datastructure.SAXRecord;
| package net.seninp.jmotif.sax.datastructures;
/**
* Test data structures used in the SAX implementation.
*
* @author Pavel Senin.
*
*/
public class TestSAXRecord {
private static final Integer iNum1 = 7;
private static final Integer iNum2 = 3;
private static final String str11 = "abggfecbb";
private static final String str1 = "aaabbaa";
private static final String str2 = "aaabbba";
private static final Integer ONE = 1;
private static final Integer ZERO = 0;
/**
* Test the SAX frequency structure.
*/
@Test
public void testSAXFrequencyEntry() {
| // Path: src/main/java/net/seninp/jmotif/sax/datastructure/SAXRecord.java
// public class SAXRecord implements Comparable<SAXRecord> {
//
// /** The payload. */
// private char[] saxString;
//
// /** The index of occurrences in the raw sequence. */
// private HashSet<Integer> occurrences;
//
// /** Disable the constructor. */
// @SuppressWarnings("unused")
// private SAXRecord() {
// super();
// }
//
// /**
// * The allowed constructor.
// *
// * @param str the payload value.
// * @param idx the occurrence index.
// */
// public SAXRecord(char[] str, int idx) {
// super();
// this.saxString = str.clone();
// this.occurrences = new HashSet<Integer>();
// this.addIndex(idx);
// }
//
// /**
// * Adds an index.
// *
// * @param idx The index to add.
// */
// public void addIndex(int idx) {
// // if (!(this.occurrences.contains(idx))) {
// this.occurrences.add(idx);
// // }
// }
//
// /**
// * Removes a single index.
// *
// * @param idx The index to remove.
// */
// public void removeIndex(Integer idx) {
// this.occurrences.remove(idx);
// }
//
// /**
// * Gets the payload of the structure.
// *
// * @return The string.
// */
// public char[] getPayload() {
// return this.saxString;
// }
//
// /**
// * Get all indexes.
// *
// * @return all indexes.
// */
// public Set<Integer> getIndexes() {
// return this.occurrences;
// }
//
// /**
// * This comparator compares entries by the length of the entries array - i.e. by the total
// * frequency of entry occurrence.
// *
// * @param o an entry to compare with.
// * @return results of comparison.
// */
// @Override
// public int compareTo(SAXRecord o) {
// int a = this.occurrences.size();
// int b = o.getIndexes().size();
// if (a == b) {
// return 0;
// }
// else if (a > b) {
// return 1;
// }
// return -1;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object o) {
// if (o instanceof SAXRecord) {
// SAXRecord other = (SAXRecord) o;
// if (Arrays.equals(other.getPayload(), this.saxString)
// && (other.getIndexes().size() == this.occurrences.size())) {
// for (Integer e : this.occurrences) {
// if (!other.getIndexes().contains(e)) {
// return false;
// }
// }
// return true;
// }
// }
// return false;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// int hash = 7;
// int num0 = 0;
// if (null == this.saxString || 0 == this.saxString.length) {
// num0 = 32;
// }
// else {
// for (int i = 0; i < this.saxString.length; i++) {
// num0 = num0 + Character.getNumericValue(this.saxString[i]);
// }
// }
//
// int num1 = 0;
// if (this.occurrences.isEmpty()) {
// num1 = 17;
// }
// else {
// for (Integer i : this.occurrences) {
// num1 = num1 + i;
// }
// }
//
// hash = num0 + hash * num1;
// return hash;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.saxString).append(" -> ").append(occurrences.toString());
// return sb.toString();
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/sax/datastructures/TestSAXRecord.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.junit.Test;
import net.seninp.jmotif.sax.datastructure.SAXRecord;
package net.seninp.jmotif.sax.datastructures;
/**
* Test data structures used in the SAX implementation.
*
* @author Pavel Senin.
*
*/
public class TestSAXRecord {
private static final Integer iNum1 = 7;
private static final Integer iNum2 = 3;
private static final String str11 = "abggfecbb";
private static final String str1 = "aaabbaa";
private static final String str2 = "aaabbba";
private static final Integer ONE = 1;
private static final Integer ZERO = 0;
/**
* Test the SAX frequency structure.
*/
@Test
public void testSAXFrequencyEntry() {
| SAXRecord se = new SAXRecord(str11.toCharArray(), iNum2);
|
jMotif/SAX | src/test/java/net/seninp/jmotif/util/TestUCRUtils.java | // Path: src/main/java/net/seninp/util/UCRUtils.java
// public class UCRUtils {
//
// private static final String CR = "\n";
//
// /**
// * Reads bunch of series from file. First column treats as a class label. Rest as a real-valued
// * series.
// *
// * @param fileName the input filename.
// * @return time series read.
// * @throws IOException if error occurs.
// * @throws NumberFormatException if error occurs.
// */
// public static Map<String, List<double[]>> readUCRData(String fileName)
// throws IOException, NumberFormatException {
//
// Map<String, List<double[]>> res = new HashMap<String, List<double[]>>();
//
// BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
// String line = "";
// while ((line = br.readLine()) != null) {
// if (line.trim().length() == 0) {
// continue;
// }
// String[] split = line.trim().split("[\\,\\s]+");
//
// String label = split[0];
// Double num = parseValue(label);
// String seriesType = label;
// if (!(Double.isNaN(num))) {
// seriesType = String.valueOf(num.intValue());
// }
// double[] series = new double[split.length - 1];
// for (int i = 1; i < split.length; i++) {
// series[i - 1] = Double.valueOf(split[i].trim()).doubleValue();
// }
//
// if (!res.containsKey(seriesType)) {
// res.put(seriesType, new ArrayList<double[]>());
// }
//
// res.get(seriesType).add(series);
// }
//
// br.close();
// return res;
//
// }
//
// /**
// * Prints the dataset statistics.
// *
// * @param data the UCRdataset.
// * @param name the dataset name to use.
// * @return stats.
// */
// public static String datasetStats(Map<String, List<double[]>> data, String name) {
//
// int globalMinLength = Integer.MAX_VALUE;
// int globalMaxLength = Integer.MIN_VALUE;
//
// double globalMinValue = Double.MAX_VALUE;
// double globalMaxValue = Double.MIN_VALUE;
//
// for (Entry<String, List<double[]>> e : data.entrySet()) {
// for (double[] dataEntry : e.getValue()) {
//
// globalMaxLength = (dataEntry.length > globalMaxLength) ? dataEntry.length : globalMaxLength;
// globalMinLength = (dataEntry.length < globalMinLength) ? dataEntry.length : globalMinLength;
//
// for (double value : dataEntry) {
// globalMaxValue = (value > globalMaxValue) ? value : globalMaxValue;
// globalMinValue = (value < globalMinValue) ? value : globalMinValue;
// }
//
// }
// }
// StringBuffer sb = new StringBuffer();
//
// sb.append(name).append("classes: ").append(data.size());
// sb.append(", series length min: ").append(globalMinLength);
// sb.append(", max: ").append(globalMaxLength);
// sb.append(", min value: ").append(globalMinValue);
// sb.append(", max value: ").append(globalMaxValue).append(";");
// for (Entry<String, List<double[]>> e : data.entrySet()) {
// sb.append(name).append(" class: ").append(e.getKey());
// sb.append(" series: ").append(e.getValue().size()).append(";");
// }
//
// return sb.delete(sb.length() - 1, sb.length()).toString();
// }
//
// private static Double parseValue(String string) {
// Double res = Double.NaN;
// try {
// Double r = Double.valueOf(string);
// res = r;
// }
// catch (NumberFormatException e) {
// assert true;
// }
// return res;
// }
//
// /**
// * Saves the dataset.
// *
// * @param data the dataset.
// * @param file the file handler.
// * @throws IOException if error occurs.
// */
// public static void saveData(Map<String, List<double[]>> data, File file) throws IOException {
//
// BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//
// for (Entry<String, List<double[]>> classEntry : data.entrySet()) {
// String classLabel = classEntry.getKey();
// for (double[] arr : classEntry.getValue()) {
// String arrStr = Arrays.toString(arr).replaceAll("[\\]\\[\\s]+", "");
// bw.write(classLabel + "," + arrStr + CR);
// }
// }
//
// bw.close();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import net.seninp.util.UCRUtils; | package net.seninp.jmotif.util;
public class TestUCRUtils {
private static final String CBF_GOOD_FNAME = "src//resources//dataset/test_dataset_good.txt";
private static final String CBF_BAD_FNAME = "src//resources//dataset/test_dataset_bad.txt";
@Test
public void testReadUCRData() {
try {
| // Path: src/main/java/net/seninp/util/UCRUtils.java
// public class UCRUtils {
//
// private static final String CR = "\n";
//
// /**
// * Reads bunch of series from file. First column treats as a class label. Rest as a real-valued
// * series.
// *
// * @param fileName the input filename.
// * @return time series read.
// * @throws IOException if error occurs.
// * @throws NumberFormatException if error occurs.
// */
// public static Map<String, List<double[]>> readUCRData(String fileName)
// throws IOException, NumberFormatException {
//
// Map<String, List<double[]>> res = new HashMap<String, List<double[]>>();
//
// BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
// String line = "";
// while ((line = br.readLine()) != null) {
// if (line.trim().length() == 0) {
// continue;
// }
// String[] split = line.trim().split("[\\,\\s]+");
//
// String label = split[0];
// Double num = parseValue(label);
// String seriesType = label;
// if (!(Double.isNaN(num))) {
// seriesType = String.valueOf(num.intValue());
// }
// double[] series = new double[split.length - 1];
// for (int i = 1; i < split.length; i++) {
// series[i - 1] = Double.valueOf(split[i].trim()).doubleValue();
// }
//
// if (!res.containsKey(seriesType)) {
// res.put(seriesType, new ArrayList<double[]>());
// }
//
// res.get(seriesType).add(series);
// }
//
// br.close();
// return res;
//
// }
//
// /**
// * Prints the dataset statistics.
// *
// * @param data the UCRdataset.
// * @param name the dataset name to use.
// * @return stats.
// */
// public static String datasetStats(Map<String, List<double[]>> data, String name) {
//
// int globalMinLength = Integer.MAX_VALUE;
// int globalMaxLength = Integer.MIN_VALUE;
//
// double globalMinValue = Double.MAX_VALUE;
// double globalMaxValue = Double.MIN_VALUE;
//
// for (Entry<String, List<double[]>> e : data.entrySet()) {
// for (double[] dataEntry : e.getValue()) {
//
// globalMaxLength = (dataEntry.length > globalMaxLength) ? dataEntry.length : globalMaxLength;
// globalMinLength = (dataEntry.length < globalMinLength) ? dataEntry.length : globalMinLength;
//
// for (double value : dataEntry) {
// globalMaxValue = (value > globalMaxValue) ? value : globalMaxValue;
// globalMinValue = (value < globalMinValue) ? value : globalMinValue;
// }
//
// }
// }
// StringBuffer sb = new StringBuffer();
//
// sb.append(name).append("classes: ").append(data.size());
// sb.append(", series length min: ").append(globalMinLength);
// sb.append(", max: ").append(globalMaxLength);
// sb.append(", min value: ").append(globalMinValue);
// sb.append(", max value: ").append(globalMaxValue).append(";");
// for (Entry<String, List<double[]>> e : data.entrySet()) {
// sb.append(name).append(" class: ").append(e.getKey());
// sb.append(" series: ").append(e.getValue().size()).append(";");
// }
//
// return sb.delete(sb.length() - 1, sb.length()).toString();
// }
//
// private static Double parseValue(String string) {
// Double res = Double.NaN;
// try {
// Double r = Double.valueOf(string);
// res = r;
// }
// catch (NumberFormatException e) {
// assert true;
// }
// return res;
// }
//
// /**
// * Saves the dataset.
// *
// * @param data the dataset.
// * @param file the file handler.
// * @throws IOException if error occurs.
// */
// public static void saveData(Map<String, List<double[]>> data, File file) throws IOException {
//
// BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//
// for (Entry<String, List<double[]>> classEntry : data.entrySet()) {
// String classLabel = classEntry.getKey();
// for (double[] arr : classEntry.getValue()) {
// String arrStr = Arrays.toString(arr).replaceAll("[\\]\\[\\s]+", "");
// bw.write(classLabel + "," + arrStr + CR);
// }
// }
//
// bw.close();
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/util/TestUCRUtils.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import net.seninp.util.UCRUtils;
package net.seninp.jmotif.util;
public class TestUCRUtils {
private static final String CBF_GOOD_FNAME = "src//resources//dataset/test_dataset_good.txt";
private static final String CBF_BAD_FNAME = "src//resources//dataset/test_dataset_bad.txt";
@Test
public void testReadUCRData() {
try {
| Map<String, List<double[]>> data = UCRUtils.readUCRData(CBF_GOOD_FNAME); |
jMotif/SAX | src/test/java/net/seninp/jmotif/util/TestMapEntry.java | // Path: src/main/java/net/seninp/util/JmotifMapEntry.java
// public class JmotifMapEntry<K, V> implements Map.Entry<K, V> {
// private final K key;
// private V value;
//
// public JmotifMapEntry(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public K getKey() {
// return key;
// }
//
// @Override
// public V getValue() {
// return value;
// }
//
// @Override
// public V setValue(V value) {
// V old = this.value;
// this.value = value;
// return old;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((key == null) ? 0 : key.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// @SuppressWarnings("rawtypes")
// JmotifMapEntry other = (JmotifMapEntry) obj;
// if (key == null) {
// if (other.key != null)
// return false;
// }
// else if (!key.equals(other.key))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// }
// else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "JmotifMapEntry [key=" + key + ", value=" + value + "]";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import net.seninp.util.JmotifMapEntry; | package net.seninp.jmotif.util;
public class TestMapEntry {
private static final String KEY1 = "key1";
private static final String KEY2 = "key2";
private static final Integer KEY3 = 75;
private static final String VALUE1 = "value1";
private static final String VALUE2 = "value2";
private static final Double VALUE3 = Double.valueOf(12.77d);
| // Path: src/main/java/net/seninp/util/JmotifMapEntry.java
// public class JmotifMapEntry<K, V> implements Map.Entry<K, V> {
// private final K key;
// private V value;
//
// public JmotifMapEntry(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public K getKey() {
// return key;
// }
//
// @Override
// public V getValue() {
// return value;
// }
//
// @Override
// public V setValue(V value) {
// V old = this.value;
// this.value = value;
// return old;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((key == null) ? 0 : key.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// @SuppressWarnings("rawtypes")
// JmotifMapEntry other = (JmotifMapEntry) obj;
// if (key == null) {
// if (other.key != null)
// return false;
// }
// else if (!key.equals(other.key))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// }
// else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// return "JmotifMapEntry [key=" + key + ", value=" + value + "]";
// }
//
// }
// Path: src/test/java/net/seninp/jmotif/util/TestMapEntry.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import net.seninp.util.JmotifMapEntry;
package net.seninp.jmotif.util;
public class TestMapEntry {
private static final String KEY1 = "key1";
private static final String KEY2 = "key2";
private static final Integer KEY3 = 75;
private static final String VALUE1 = "value1";
private static final String VALUE2 = "value2";
private static final Double VALUE3 = Double.valueOf(12.77d);
| private JmotifMapEntry<String, String> e1; |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/set/Settings.java | // Path: sft-core/src/test/java/sft/integration/fixtures/JavaResource.java
// public class JavaResource extends SftResource {
//
// private final HtmlResources htmlResources = new HtmlResources();
// private final SftDocumentationConfiguration configuration;
//
// public JavaResource(Class javaClass) {
// super(javaClass, ".java.html");
// configuration = new SftDocumentationConfiguration();
// createJavaHtml();
// }
//
// private static void copy(Reader input, Writer output) throws IOException {
// String read = getStringBuffer(input);
// while (read != null) {
// output.write(read.replace("<", "<").replace(">", ">"));
// read = getStringBuffer(input);
// }
// }
//
// private static String getStringBuffer(Reader input) throws IOException {
// char[] buffer = new char[1024];
// int bufferSize = input.read(buffer);
// if (-1 == bufferSize) {
// return null;
// } else {
// return new String(buffer, 0, bufferSize);
// }
// }
//
// private void createJavaHtml() {
// try {
// File htmlJavaFile = configuration.getReport(HtmlReport.class).getReportFolder().createFileFromClass(targetClass, extension);
//
// Writer html = new OutputStreamWriter(new FileOutputStream(htmlJavaFile));
// html.write("<html><head><title>\n");
// html.write(targetClass.getCanonicalName() + "\n");
// html.write("</title>\n");
// html.write(htmlResources.getIncludeCssDirectives(targetClass));
// html.write("</head>\n");
// html.write("<body><div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Source file</h3></div><div class='panel-body'><pre>\n");
//
// File javaFile = configuration.getSourceFolder().getFileFromClass(targetClass, ".java");
//
// InputStream javaIn = new FileInputStream(javaFile);
// Reader reader = new InputStreamReader(javaIn, "UTF-8");
// copy(reader, html);
//
// html.write("</pre></div></div></body></html>");
// html.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.DefaultConfiguration;
import sft.Displayable;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.UseCase;
import sft.decorators.Breadcrumb;
import sft.decorators.Group;
import sft.integration.fixtures.JavaResource;
import sft.integration.set.sut.CommonUseCase;
import sft.integration.set.sut.CustomConfiguration;
import sft.integration.set.sut.UseCaseWithSpecificConfiguration;
import sft.report.HtmlResources; | package sft.integration.set;
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
public class Settings {
private static final String AVAILABLE_SETTINGS = "Available settings";
@Displayable
private String files;
private UseCase useCase;
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public HtmlReportSettings htmlReportSettings = new HtmlReportSettings();
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public SourceAndClassSettings sourceAndClassSettings = new SourceAndClassSettings();
@Test
public void configurationMechanism() throws Exception {
allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration();
toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor();
thenYouCanInjectConfigurationByAnnotatedUseCaseJavaClassWithUsingCustomConfiguration();
allRelatedUseCasesWillUseThisConfiguration();
}
private void allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration() throws Exception { | // Path: sft-core/src/test/java/sft/integration/fixtures/JavaResource.java
// public class JavaResource extends SftResource {
//
// private final HtmlResources htmlResources = new HtmlResources();
// private final SftDocumentationConfiguration configuration;
//
// public JavaResource(Class javaClass) {
// super(javaClass, ".java.html");
// configuration = new SftDocumentationConfiguration();
// createJavaHtml();
// }
//
// private static void copy(Reader input, Writer output) throws IOException {
// String read = getStringBuffer(input);
// while (read != null) {
// output.write(read.replace("<", "<").replace(">", ">"));
// read = getStringBuffer(input);
// }
// }
//
// private static String getStringBuffer(Reader input) throws IOException {
// char[] buffer = new char[1024];
// int bufferSize = input.read(buffer);
// if (-1 == bufferSize) {
// return null;
// } else {
// return new String(buffer, 0, bufferSize);
// }
// }
//
// private void createJavaHtml() {
// try {
// File htmlJavaFile = configuration.getReport(HtmlReport.class).getReportFolder().createFileFromClass(targetClass, extension);
//
// Writer html = new OutputStreamWriter(new FileOutputStream(htmlJavaFile));
// html.write("<html><head><title>\n");
// html.write(targetClass.getCanonicalName() + "\n");
// html.write("</title>\n");
// html.write(htmlResources.getIncludeCssDirectives(targetClass));
// html.write("</head>\n");
// html.write("<body><div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Source file</h3></div><div class='panel-body'><pre>\n");
//
// File javaFile = configuration.getSourceFolder().getFileFromClass(targetClass, ".java");
//
// InputStream javaIn = new FileInputStream(javaFile);
// Reader reader = new InputStreamReader(javaIn, "UTF-8");
// copy(reader, html);
//
// html.write("</pre></div></div></body></html>");
// html.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
// Path: sft-core/src/test/java/sft/integration/set/Settings.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.DefaultConfiguration;
import sft.Displayable;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.UseCase;
import sft.decorators.Breadcrumb;
import sft.decorators.Group;
import sft.integration.fixtures.JavaResource;
import sft.integration.set.sut.CommonUseCase;
import sft.integration.set.sut.CustomConfiguration;
import sft.integration.set.sut.UseCaseWithSpecificConfiguration;
import sft.report.HtmlResources;
package sft.integration.set;
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
public class Settings {
private static final String AVAILABLE_SETTINGS = "Available settings";
@Displayable
private String files;
private UseCase useCase;
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public HtmlReportSettings htmlReportSettings = new HtmlReportSettings();
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public SourceAndClassSettings sourceAndClassSettings = new SourceAndClassSettings();
@Test
public void configurationMechanism() throws Exception {
allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration();
toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor();
thenYouCanInjectConfigurationByAnnotatedUseCaseJavaClassWithUsingCustomConfiguration();
allRelatedUseCasesWillUseThisConfiguration();
}
private void allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration() throws Exception { | useCase = new UseCase(CommonUseCase.class); |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/set/Settings.java | // Path: sft-core/src/test/java/sft/integration/fixtures/JavaResource.java
// public class JavaResource extends SftResource {
//
// private final HtmlResources htmlResources = new HtmlResources();
// private final SftDocumentationConfiguration configuration;
//
// public JavaResource(Class javaClass) {
// super(javaClass, ".java.html");
// configuration = new SftDocumentationConfiguration();
// createJavaHtml();
// }
//
// private static void copy(Reader input, Writer output) throws IOException {
// String read = getStringBuffer(input);
// while (read != null) {
// output.write(read.replace("<", "<").replace(">", ">"));
// read = getStringBuffer(input);
// }
// }
//
// private static String getStringBuffer(Reader input) throws IOException {
// char[] buffer = new char[1024];
// int bufferSize = input.read(buffer);
// if (-1 == bufferSize) {
// return null;
// } else {
// return new String(buffer, 0, bufferSize);
// }
// }
//
// private void createJavaHtml() {
// try {
// File htmlJavaFile = configuration.getReport(HtmlReport.class).getReportFolder().createFileFromClass(targetClass, extension);
//
// Writer html = new OutputStreamWriter(new FileOutputStream(htmlJavaFile));
// html.write("<html><head><title>\n");
// html.write(targetClass.getCanonicalName() + "\n");
// html.write("</title>\n");
// html.write(htmlResources.getIncludeCssDirectives(targetClass));
// html.write("</head>\n");
// html.write("<body><div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Source file</h3></div><div class='panel-body'><pre>\n");
//
// File javaFile = configuration.getSourceFolder().getFileFromClass(targetClass, ".java");
//
// InputStream javaIn = new FileInputStream(javaFile);
// Reader reader = new InputStreamReader(javaIn, "UTF-8");
// copy(reader, html);
//
// html.write("</pre></div></div></body></html>");
// html.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.DefaultConfiguration;
import sft.Displayable;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.UseCase;
import sft.decorators.Breadcrumb;
import sft.decorators.Group;
import sft.integration.fixtures.JavaResource;
import sft.integration.set.sut.CommonUseCase;
import sft.integration.set.sut.CustomConfiguration;
import sft.integration.set.sut.UseCaseWithSpecificConfiguration;
import sft.report.HtmlResources; | package sft.integration.set;
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
public class Settings {
private static final String AVAILABLE_SETTINGS = "Available settings";
@Displayable
private String files;
private UseCase useCase;
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public HtmlReportSettings htmlReportSettings = new HtmlReportSettings();
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public SourceAndClassSettings sourceAndClassSettings = new SourceAndClassSettings();
@Test
public void configurationMechanism() throws Exception {
allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration();
toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor();
thenYouCanInjectConfigurationByAnnotatedUseCaseJavaClassWithUsingCustomConfiguration();
allRelatedUseCasesWillUseThisConfiguration();
}
private void allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration() throws Exception {
useCase = new UseCase(CommonUseCase.class);
Assert.assertEquals(DefaultConfiguration.class, useCase.configuration.getClass());
Assert.assertEquals(DefaultConfiguration.class, useCase.subUseCases.get(0).subUseCase.configuration.getClass());
Assert.assertEquals(DefaultConfiguration.class, useCase.subUseCases.get(1).subUseCase.configuration.getClass());
}
@Text("To modify settings you have to create an inherited class from DefaultConfiguration and change setting in the constructor")
private void toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor() throws Exception {
new HtmlResources().ensureIsCreated();
files = "<div class=\"resources\">" + | // Path: sft-core/src/test/java/sft/integration/fixtures/JavaResource.java
// public class JavaResource extends SftResource {
//
// private final HtmlResources htmlResources = new HtmlResources();
// private final SftDocumentationConfiguration configuration;
//
// public JavaResource(Class javaClass) {
// super(javaClass, ".java.html");
// configuration = new SftDocumentationConfiguration();
// createJavaHtml();
// }
//
// private static void copy(Reader input, Writer output) throws IOException {
// String read = getStringBuffer(input);
// while (read != null) {
// output.write(read.replace("<", "<").replace(">", ">"));
// read = getStringBuffer(input);
// }
// }
//
// private static String getStringBuffer(Reader input) throws IOException {
// char[] buffer = new char[1024];
// int bufferSize = input.read(buffer);
// if (-1 == bufferSize) {
// return null;
// } else {
// return new String(buffer, 0, bufferSize);
// }
// }
//
// private void createJavaHtml() {
// try {
// File htmlJavaFile = configuration.getReport(HtmlReport.class).getReportFolder().createFileFromClass(targetClass, extension);
//
// Writer html = new OutputStreamWriter(new FileOutputStream(htmlJavaFile));
// html.write("<html><head><title>\n");
// html.write(targetClass.getCanonicalName() + "\n");
// html.write("</title>\n");
// html.write(htmlResources.getIncludeCssDirectives(targetClass));
// html.write("</head>\n");
// html.write("<body><div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>Source file</h3></div><div class='panel-body'><pre>\n");
//
// File javaFile = configuration.getSourceFolder().getFileFromClass(targetClass, ".java");
//
// InputStream javaIn = new FileInputStream(javaFile);
// Reader reader = new InputStreamReader(javaIn, "UTF-8");
// copy(reader, html);
//
// html.write("</pre></div></div></body></html>");
// html.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
// Path: sft-core/src/test/java/sft/integration/set/Settings.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.DefaultConfiguration;
import sft.Displayable;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.UseCase;
import sft.decorators.Breadcrumb;
import sft.decorators.Group;
import sft.integration.fixtures.JavaResource;
import sft.integration.set.sut.CommonUseCase;
import sft.integration.set.sut.CustomConfiguration;
import sft.integration.set.sut.UseCaseWithSpecificConfiguration;
import sft.report.HtmlResources;
package sft.integration.set;
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
public class Settings {
private static final String AVAILABLE_SETTINGS = "Available settings";
@Displayable
private String files;
private UseCase useCase;
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public HtmlReportSettings htmlReportSettings = new HtmlReportSettings();
@Decorate(decorator = Group.class,parameters = AVAILABLE_SETTINGS)
public SourceAndClassSettings sourceAndClassSettings = new SourceAndClassSettings();
@Test
public void configurationMechanism() throws Exception {
allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration();
toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor();
thenYouCanInjectConfigurationByAnnotatedUseCaseJavaClassWithUsingCustomConfiguration();
allRelatedUseCasesWillUseThisConfiguration();
}
private void allSettingsOfAnUseCaseAreHoldByTheClassDefaultConfiguration() throws Exception {
useCase = new UseCase(CommonUseCase.class);
Assert.assertEquals(DefaultConfiguration.class, useCase.configuration.getClass());
Assert.assertEquals(DefaultConfiguration.class, useCase.subUseCases.get(0).subUseCase.configuration.getClass());
Assert.assertEquals(DefaultConfiguration.class, useCase.subUseCases.get(1).subUseCase.configuration.getClass());
}
@Text("To modify settings you have to create an inherited class from DefaultConfiguration and change setting in the constructor")
private void toModifySettingsYouHaveToCreateAnInheritedClassFromDefaultConfigurationAndChangeSettingInTheConstructor() throws Exception {
new HtmlResources().ensureIsCreated();
files = "<div class=\"resources\">" + | new JavaResource(CustomConfiguration.class).getOpenResourceHtmlLink(this.getClass(), "custom configuration", "alert-info") + |
slezier/SimpleFunctionalTest | sft-core/src/main/java/sft/report/HtmlReport.java | // Path: sft-core/src/main/java/sft/environment/TargetFolder.java
// public class TargetFolder extends ResourceFolder {
// public TargetFolder(String toProjectPath, String path) {
// super(toProjectPath, path);
// }
//
// public File createFileFromClass(Class<?> aClass, String extension) {
// String filePath = getFilePath(aClass, extension);
// makeDir(filePath);
// return getFile(filePath);
// }
//
// public List<String> copyFromResources(String fileName) throws IOException {
// try {
// final File targetDirectory = ensureTargetDirectoryExists();
// final URL resource = this .getClass().getClassLoader().getResource(fileName);
// final List<String> paths ;
// if( resource == null ){
// throw new RuntimeException("Can't find resource \""+fileName+ "\"; ensure this resource exists");
// }else if (resource.getProtocol().equals("jar")) {
// paths = new FromJar(resource).copy(targetDirectory);
// } else {
// paths = new FromDirectory(resource).copy(targetDirectory);
// }
// Collections.sort(paths);
// return paths;
// } catch (URISyntaxException e) {
// throw new RuntimeException(e);
// }
// }
//
// private void makeDir(String path) {
// File parentDirectory = ensureTargetDirectoryExists();
// for (String file : path.split("/")) {
// if (!file.contains(".")) {
// parentDirectory = new File(parentDirectory, file);
// if (!parentDirectory.exists()) {
// parentDirectory.mkdir();
// }
// }
// }
// }
//
// private File ensureTargetDirectoryExists() {
// final File targetDirectory = new File(getResourceFolder() + path);
// if (!targetDirectory.exists()) {
// targetDirectory.mkdir();
// }
// return targetDirectory;
// }
// }
| import sft.*;
import sft.decorators.*;
import sft.environment.TargetFolder;
import sft.report.decorators.*;
import sft.result.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; | public String contextInstructionTemplate =
" <div>\n" +
" <span>@@@instruction.text@@@</span>\n" +
" </div>\n";
public String relatedUseCasesTitleTemplate =
" <div class=\"panel-heading\">\n" +
" <h3>@@@relatedUseCasesTitle@@@</h3>\n" +
" </div>\n";
public String relatedUseCasesTemplate =
" <div class=\"panel panel-default relatedUseCases\">\n" +
"@@@relatedUseCasesTitleTemplates@@@" +
" <div class=\"panel-body\">\n" +
" <ul>\n" +
"@@@relatedUseCaseTemplates@@@" +
" </ul>\n" +
" </div>\n" +
" </div>\n";
public String relatedUseCaseTemplate =
" <li class=\"relatedUseCase @@@relatedUseCase.issue@@@\">\n" +
" <a href=\"@@@relatedUseCase.link@@@\"><span>@@@relatedUseCase.name@@@</span></a>\n" +
" </li>\n";
public String parameterTemplate = "<i class=\"value\">@@@parameter.value@@@</i>";
public String ignoredClass = "ignored";
public String failedClass = "failed";
public String successClass = "succeeded";
private HtmlResources htmlResources;
private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
| // Path: sft-core/src/main/java/sft/environment/TargetFolder.java
// public class TargetFolder extends ResourceFolder {
// public TargetFolder(String toProjectPath, String path) {
// super(toProjectPath, path);
// }
//
// public File createFileFromClass(Class<?> aClass, String extension) {
// String filePath = getFilePath(aClass, extension);
// makeDir(filePath);
// return getFile(filePath);
// }
//
// public List<String> copyFromResources(String fileName) throws IOException {
// try {
// final File targetDirectory = ensureTargetDirectoryExists();
// final URL resource = this .getClass().getClassLoader().getResource(fileName);
// final List<String> paths ;
// if( resource == null ){
// throw new RuntimeException("Can't find resource \""+fileName+ "\"; ensure this resource exists");
// }else if (resource.getProtocol().equals("jar")) {
// paths = new FromJar(resource).copy(targetDirectory);
// } else {
// paths = new FromDirectory(resource).copy(targetDirectory);
// }
// Collections.sort(paths);
// return paths;
// } catch (URISyntaxException e) {
// throw new RuntimeException(e);
// }
// }
//
// private void makeDir(String path) {
// File parentDirectory = ensureTargetDirectoryExists();
// for (String file : path.split("/")) {
// if (!file.contains(".")) {
// parentDirectory = new File(parentDirectory, file);
// if (!parentDirectory.exists()) {
// parentDirectory.mkdir();
// }
// }
// }
// }
//
// private File ensureTargetDirectoryExists() {
// final File targetDirectory = new File(getResourceFolder() + path);
// if (!targetDirectory.exists()) {
// targetDirectory.mkdir();
// }
// return targetDirectory;
// }
// }
// Path: sft-core/src/main/java/sft/report/HtmlReport.java
import sft.*;
import sft.decorators.*;
import sft.environment.TargetFolder;
import sft.report.decorators.*;
import sft.result.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
public String contextInstructionTemplate =
" <div>\n" +
" <span>@@@instruction.text@@@</span>\n" +
" </div>\n";
public String relatedUseCasesTitleTemplate =
" <div class=\"panel-heading\">\n" +
" <h3>@@@relatedUseCasesTitle@@@</h3>\n" +
" </div>\n";
public String relatedUseCasesTemplate =
" <div class=\"panel panel-default relatedUseCases\">\n" +
"@@@relatedUseCasesTitleTemplates@@@" +
" <div class=\"panel-body\">\n" +
" <ul>\n" +
"@@@relatedUseCaseTemplates@@@" +
" </ul>\n" +
" </div>\n" +
" </div>\n";
public String relatedUseCaseTemplate =
" <li class=\"relatedUseCase @@@relatedUseCase.issue@@@\">\n" +
" <a href=\"@@@relatedUseCase.link@@@\"><span>@@@relatedUseCase.name@@@</span></a>\n" +
" </li>\n";
public String parameterTemplate = "<i class=\"value\">@@@parameter.value@@@</i>";
public String ignoredClass = "ignored";
public String failedClass = "failed";
public String successClass = "succeeded";
private HtmlResources htmlResources;
private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
| private TargetFolder reportFolder; |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/use/UsingDecorator.java | // Path: sft-core/src/test/java/sft/integration/fixtures/SftResources.java
// public class SftResources {
//
// private final Class callerClass;
// private final JavaResource javaResource;
// private final SftResource htmlResource;
//
// public SftResources(Class callerClass, Class functionalTestClass) {
// this.callerClass = callerClass;
// javaResource = new JavaResource(functionalTestClass);
// htmlResource = new SftResource(functionalTestClass);
// }
//
// @Override
// public String toString() {
// return "<div class='resources'>" + javaResource.getOpenResourceHtmlLink(callerClass, "java", "alert-info") +
// htmlResource.getOpenResourceHtmlLink(callerClass, "html", "alert-info") + "</div>";
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/decorators/subUseCase/SubUseCaseBreadcrumb.java
// @Decorate(decorator = Breadcrumb.class)
// public class SubUseCaseBreadcrumb {
// @FixturesHelper
// private SftFixturesHelper sftFixturesHelper = new SftFixturesHelper();
//
// public SubSubUseCaseBreadcrumb subSubUseCaseBreadcrumb= new SubSubUseCaseBreadcrumb();
//
// @Test
// public void test(){
// sftFixturesHelper.doStuff();
// }
// }
| import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.Displayable;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.fixtures.SftResources;
import sft.integration.use.sut.decorators.*;
import sft.integration.use.sut.decorators.subUseCase.SubSubUseCaseBreadcrumb;
import sft.integration.use.sut.decorators.subUseCase.SubUseCaseBreadcrumb;
import java.io.IOException;
import java.util.ArrayList; | Assert.assertTrue("Expecting class " + style + " in body", jUnitHtmlHelper.html.select("body.useCase").hasClass(style));
}
@Text("Several style can be used together @Decorate(decorator = Style.class, parameters ={\"${style1}\",\"${style2}\",\"${style3}\"}) ")
private void severalStylesCanBeSpecified(String style1, String style2, String style3) throws Exception {
final Elements select = jUnitHtmlHelper.html.select("div.scenario");
Assert.assertTrue("Expecting class " + style1 + " in scenario div", select.hasClass(style1));
Assert.assertTrue("Expecting class " + style2 + " in scenario div", select.hasClass(style2));
Assert.assertTrue("Expecting class " + style3 + " in scenario div", select.hasClass(style3));
}
@Text("The style decorator can be apply on use case, scenario, fixture and sub use case")
private void theStyleDecoratorCanBeApplyOnUseCaseScenarioFixtureAndSubUseCase() throws Exception {
final Document htmlReport = jUnitHtmlHelper.html;
Assert.assertTrue("Expecting class style in body", htmlReport.select("body.useCase").hasClass("style"));
Assert.assertTrue("Expecting class style1 in scenario div", htmlReport.select("div.scenario").hasClass("style1"));
Assert.assertTrue("Expecting class style4 in instruction div", htmlReport.select("div.instruction").hasClass("style4"));
Assert.assertTrue("Expecting class style5 in relatedUseCase li", htmlReport.select("li.relatedUseCase").hasClass("style5"));
}
private void byAddingBreadcrumbDecoratorOnUseCase() throws Exception {
jUnitHtmlHelper.run(this.getClass(), BreadcrumbDecoratorSample.class);
displayableResources = new DisplayableResources("parent user story", jUnitHtmlHelper.displayResources);
}
private void aBreadcrumbsIsAddedAfterTitle() throws Exception {
Elements breadcrumbs = jUnitHtmlHelper.html.select("ol.breadcrumb");
Assert.assertEquals(1, breadcrumbs.select("li").size());
Assert.assertEquals("Breadcrumb decorator sample", breadcrumbs.select("li").get(0).text());
| // Path: sft-core/src/test/java/sft/integration/fixtures/SftResources.java
// public class SftResources {
//
// private final Class callerClass;
// private final JavaResource javaResource;
// private final SftResource htmlResource;
//
// public SftResources(Class callerClass, Class functionalTestClass) {
// this.callerClass = callerClass;
// javaResource = new JavaResource(functionalTestClass);
// htmlResource = new SftResource(functionalTestClass);
// }
//
// @Override
// public String toString() {
// return "<div class='resources'>" + javaResource.getOpenResourceHtmlLink(callerClass, "java", "alert-info") +
// htmlResource.getOpenResourceHtmlLink(callerClass, "html", "alert-info") + "</div>";
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/decorators/subUseCase/SubUseCaseBreadcrumb.java
// @Decorate(decorator = Breadcrumb.class)
// public class SubUseCaseBreadcrumb {
// @FixturesHelper
// private SftFixturesHelper sftFixturesHelper = new SftFixturesHelper();
//
// public SubSubUseCaseBreadcrumb subSubUseCaseBreadcrumb= new SubSubUseCaseBreadcrumb();
//
// @Test
// public void test(){
// sftFixturesHelper.doStuff();
// }
// }
// Path: sft-core/src/test/java/sft/integration/use/UsingDecorator.java
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.Displayable;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.fixtures.SftResources;
import sft.integration.use.sut.decorators.*;
import sft.integration.use.sut.decorators.subUseCase.SubSubUseCaseBreadcrumb;
import sft.integration.use.sut.decorators.subUseCase.SubUseCaseBreadcrumb;
import java.io.IOException;
import java.util.ArrayList;
Assert.assertTrue("Expecting class " + style + " in body", jUnitHtmlHelper.html.select("body.useCase").hasClass(style));
}
@Text("Several style can be used together @Decorate(decorator = Style.class, parameters ={\"${style1}\",\"${style2}\",\"${style3}\"}) ")
private void severalStylesCanBeSpecified(String style1, String style2, String style3) throws Exception {
final Elements select = jUnitHtmlHelper.html.select("div.scenario");
Assert.assertTrue("Expecting class " + style1 + " in scenario div", select.hasClass(style1));
Assert.assertTrue("Expecting class " + style2 + " in scenario div", select.hasClass(style2));
Assert.assertTrue("Expecting class " + style3 + " in scenario div", select.hasClass(style3));
}
@Text("The style decorator can be apply on use case, scenario, fixture and sub use case")
private void theStyleDecoratorCanBeApplyOnUseCaseScenarioFixtureAndSubUseCase() throws Exception {
final Document htmlReport = jUnitHtmlHelper.html;
Assert.assertTrue("Expecting class style in body", htmlReport.select("body.useCase").hasClass("style"));
Assert.assertTrue("Expecting class style1 in scenario div", htmlReport.select("div.scenario").hasClass("style1"));
Assert.assertTrue("Expecting class style4 in instruction div", htmlReport.select("div.instruction").hasClass("style4"));
Assert.assertTrue("Expecting class style5 in relatedUseCase li", htmlReport.select("li.relatedUseCase").hasClass("style5"));
}
private void byAddingBreadcrumbDecoratorOnUseCase() throws Exception {
jUnitHtmlHelper.run(this.getClass(), BreadcrumbDecoratorSample.class);
displayableResources = new DisplayableResources("parent user story", jUnitHtmlHelper.displayResources);
}
private void aBreadcrumbsIsAddedAfterTitle() throws Exception {
Elements breadcrumbs = jUnitHtmlHelper.html.select("ol.breadcrumb");
Assert.assertEquals(1, breadcrumbs.select("li").size());
Assert.assertEquals("Breadcrumb decorator sample", breadcrumbs.select("li").get(0).text());
| jUnitHtmlHelper.run(this.getClass(), SubUseCaseBreadcrumb.class); |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/use/UsingDecorator.java | // Path: sft-core/src/test/java/sft/integration/fixtures/SftResources.java
// public class SftResources {
//
// private final Class callerClass;
// private final JavaResource javaResource;
// private final SftResource htmlResource;
//
// public SftResources(Class callerClass, Class functionalTestClass) {
// this.callerClass = callerClass;
// javaResource = new JavaResource(functionalTestClass);
// htmlResource = new SftResource(functionalTestClass);
// }
//
// @Override
// public String toString() {
// return "<div class='resources'>" + javaResource.getOpenResourceHtmlLink(callerClass, "java", "alert-info") +
// htmlResource.getOpenResourceHtmlLink(callerClass, "html", "alert-info") + "</div>";
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/decorators/subUseCase/SubUseCaseBreadcrumb.java
// @Decorate(decorator = Breadcrumb.class)
// public class SubUseCaseBreadcrumb {
// @FixturesHelper
// private SftFixturesHelper sftFixturesHelper = new SftFixturesHelper();
//
// public SubSubUseCaseBreadcrumb subSubUseCaseBreadcrumb= new SubSubUseCaseBreadcrumb();
//
// @Test
// public void test(){
// sftFixturesHelper.doStuff();
// }
// }
| import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.Displayable;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.fixtures.SftResources;
import sft.integration.use.sut.decorators.*;
import sft.integration.use.sut.decorators.subUseCase.SubSubUseCaseBreadcrumb;
import sft.integration.use.sut.decorators.subUseCase.SubUseCaseBreadcrumb;
import java.io.IOException;
import java.util.ArrayList; | }
private void ignoredScenariosAreNumberedAndDisplayedWithDirectAccess() {
Elements digestTitles = jUnitHtmlHelper.html.select(".synthesis .digest.ignored .title");
Assert.assertEquals("2 scenarios ignored",digestTitles.get(0).text());
Assert.assertEquals("display: none;", jUnitHtmlHelper.html.select("#ignored_fold").get(0).attr("style"));
Assert.assertFalse(jUnitHtmlHelper.html.select("#ignored_unfold").get(0).hasAttr("style"));
Elements scenarios = jUnitHtmlHelper.html.select(".synthesis .digest.ignored .relatedUseCase");
Assert.assertEquals("Sub use case toc 2 : Sub use case toc 2b : Scenario 2b 1",scenarios.get(0).text());
Assert.assertEquals("Sub use case toc 3 : Scenario 32",scenarios.get(1).text());
}
private void failedScenariosAreNumberedAndDisplayedWithDirectAccess() {
Elements digestTitles = jUnitHtmlHelper.html.select(".synthesis .digest.failed .title");
Assert.assertEquals("2 scenarios failed",digestTitles.get(0).text());
Assert.assertEquals("display: none;", jUnitHtmlHelper.html.select("#failed_fold").get(0).attr("style"));
Assert.assertFalse(jUnitHtmlHelper.html.select("#failed_unfold").get(0).hasAttr("style"));
Elements scenarios = jUnitHtmlHelper.html.select(".synthesis .digest.failed .relatedUseCase");
Assert.assertEquals("Sub use case toc 2 : Sub use case toc 2c : Scenario 2c 1",scenarios.get(0).text());
Assert.assertEquals("Sub use case toc 3 : Scenario 33",scenarios.get(1).text());
}
private class DisplayableResources {
private ArrayList<String> labels = new ArrayList<String>(); | // Path: sft-core/src/test/java/sft/integration/fixtures/SftResources.java
// public class SftResources {
//
// private final Class callerClass;
// private final JavaResource javaResource;
// private final SftResource htmlResource;
//
// public SftResources(Class callerClass, Class functionalTestClass) {
// this.callerClass = callerClass;
// javaResource = new JavaResource(functionalTestClass);
// htmlResource = new SftResource(functionalTestClass);
// }
//
// @Override
// public String toString() {
// return "<div class='resources'>" + javaResource.getOpenResourceHtmlLink(callerClass, "java", "alert-info") +
// htmlResource.getOpenResourceHtmlLink(callerClass, "html", "alert-info") + "</div>";
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/decorators/subUseCase/SubUseCaseBreadcrumb.java
// @Decorate(decorator = Breadcrumb.class)
// public class SubUseCaseBreadcrumb {
// @FixturesHelper
// private SftFixturesHelper sftFixturesHelper = new SftFixturesHelper();
//
// public SubSubUseCaseBreadcrumb subSubUseCaseBreadcrumb= new SubSubUseCaseBreadcrumb();
//
// @Test
// public void test(){
// sftFixturesHelper.doStuff();
// }
// }
// Path: sft-core/src/test/java/sft/integration/use/UsingDecorator.java
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.Displayable;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.fixtures.SftResources;
import sft.integration.use.sut.decorators.*;
import sft.integration.use.sut.decorators.subUseCase.SubSubUseCaseBreadcrumb;
import sft.integration.use.sut.decorators.subUseCase.SubUseCaseBreadcrumb;
import java.io.IOException;
import java.util.ArrayList;
}
private void ignoredScenariosAreNumberedAndDisplayedWithDirectAccess() {
Elements digestTitles = jUnitHtmlHelper.html.select(".synthesis .digest.ignored .title");
Assert.assertEquals("2 scenarios ignored",digestTitles.get(0).text());
Assert.assertEquals("display: none;", jUnitHtmlHelper.html.select("#ignored_fold").get(0).attr("style"));
Assert.assertFalse(jUnitHtmlHelper.html.select("#ignored_unfold").get(0).hasAttr("style"));
Elements scenarios = jUnitHtmlHelper.html.select(".synthesis .digest.ignored .relatedUseCase");
Assert.assertEquals("Sub use case toc 2 : Sub use case toc 2b : Scenario 2b 1",scenarios.get(0).text());
Assert.assertEquals("Sub use case toc 3 : Scenario 32",scenarios.get(1).text());
}
private void failedScenariosAreNumberedAndDisplayedWithDirectAccess() {
Elements digestTitles = jUnitHtmlHelper.html.select(".synthesis .digest.failed .title");
Assert.assertEquals("2 scenarios failed",digestTitles.get(0).text());
Assert.assertEquals("display: none;", jUnitHtmlHelper.html.select("#failed_fold").get(0).attr("style"));
Assert.assertFalse(jUnitHtmlHelper.html.select("#failed_unfold").get(0).hasAttr("style"));
Elements scenarios = jUnitHtmlHelper.html.select(".synthesis .digest.failed .relatedUseCase");
Assert.assertEquals("Sub use case toc 2 : Sub use case toc 2c : Scenario 2c 1",scenarios.get(0).text());
Assert.assertEquals("Sub use case toc 3 : Scenario 33",scenarios.get(1).text());
}
private class DisplayableResources {
private ArrayList<String> labels = new ArrayList<String>(); | private ArrayList<SftResources> resources = new ArrayList<SftResources>(); |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/junit/JUnitResultTest.java | // Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import sft.integration.set.sut.CommonUseCase; | package sft.junit;
public class JUnitResultTest {
@Test
public void toto() { | // Path: sft-core/src/test/java/sft/integration/set/sut/CommonUseCase.java
// @RunWith(SimpleFunctionalTest.class)
// public class CommonUseCase {
//
// public SubUseCase1 subUseCase1 = new SubUseCase1();
// public SubUseCase2 subUseCase2 = new SubUseCase2();
//
// @Test
// public void scenario(){
// fixtureCall();
// }
//
// private void fixtureCall() {
// Assert.assertTrue(true);
// }
// }
// Path: sft-core/src/test/java/sft/junit/JUnitResultTest.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import sft.integration.set.sut.CommonUseCase;
package sft.junit;
public class JUnitResultTest {
@Test
public void toto() { | Result run = new JUnitCore().run(CommonUseCase.class); |
slezier/SimpleFunctionalTest | sft-core/src/main/java/sft/ProjectFolder.java | // Path: sft-core/src/main/java/sft/environment/TargetFolder.java
// public class TargetFolder extends ResourceFolder {
// public TargetFolder(String toProjectPath, String path) {
// super(toProjectPath, path);
// }
//
// public File createFileFromClass(Class<?> aClass, String extension) {
// String filePath = getFilePath(aClass, extension);
// makeDir(filePath);
// return getFile(filePath);
// }
//
// public List<String> copyFromResources(String fileName) throws IOException {
// try {
// final File targetDirectory = ensureTargetDirectoryExists();
// final URL resource = this .getClass().getClassLoader().getResource(fileName);
// final List<String> paths ;
// if( resource == null ){
// throw new RuntimeException("Can't find resource \""+fileName+ "\"; ensure this resource exists");
// }else if (resource.getProtocol().equals("jar")) {
// paths = new FromJar(resource).copy(targetDirectory);
// } else {
// paths = new FromDirectory(resource).copy(targetDirectory);
// }
// Collections.sort(paths);
// return paths;
// } catch (URISyntaxException e) {
// throw new RuntimeException(e);
// }
// }
//
// private void makeDir(String path) {
// File parentDirectory = ensureTargetDirectoryExists();
// for (String file : path.split("/")) {
// if (!file.contains(".")) {
// parentDirectory = new File(parentDirectory, file);
// if (!parentDirectory.exists()) {
// parentDirectory.mkdir();
// }
// }
// }
// }
//
// private File ensureTargetDirectoryExists() {
// final File targetDirectory = new File(getResourceFolder() + path);
// if (!targetDirectory.exists()) {
// targetDirectory.mkdir();
// }
// return targetDirectory;
// }
// }
| import sft.environment.ResourceFolder;
import sft.environment.TargetFolder; | package sft;
public class ProjectFolder {
public static final String MAVEN_CLASSES_TEST_PATH = "target/test-classes/";
public static final String MAVEN_SOURCES_TEST_PATH = "src/test/java/";
private String sourcesTest = MAVEN_SOURCES_TEST_PATH;
private String classesTest = MAVEN_CLASSES_TEST_PATH;
public void setSourcesTest(String pathToSourcesTest){
this.sourcesTest = pathToSourcesTest;
}
public void setClassesTest(String pathToClassesTest){
this.classesTest = pathToClassesTest;
}
public String getClassesTestPath() {
return classesTest;
}
public ResourceFolder getResourceFolder() {
return new ResourceFolder(toProjectPath(), sourcesTest);
}
| // Path: sft-core/src/main/java/sft/environment/TargetFolder.java
// public class TargetFolder extends ResourceFolder {
// public TargetFolder(String toProjectPath, String path) {
// super(toProjectPath, path);
// }
//
// public File createFileFromClass(Class<?> aClass, String extension) {
// String filePath = getFilePath(aClass, extension);
// makeDir(filePath);
// return getFile(filePath);
// }
//
// public List<String> copyFromResources(String fileName) throws IOException {
// try {
// final File targetDirectory = ensureTargetDirectoryExists();
// final URL resource = this .getClass().getClassLoader().getResource(fileName);
// final List<String> paths ;
// if( resource == null ){
// throw new RuntimeException("Can't find resource \""+fileName+ "\"; ensure this resource exists");
// }else if (resource.getProtocol().equals("jar")) {
// paths = new FromJar(resource).copy(targetDirectory);
// } else {
// paths = new FromDirectory(resource).copy(targetDirectory);
// }
// Collections.sort(paths);
// return paths;
// } catch (URISyntaxException e) {
// throw new RuntimeException(e);
// }
// }
//
// private void makeDir(String path) {
// File parentDirectory = ensureTargetDirectoryExists();
// for (String file : path.split("/")) {
// if (!file.contains(".")) {
// parentDirectory = new File(parentDirectory, file);
// if (!parentDirectory.exists()) {
// parentDirectory.mkdir();
// }
// }
// }
// }
//
// private File ensureTargetDirectoryExists() {
// final File targetDirectory = new File(getResourceFolder() + path);
// if (!targetDirectory.exists()) {
// targetDirectory.mkdir();
// }
// return targetDirectory;
// }
// }
// Path: sft-core/src/main/java/sft/ProjectFolder.java
import sft.environment.ResourceFolder;
import sft.environment.TargetFolder;
package sft;
public class ProjectFolder {
public static final String MAVEN_CLASSES_TEST_PATH = "target/test-classes/";
public static final String MAVEN_SOURCES_TEST_PATH = "src/test/java/";
private String sourcesTest = MAVEN_SOURCES_TEST_PATH;
private String classesTest = MAVEN_CLASSES_TEST_PATH;
public void setSourcesTest(String pathToSourcesTest){
this.sourcesTest = pathToSourcesTest;
}
public void setClassesTest(String pathToClassesTest){
this.classesTest = pathToClassesTest;
}
public String getClassesTestPath() {
return classesTest;
}
public ResourceFolder getResourceFolder() {
return new ResourceFolder(toProjectPath(), sourcesTest);
}
| public TargetFolder getTargetFolder(String path ){ |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/use/HumanizationCodeUsage.java | // Path: sft-core/src/test/java/sft/integration/use/sut/HumanizationUsingTextAnnotation.java
// @RunWith(SimpleFunctionalTest.class)
// @Text("Use case name specified in @Text")
// public class HumanizationUsingTextAnnotation {
//
// @Test
// @Text("Scenario name specified in @Text")
// public void scenario1(){
// fixture1();
// }
//
// @Text("Fixture name specified in @Text")
// private void fixture1() {
// Assert.assertTrue(true);
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/Humanization_underscore_class_name_humanized.java
// @RunWith(SimpleFunctionalTest.class)
// public class Humanization_underscore_class_name_humanized {
// @Test
// public void underscore_scenario_name_humanized(){
// underscore_fixture_name_humanized();
// }
//
// private void underscore_fixture_name_humanized() {
// Assert.assertTrue(true);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.use.sut.HumanizationCamelCaseClassNameHumanized;
import sft.integration.use.sut.HumanizationUsingTextAnnotation;
import sft.integration.use.sut.Humanization_underscore_class_name_humanized;
import java.io.IOException; | package sft.integration.use;
/*
Class and methods could be humanized 3 different ways:
*/
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
@Text("Humanized your code: using camelCase or underscore transformation or annotation")
public class HumanizationCodeUsage {
@FixturesHelper
private JUnitHtmlHelper jUnitHtmlHelper = new JUnitHtmlHelper();
@Test
public void namingInCamelCase() throws IOException {
allCaseChangesAreReplacedBySpaces();
}
@Test
public void namingUsingUnderscore() throws IOException {
underscoreAreReplacedBySpace();
}
@Test
public void usingTextAnnotation() throws IOException {
textsAreDisplayedUnchanged();
}
private void allCaseChangesAreReplacedBySpaces() throws IOException {
jUnitHtmlHelper.run(this.getClass(), HumanizationCamelCaseClassNameHumanized.class);
Assert.assertEquals("Humanization camel case class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Camel case scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Camel case fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void underscoreAreReplacedBySpace() throws IOException { | // Path: sft-core/src/test/java/sft/integration/use/sut/HumanizationUsingTextAnnotation.java
// @RunWith(SimpleFunctionalTest.class)
// @Text("Use case name specified in @Text")
// public class HumanizationUsingTextAnnotation {
//
// @Test
// @Text("Scenario name specified in @Text")
// public void scenario1(){
// fixture1();
// }
//
// @Text("Fixture name specified in @Text")
// private void fixture1() {
// Assert.assertTrue(true);
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/Humanization_underscore_class_name_humanized.java
// @RunWith(SimpleFunctionalTest.class)
// public class Humanization_underscore_class_name_humanized {
// @Test
// public void underscore_scenario_name_humanized(){
// underscore_fixture_name_humanized();
// }
//
// private void underscore_fixture_name_humanized() {
// Assert.assertTrue(true);
// }
// }
// Path: sft-core/src/test/java/sft/integration/use/HumanizationCodeUsage.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.use.sut.HumanizationCamelCaseClassNameHumanized;
import sft.integration.use.sut.HumanizationUsingTextAnnotation;
import sft.integration.use.sut.Humanization_underscore_class_name_humanized;
import java.io.IOException;
package sft.integration.use;
/*
Class and methods could be humanized 3 different ways:
*/
@RunWith(SimpleFunctionalTest.class)
@Decorate(decorator = Breadcrumb.class)
@Text("Humanized your code: using camelCase or underscore transformation or annotation")
public class HumanizationCodeUsage {
@FixturesHelper
private JUnitHtmlHelper jUnitHtmlHelper = new JUnitHtmlHelper();
@Test
public void namingInCamelCase() throws IOException {
allCaseChangesAreReplacedBySpaces();
}
@Test
public void namingUsingUnderscore() throws IOException {
underscoreAreReplacedBySpace();
}
@Test
public void usingTextAnnotation() throws IOException {
textsAreDisplayedUnchanged();
}
private void allCaseChangesAreReplacedBySpaces() throws IOException {
jUnitHtmlHelper.run(this.getClass(), HumanizationCamelCaseClassNameHumanized.class);
Assert.assertEquals("Humanization camel case class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Camel case scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Camel case fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void underscoreAreReplacedBySpace() throws IOException { | jUnitHtmlHelper.run(this.getClass(), Humanization_underscore_class_name_humanized.class); |
slezier/SimpleFunctionalTest | sft-core/src/test/java/sft/integration/use/HumanizationCodeUsage.java | // Path: sft-core/src/test/java/sft/integration/use/sut/HumanizationUsingTextAnnotation.java
// @RunWith(SimpleFunctionalTest.class)
// @Text("Use case name specified in @Text")
// public class HumanizationUsingTextAnnotation {
//
// @Test
// @Text("Scenario name specified in @Text")
// public void scenario1(){
// fixture1();
// }
//
// @Text("Fixture name specified in @Text")
// private void fixture1() {
// Assert.assertTrue(true);
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/Humanization_underscore_class_name_humanized.java
// @RunWith(SimpleFunctionalTest.class)
// public class Humanization_underscore_class_name_humanized {
// @Test
// public void underscore_scenario_name_humanized(){
// underscore_fixture_name_humanized();
// }
//
// private void underscore_fixture_name_humanized() {
// Assert.assertTrue(true);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.use.sut.HumanizationCamelCaseClassNameHumanized;
import sft.integration.use.sut.HumanizationUsingTextAnnotation;
import sft.integration.use.sut.Humanization_underscore_class_name_humanized;
import java.io.IOException; |
@Test
public void namingInCamelCase() throws IOException {
allCaseChangesAreReplacedBySpaces();
}
@Test
public void namingUsingUnderscore() throws IOException {
underscoreAreReplacedBySpace();
}
@Test
public void usingTextAnnotation() throws IOException {
textsAreDisplayedUnchanged();
}
private void allCaseChangesAreReplacedBySpaces() throws IOException {
jUnitHtmlHelper.run(this.getClass(), HumanizationCamelCaseClassNameHumanized.class);
Assert.assertEquals("Humanization camel case class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Camel case scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Camel case fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void underscoreAreReplacedBySpace() throws IOException {
jUnitHtmlHelper.run(this.getClass(), Humanization_underscore_class_name_humanized.class);
Assert.assertEquals("Humanization underscore class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Underscore scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Underscore fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void textsAreDisplayedUnchanged() throws IOException { | // Path: sft-core/src/test/java/sft/integration/use/sut/HumanizationUsingTextAnnotation.java
// @RunWith(SimpleFunctionalTest.class)
// @Text("Use case name specified in @Text")
// public class HumanizationUsingTextAnnotation {
//
// @Test
// @Text("Scenario name specified in @Text")
// public void scenario1(){
// fixture1();
// }
//
// @Text("Fixture name specified in @Text")
// private void fixture1() {
// Assert.assertTrue(true);
// }
// }
//
// Path: sft-core/src/test/java/sft/integration/use/sut/Humanization_underscore_class_name_humanized.java
// @RunWith(SimpleFunctionalTest.class)
// public class Humanization_underscore_class_name_humanized {
// @Test
// public void underscore_scenario_name_humanized(){
// underscore_fixture_name_humanized();
// }
//
// private void underscore_fixture_name_humanized() {
// Assert.assertTrue(true);
// }
// }
// Path: sft-core/src/test/java/sft/integration/use/HumanizationCodeUsage.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import sft.Decorate;
import sft.FixturesHelper;
import sft.SimpleFunctionalTest;
import sft.Text;
import sft.decorators.Breadcrumb;
import sft.integration.fixtures.JUnitHtmlHelper;
import sft.integration.use.sut.HumanizationCamelCaseClassNameHumanized;
import sft.integration.use.sut.HumanizationUsingTextAnnotation;
import sft.integration.use.sut.Humanization_underscore_class_name_humanized;
import java.io.IOException;
@Test
public void namingInCamelCase() throws IOException {
allCaseChangesAreReplacedBySpaces();
}
@Test
public void namingUsingUnderscore() throws IOException {
underscoreAreReplacedBySpace();
}
@Test
public void usingTextAnnotation() throws IOException {
textsAreDisplayedUnchanged();
}
private void allCaseChangesAreReplacedBySpaces() throws IOException {
jUnitHtmlHelper.run(this.getClass(), HumanizationCamelCaseClassNameHumanized.class);
Assert.assertEquals("Humanization camel case class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Camel case scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Camel case fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void underscoreAreReplacedBySpace() throws IOException {
jUnitHtmlHelper.run(this.getClass(), Humanization_underscore_class_name_humanized.class);
Assert.assertEquals("Humanization underscore class name humanized", jUnitHtmlHelper.html.select("*.useCaseName").text());
Assert.assertEquals("Underscore scenario name humanized", jUnitHtmlHelper.html.select("*.scenarioName").text());
Assert.assertEquals("Underscore fixture name humanized", jUnitHtmlHelper.html.select("*.instruction").text());
}
private void textsAreDisplayedUnchanged() throws IOException { | jUnitHtmlHelper.run(this.getClass(),HumanizationUsingTextAnnotation.class); |
slezier/SimpleFunctionalTest | sft-md-report/src/main/java/sft/reports/markdown/decorators/MdNullDecorator.java | // Path: sft-core/src/main/java/sft/FixtureCall.java
// public class FixtureCall {
//
// public final UseCase useCase;
// public final String name;
// public final int line;
// public final Fixture fixture;
// public final int emptyLine;
// public ArrayList<String> parametersValues = new ArrayList<String>();
//
// public FixtureCall(UseCase useCase, String name, int line, Fixture fixture, ArrayList<String> parametersValues, int emptyLine) {
// this.useCase = useCase;
// this.name = name;
// this.line = line;
// this.fixture= fixture;
// this.emptyLine = emptyLine;
// this.parametersValues.addAll(parametersValues);
// }
//
// public Map<String, String> getParameters() {
// final HashMap<String, String> parameters = new HashMap<String, String>();
// for (int index = 0; index < fixture.parametersName.size(); index++) {
// String name = fixture.parametersName.get(index);
// String value = parametersValues.get(index);
// parameters.put(name,value);
// }
// return parameters;
// }
// }
//
// Path: sft-md-report/src/main/java/sft/reports/markdown/MarkdownReport.java
// public class MarkdownReport extends Report {
// private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
//
// private TargetFolder folder;
// private static final String TARGET_SFT_RESULT = "target/sft-result/";
// public static final String MD_DEPENDENCIES_FOLDER = "sft-md-default";
//
//
// public MarkdownReport(DefaultConfiguration configuration){
// super(configuration);
// decorators.put(NullDecorator.class,new MdNullDecorator(configuration));
// folder=configuration.getProjectFolder().getTargetFolder(TARGET_SFT_RESULT);
// }
//
// @Override
// public DecoratorReportImplementation getDecoratorImplementation(Decorator decorator) {
// DecoratorReportImplementation result = decorators.get(decorator.getClass());
// if( result == null ){
// result = new MdNullDecorator(configuration);
// }
// return result;
// }
//
// @Override
// public void addDecorator(Class<? extends Decorator> decoratorClass, DecoratorReportImplementation decoratorImplementation) {
// decorators.put(decoratorClass,decoratorImplementation);
//
// }
//
// @Override
// public void report(UseCaseResult useCaseResult) throws Exception {
// folder.copyFromResources(MD_DEPENDENCIES_FOLDER);
// final Decorator decorator = useCaseResult.useCase.useCaseDecorator;
// DecoratorReportImplementation decoratorImplementation = getDecoratorImplementation(decorator);
// String useCaseReport = decoratorImplementation.applyOnUseCase(useCaseResult, decorator.parameters);
//
// File mdFile = folder.createFileFromClass(useCaseResult.useCase.classUnderTest, ".md");
// Writer html = new OutputStreamWriter(new FileOutputStream(mdFile));
// html.write(useCaseReport);
// html.close();
// System.out.println("Report wrote: " + mdFile.getCanonicalPath());
// }
// }
| import sft.ContextHandler;
import sft.DefaultConfiguration;
import sft.FixtureCall;
import sft.UseCase;
import sft.decorators.DecoratorReportImplementation;
import sft.report.RelativePathResolver;
import sft.reports.markdown.MarkdownReport;
import sft.result.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; | package sft.reports.markdown.decorators;
public class MdNullDecorator implements DecoratorReportImplementation {
private final DefaultConfiguration configuration;
private final RelativePathResolver pathResolver = new RelativePathResolver();
public MdNullDecorator(DefaultConfiguration configuration) {
this.configuration = configuration;
}
@Override
public String applyOnUseCase(UseCaseResult useCaseResult, String... parameters) {
String result = writeUseCaseName(useCaseResult.useCase, useCaseResult.getIssue());
result += writeComment(useCaseResult.useCase.getComment());
result += writeContext(useCaseResult.useCase.beforeUseCase);
result += applyOnScenarios(useCaseResult.scenarioResults);
result += writeContext(useCaseResult.useCase.afterUseCase);
result += applyOnSubUseCases(useCaseResult.subUseCaseResults);
return result;
}
private String writeContext(ContextHandler beforeUseCase) {
String result = "";
if(beforeUseCase != null && beforeUseCase.fixtureCalls !=null){ | // Path: sft-core/src/main/java/sft/FixtureCall.java
// public class FixtureCall {
//
// public final UseCase useCase;
// public final String name;
// public final int line;
// public final Fixture fixture;
// public final int emptyLine;
// public ArrayList<String> parametersValues = new ArrayList<String>();
//
// public FixtureCall(UseCase useCase, String name, int line, Fixture fixture, ArrayList<String> parametersValues, int emptyLine) {
// this.useCase = useCase;
// this.name = name;
// this.line = line;
// this.fixture= fixture;
// this.emptyLine = emptyLine;
// this.parametersValues.addAll(parametersValues);
// }
//
// public Map<String, String> getParameters() {
// final HashMap<String, String> parameters = new HashMap<String, String>();
// for (int index = 0; index < fixture.parametersName.size(); index++) {
// String name = fixture.parametersName.get(index);
// String value = parametersValues.get(index);
// parameters.put(name,value);
// }
// return parameters;
// }
// }
//
// Path: sft-md-report/src/main/java/sft/reports/markdown/MarkdownReport.java
// public class MarkdownReport extends Report {
// private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
//
// private TargetFolder folder;
// private static final String TARGET_SFT_RESULT = "target/sft-result/";
// public static final String MD_DEPENDENCIES_FOLDER = "sft-md-default";
//
//
// public MarkdownReport(DefaultConfiguration configuration){
// super(configuration);
// decorators.put(NullDecorator.class,new MdNullDecorator(configuration));
// folder=configuration.getProjectFolder().getTargetFolder(TARGET_SFT_RESULT);
// }
//
// @Override
// public DecoratorReportImplementation getDecoratorImplementation(Decorator decorator) {
// DecoratorReportImplementation result = decorators.get(decorator.getClass());
// if( result == null ){
// result = new MdNullDecorator(configuration);
// }
// return result;
// }
//
// @Override
// public void addDecorator(Class<? extends Decorator> decoratorClass, DecoratorReportImplementation decoratorImplementation) {
// decorators.put(decoratorClass,decoratorImplementation);
//
// }
//
// @Override
// public void report(UseCaseResult useCaseResult) throws Exception {
// folder.copyFromResources(MD_DEPENDENCIES_FOLDER);
// final Decorator decorator = useCaseResult.useCase.useCaseDecorator;
// DecoratorReportImplementation decoratorImplementation = getDecoratorImplementation(decorator);
// String useCaseReport = decoratorImplementation.applyOnUseCase(useCaseResult, decorator.parameters);
//
// File mdFile = folder.createFileFromClass(useCaseResult.useCase.classUnderTest, ".md");
// Writer html = new OutputStreamWriter(new FileOutputStream(mdFile));
// html.write(useCaseReport);
// html.close();
// System.out.println("Report wrote: " + mdFile.getCanonicalPath());
// }
// }
// Path: sft-md-report/src/main/java/sft/reports/markdown/decorators/MdNullDecorator.java
import sft.ContextHandler;
import sft.DefaultConfiguration;
import sft.FixtureCall;
import sft.UseCase;
import sft.decorators.DecoratorReportImplementation;
import sft.report.RelativePathResolver;
import sft.reports.markdown.MarkdownReport;
import sft.result.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
package sft.reports.markdown.decorators;
public class MdNullDecorator implements DecoratorReportImplementation {
private final DefaultConfiguration configuration;
private final RelativePathResolver pathResolver = new RelativePathResolver();
public MdNullDecorator(DefaultConfiguration configuration) {
this.configuration = configuration;
}
@Override
public String applyOnUseCase(UseCaseResult useCaseResult, String... parameters) {
String result = writeUseCaseName(useCaseResult.useCase, useCaseResult.getIssue());
result += writeComment(useCaseResult.useCase.getComment());
result += writeContext(useCaseResult.useCase.beforeUseCase);
result += applyOnScenarios(useCaseResult.scenarioResults);
result += writeContext(useCaseResult.useCase.afterUseCase);
result += applyOnSubUseCases(useCaseResult.subUseCaseResults);
return result;
}
private String writeContext(ContextHandler beforeUseCase) {
String result = "";
if(beforeUseCase != null && beforeUseCase.fixtureCalls !=null){ | for (FixtureCall fixtureCall : beforeUseCase.fixtureCalls) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.