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
Adyen/adyen-hybris
adyenv6notification/src/com/adyen/v6/jalo/Adyenv6notificationManager.java
// Path: adyenv6notification/src/com/adyen/v6/constants/Adyenv6notificationConstants.java // @SuppressWarnings("deprecation") // public final class Adyenv6notificationConstants extends GeneratedAdyenv6notificationConstants //NOSONAR // { // public static final String EXTENSIONNAME = "adyenv6notification"; // // private Adyenv6notificationConstants() // { // //empty to avoid instantiating this constant class // } // // // implement here constants used by this extension // }
import de.hybris.platform.jalo.JaloSession; import de.hybris.platform.jalo.extension.ExtensionManager; import org.apache.log4j.Logger; import com.adyen.v6.constants.Adyenv6notificationConstants;
/* * [y] hybris Platform * * Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.adyen.v6.jalo; @SuppressWarnings("PMD") public class Adyenv6notificationManager extends GeneratedAdyenv6notificationManager { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger( Adyenv6notificationManager.class.getName() ); public static final Adyenv6notificationManager getInstance() { ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager();
// Path: adyenv6notification/src/com/adyen/v6/constants/Adyenv6notificationConstants.java // @SuppressWarnings("deprecation") // public final class Adyenv6notificationConstants extends GeneratedAdyenv6notificationConstants //NOSONAR // { // public static final String EXTENSIONNAME = "adyenv6notification"; // // private Adyenv6notificationConstants() // { // //empty to avoid instantiating this constant class // } // // // implement here constants used by this extension // } // Path: adyenv6notification/src/com/adyen/v6/jalo/Adyenv6notificationManager.java import de.hybris.platform.jalo.JaloSession; import de.hybris.platform.jalo.extension.ExtensionManager; import org.apache.log4j.Logger; import com.adyen.v6.constants.Adyenv6notificationConstants; /* * [y] hybris Platform * * Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.adyen.v6.jalo; @SuppressWarnings("PMD") public class Adyenv6notificationManager extends GeneratedAdyenv6notificationManager { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger( Adyenv6notificationManager.class.getName() ); public static final Adyenv6notificationManager getInstance() { ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager();
return (Adyenv6notificationManager) em.getExtension(Adyenv6notificationConstants.EXTENSIONNAME);
Adyen/adyen-hybris
adyenv6fulfilmentprocess/src/com/adyen/v6/jalo/Adyenv6fulfilmentprocessManager.java
// Path: adyenv6fulfilmentprocess/src/com/adyen/v6/constants/Adyenv6fulfilmentprocessConstants.java // public final class Adyenv6fulfilmentprocessConstants extends GeneratedAdyenv6fulfilmentprocessConstants // { // public static final String EXTENSIONNAME = "adyenv6fulfilmentprocess"; // // private Adyenv6fulfilmentprocessConstants() // { // //empty to avoid instantiating this constant class // } // // // implement here constants used by this extension // // public static final String PLATFORM_LOGO_CODE = "adyenv6fulfilmentprocessPlatformLogo"; // }
import de.hybris.platform.core.Registry; import de.hybris.platform.util.JspContext; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.adyen.v6.constants.Adyenv6fulfilmentprocessConstants;
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.adyen.v6.jalo; /** * This is the extension manager of the Adyenv6fulfilmentprocess extension. */ public class Adyenv6fulfilmentprocessManager extends GeneratedAdyenv6fulfilmentprocessManager { /** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */ private static final Logger LOG = LoggerFactory.getLogger(Adyenv6fulfilmentprocessManager.class); /* * Some important tips for development: Do NEVER use the default constructor of manager's or items. => If you want to * do something whenever the manger is created use the init() or destroy() methods described below Do NEVER use * STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an instance * variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant. */ /** * Get the valid instance of this manager. * * @return the current instance of this manager */ public static Adyenv6fulfilmentprocessManager getInstance() { return (Adyenv6fulfilmentprocessManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager()
// Path: adyenv6fulfilmentprocess/src/com/adyen/v6/constants/Adyenv6fulfilmentprocessConstants.java // public final class Adyenv6fulfilmentprocessConstants extends GeneratedAdyenv6fulfilmentprocessConstants // { // public static final String EXTENSIONNAME = "adyenv6fulfilmentprocess"; // // private Adyenv6fulfilmentprocessConstants() // { // //empty to avoid instantiating this constant class // } // // // implement here constants used by this extension // // public static final String PLATFORM_LOGO_CODE = "adyenv6fulfilmentprocessPlatformLogo"; // } // Path: adyenv6fulfilmentprocess/src/com/adyen/v6/jalo/Adyenv6fulfilmentprocessManager.java import de.hybris.platform.core.Registry; import de.hybris.platform.util.JspContext; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.adyen.v6.constants.Adyenv6fulfilmentprocessConstants; /* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.adyen.v6.jalo; /** * This is the extension manager of the Adyenv6fulfilmentprocess extension. */ public class Adyenv6fulfilmentprocessManager extends GeneratedAdyenv6fulfilmentprocessManager { /** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */ private static final Logger LOG = LoggerFactory.getLogger(Adyenv6fulfilmentprocessManager.class); /* * Some important tips for development: Do NEVER use the default constructor of manager's or items. => If you want to * do something whenever the manger is created use the init() or destroy() methods described below Do NEVER use * STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an instance * variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant. */ /** * Get the valid instance of this manager. * * @return the current instance of this manager */ public static Adyenv6fulfilmentprocessManager getInstance() { return (Adyenv6fulfilmentprocessManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager()
.getExtension(Adyenv6fulfilmentprocessConstants.EXTENSIONNAME);
Adyen/adyen-hybris
adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.enums.PaymentTransactionType; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import java.math.BigDecimal; import java.util.ArrayList; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
protected PaymentTransactionEntryModel createCaptureRejectedEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.CAPTURE); entry.setTransactionStatus(TransactionStatus.REJECTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); return entry; } protected PaymentTransactionEntryModel createRefundRejectedEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); entry.setTransactionStatus(TransactionStatus.REJECTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); return entry; } protected PaymentTransactionEntryModel createRefundSuccessEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); return entry; } protected PaymentTransactionModel createAdyenTransaction() { PaymentTransactionModel adyenTransaction = new PaymentTransactionModel();
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.enums.PaymentTransactionType; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import java.math.BigDecimal; import java.util.ArrayList; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; protected PaymentTransactionEntryModel createCaptureRejectedEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.CAPTURE); entry.setTransactionStatus(TransactionStatus.REJECTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); return entry; } protected PaymentTransactionEntryModel createRefundRejectedEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); entry.setTransactionStatus(TransactionStatus.REJECTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); return entry; } protected PaymentTransactionEntryModel createRefundSuccessEntry() { PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); return entry; } protected PaymentTransactionModel createAdyenTransaction() { PaymentTransactionModel adyenTransaction = new PaymentTransactionModel();
adyenTransaction.setPaymentProvider(PAYMENT_PROVIDER);
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public class DefaultAdyenOrderService implements AdyenOrderService { private static final Logger LOG = Logger.getLogger(DefaultAdyenOrderService.class); private ModelService modelService;
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; /* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public class DefaultAdyenOrderService implements AdyenOrderService { private static final Logger LOG = Logger.getLogger(DefaultAdyenOrderService.class); private ModelService modelService;
private PaymentsResponseConverter paymentsResponseConverter;
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public class DefaultAdyenOrderService implements AdyenOrderService { private static final Logger LOG = Logger.getLogger(DefaultAdyenOrderService.class); private ModelService modelService; private PaymentsResponseConverter paymentsResponseConverter; @Override public FraudReportModel createFraudReportFromPaymentsResponse(PaymentsResponse paymentsResponse) { FraudReportModel fraudReport = modelService.create(FraudReportModel.class); FraudResult fraudResult = paymentsResponse.getFraudResult(); if (fraudResult == null) { LOG.debug("No fraud result found"); return null; } fraudReport.setCode(paymentsResponse.getPspReference()); fraudReport.setStatus(FraudStatus.OK); fraudReport.setExplanation("Score: " + fraudResult.getAccountScore()); fraudReport.setTimestamp(new Date());
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; /* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public class DefaultAdyenOrderService implements AdyenOrderService { private static final Logger LOG = Logger.getLogger(DefaultAdyenOrderService.class); private ModelService modelService; private PaymentsResponseConverter paymentsResponseConverter; @Override public FraudReportModel createFraudReportFromPaymentsResponse(PaymentsResponse paymentsResponse) { FraudReportModel fraudReport = modelService.create(FraudReportModel.class); FraudResult fraudResult = paymentsResponse.getFraudResult(); if (fraudResult == null) { LOG.debug("No fraud result found"); return null; } fraudReport.setCode(paymentsResponse.getPspReference()); fraudReport.setStatus(FraudStatus.OK); fraudReport.setExplanation("Score: " + fraudResult.getAccountScore()); fraudReport.setTimestamp(new Date());
fraudReport.setProvider(PAYMENT_PROVIDER);
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); storeFraudReportFromPaymentsResponse(order, paymentsResponse); } @Override public void updateOrderFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse) { if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) {
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); storeFraudReportFromPaymentsResponse(order, paymentsResponse); } @Override public void updateOrderFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse) { if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) {
if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) {
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) { if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { //Multibanco data paymentInfo.setAdyenMultibancoEntity(action.getEntity()); paymentInfo.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); paymentInfo.setAdyenMultibancoDeadline(action.getExpiresAt()); paymentInfo.setAdyenMultibancoReference(action.getReference());
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) { if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { //Multibanco data paymentInfo.setAdyenMultibancoEntity(action.getEntity()); paymentInfo.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); paymentInfo.setAdyenMultibancoDeadline(action.getExpiresAt()); paymentInfo.setAdyenMultibancoReference(action.getReference());
} else if (PAYMENT_METHOD_BOLETO.equals(action.getPaymentMethodType()) || PAYMENT_METHOD_BOLETO_SANTANDER.equals(action.getPaymentMethodType())) {
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) { if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { //Multibanco data paymentInfo.setAdyenMultibancoEntity(action.getEntity()); paymentInfo.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); paymentInfo.setAdyenMultibancoDeadline(action.getExpiresAt()); paymentInfo.setAdyenMultibancoReference(action.getReference());
// Path: adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java // public class PaymentsResponseConverter implements Converter<PaymentResult, PaymentsResponse> { // @Override // public PaymentsResponse convert(PaymentResult paymentResult) { // if (paymentResult == null) { // throw new IllegalArgumentException("Null PaymentResult"); // } // PaymentsResponse paymentsResponse = new PaymentsResponse(); // paymentsResponse.setPspReference(paymentResult.getPspReference()); // paymentsResponse.setFraudResult(paymentResult.getFraudResult()); // // paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); // paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); // // return paymentsResponse; // } // } // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO = "boleto"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_BOLETO_SANTANDER = "boletobancario_santander"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // final public static String PAYMENT_METHOD_MULTIBANCO = "multibanco"; // // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.adyen.util.DateUtil; import org.apache.log4j.Logger; import com.adyen.model.FraudCheckResult; import com.adyen.model.FraudResult; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.CheckoutPaymentsAction; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.v6.converters.PaymentsResponseConverter; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); if(paymentsResponse.getPaymentMethod()!=null && !paymentsResponse.getPaymentMethod().isEmpty()) { paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod()); } //Card specific data paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); CheckoutPaymentsAction action = paymentsResponse.getAction(); if (action != null) { if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { //Multibanco data paymentInfo.setAdyenMultibancoEntity(action.getEntity()); paymentInfo.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); paymentInfo.setAdyenMultibancoDeadline(action.getExpiresAt()); paymentInfo.setAdyenMultibancoReference(action.getReference());
} else if (PAYMENT_METHOD_BOLETO.equals(action.getPaymentMethodType()) || PAYMENT_METHOD_BOLETO_SANTANDER.equals(action.getPaymentMethodType())) {
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/AdyenOrderCancelPaymentServiceAdapter.java
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen";
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; import static de.hybris.platform.core.enums.OrderStatus.CANCELLED; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.order.CalculationService; import de.hybris.platform.order.exceptions.CalculationException; import de.hybris.platform.ordercancel.OrderCancelPaymentServiceAdapter; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.servicelayer.model.ModelService; import org.apache.log4j.Logger;
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; /** * Used for cancellations by ImmediateCancelRequestExecutor */ public class AdyenOrderCancelPaymentServiceAdapter implements OrderCancelPaymentServiceAdapter { private PaymentService paymentService; private ModelService modelService; private CalculationService calculationService; private static final Logger LOG = Logger.getLogger(AdyenOrderCancelPaymentServiceAdapter.class); /** * Issues a cancel request for complete cancelled orders * * @param order */ @Override public void recalculateOrderAndModifyPayments(final OrderModel order) { LOG.debug("recalculateOrderAndModifyPayments received for order: " + order.getCode() + ":" + order.getTotalPrice() + ":" + order.getStatus().getCode()); try { calculationService.recalculate(order); } catch (CalculationException e) { LOG.error(e); } //Send the cancel request only when the whole order is cancelled if (!CANCELLED.getCode().equals(order.getStatus().getCode())) { LOG.info("Partial cancellation - do nothing"); return; } if(order.getPaymentTransactions().isEmpty()) { LOG.warn("No transaction found!"); return; } final PaymentTransactionModel transaction = order.getPaymentTransactions().get(0); //Ignore non-Adyen payments
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java // public static final String PAYMENT_PROVIDER = "Adyen"; // Path: adyenv6core/src/com/adyen/v6/service/AdyenOrderCancelPaymentServiceAdapter.java import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; import static de.hybris.platform.core.enums.OrderStatus.CANCELLED; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.order.CalculationService; import de.hybris.platform.order.exceptions.CalculationException; import de.hybris.platform.ordercancel.OrderCancelPaymentServiceAdapter; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.servicelayer.model.ModelService; import org.apache.log4j.Logger; /* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; /** * Used for cancellations by ImmediateCancelRequestExecutor */ public class AdyenOrderCancelPaymentServiceAdapter implements OrderCancelPaymentServiceAdapter { private PaymentService paymentService; private ModelService modelService; private CalculationService calculationService; private static final Logger LOG = Logger.getLogger(AdyenOrderCancelPaymentServiceAdapter.class); /** * Issues a cancel request for complete cancelled orders * * @param order */ @Override public void recalculateOrderAndModifyPayments(final OrderModel order) { LOG.debug("recalculateOrderAndModifyPayments received for order: " + order.getCode() + ":" + order.getTotalPrice() + ":" + order.getStatus().getCode()); try { calculationService.recalculate(order); } catch (CalculationException e) { LOG.error(e); } //Send the cancel request only when the whole order is cancelled if (!CANCELLED.getCode().equals(order.getStatus().getCode())) { LOG.info("Partial cancellation - do nothing"); return; } if(order.getPaymentTransactions().isEmpty()) { LOG.warn("No transaction found!"); return; } final PaymentTransactionModel transaction = order.getPaymentTransactions().get(0); //Ignore non-Adyen payments
if (!PAYMENT_PROVIDER.equals(transaction.getPaymentProvider())) {
Adyen/adyen-hybris
adyenv6core/src/com/adyen/v6/service/AdyenPaymentService.java
// Path: adyenv6core/src/com/adyen/v6/model/RequestInfo.java // public class RequestInfo { // // public static final String USER_AGENT_HEADER = "User-Agent"; // public static final String ACCEPT_HEADER = "Accept"; // // private String userAgent; // private String acceptHeader; // private String shopperIp; // private String origin; // private String shopperLocale; // // public RequestInfo(HttpServletRequest request) { // this.userAgent = request.getHeader(USER_AGENT_HEADER); // this.acceptHeader = request.getHeader(ACCEPT_HEADER); // this.shopperIp = request.getRemoteAddr(); // this.origin = getOrigin(request); // } // // private RequestInfo() { // } // // public String getOrigin(HttpServletRequest request) { // String currentRequestURL = request.getRequestURL().toString(); // int requestUrlLength = currentRequestURL.length(); // int requestUriLength = request.getRequestURI().length(); // // String baseURL = currentRequestURL.substring(0, requestUrlLength - requestUriLength); // return baseURL; // } // // public String getOrigin() { // return this.origin; // } // // public static RequestInfo empty() { // return new RequestInfo(); // } // // public String getUserAgent() { // return userAgent; // } // // public String getAcceptHeader() { // return acceptHeader; // } // // public String getShopperIp() { // return shopperIp; // } // // public String getShopperLocale() { // return shopperLocale; // } // // public void setShopperLocale(String shopperLocale) { // this.shopperLocale = shopperLocale; // } // }
import com.adyen.httpclient.HTTPClientException; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.PaymentMethod; import com.adyen.model.checkout.PaymentMethodDetails; import com.adyen.model.checkout.PaymentMethodsResponse; import com.adyen.model.checkout.PaymentsDetailsResponse; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.model.modification.ModificationResult; import com.adyen.model.recurring.RecurringDetail; import com.adyen.model.terminal.ConnectedTerminalsResponse; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.service.exception.ApiException; import com.adyen.v6.model.RequestInfo; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.core.model.user.CustomerModel; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.security.SignatureException; import java.util.Currency; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public interface AdyenPaymentService { /** * Performs authorization request via Adyen API */ PaymentResult authorise(CartData cartData, HttpServletRequest request, CustomerModel customerModel) throws Exception; ConnectedTerminalsResponse getConnectedTerminals() throws IOException, ApiException ;
// Path: adyenv6core/src/com/adyen/v6/model/RequestInfo.java // public class RequestInfo { // // public static final String USER_AGENT_HEADER = "User-Agent"; // public static final String ACCEPT_HEADER = "Accept"; // // private String userAgent; // private String acceptHeader; // private String shopperIp; // private String origin; // private String shopperLocale; // // public RequestInfo(HttpServletRequest request) { // this.userAgent = request.getHeader(USER_AGENT_HEADER); // this.acceptHeader = request.getHeader(ACCEPT_HEADER); // this.shopperIp = request.getRemoteAddr(); // this.origin = getOrigin(request); // } // // private RequestInfo() { // } // // public String getOrigin(HttpServletRequest request) { // String currentRequestURL = request.getRequestURL().toString(); // int requestUrlLength = currentRequestURL.length(); // int requestUriLength = request.getRequestURI().length(); // // String baseURL = currentRequestURL.substring(0, requestUrlLength - requestUriLength); // return baseURL; // } // // public String getOrigin() { // return this.origin; // } // // public static RequestInfo empty() { // return new RequestInfo(); // } // // public String getUserAgent() { // return userAgent; // } // // public String getAcceptHeader() { // return acceptHeader; // } // // public String getShopperIp() { // return shopperIp; // } // // public String getShopperLocale() { // return shopperLocale; // } // // public void setShopperLocale(String shopperLocale) { // this.shopperLocale = shopperLocale; // } // } // Path: adyenv6core/src/com/adyen/v6/service/AdyenPaymentService.java import com.adyen.httpclient.HTTPClientException; import com.adyen.model.PaymentResult; import com.adyen.model.checkout.PaymentMethod; import com.adyen.model.checkout.PaymentMethodDetails; import com.adyen.model.checkout.PaymentMethodsResponse; import com.adyen.model.checkout.PaymentsDetailsResponse; import com.adyen.model.checkout.PaymentsResponse; import com.adyen.model.modification.ModificationResult; import com.adyen.model.recurring.RecurringDetail; import com.adyen.model.terminal.ConnectedTerminalsResponse; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.service.exception.ApiException; import com.adyen.v6.model.RequestInfo; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.core.model.user.CustomerModel; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.security.SignatureException; import java.util.Currency; import java.util.HashMap; import java.util.List; import java.util.Map; /* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.service; public interface AdyenPaymentService { /** * Performs authorization request via Adyen API */ PaymentResult authorise(CartData cartData, HttpServletRequest request, CustomerModel customerModel) throws Exception; ConnectedTerminalsResponse getConnectedTerminals() throws IOException, ApiException ;
PaymentsResponse authorisePayment(CartData cartData, RequestInfo requestInfo, CustomerModel customerModel) throws Exception;
Adyen/adyen-hybris
adyenv6ordermanagement/testsrc/com/adyen/v6/actions/returns/AdyenCaptureRefundActionTest.java
// Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java // abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> { // public enum Transition { // OK, NOK, WAIT; // // public static Set<String> getStringValues() { // Set<String> res = new HashSet<>(); // for (final Transition transitions : Transition.values()) { // res.add(transitions.toString()); // } // return res; // } // } // // @Override // public Set<String> getTransitions() { // return Transition.getStringValues(); // } // } // // Path: adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java // public class AbstractActionTest { // protected PaymentTransactionEntryModel createAuthorizedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createAuthorizedRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureReceivedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // // return entry; // } // // protected PaymentTransactionModel createAdyenTransaction() { // PaymentTransactionModel adyenTransaction = new PaymentTransactionModel(); // adyenTransaction.setPaymentProvider(PAYMENT_PROVIDER); // adyenTransaction.setEntries(new ArrayList<>()); // // return adyenTransaction; // } // }
import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.actions.order.AbstractActionTest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.basecommerce.enums.ReturnStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.returns.model.ReturnEntryModel; import de.hybris.platform.returns.model.ReturnProcessModel; import de.hybris.platform.returns.model.ReturnRequestModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.warehousing.returns.service.RefundAmountCalculationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.actions.returns; /** * Tests AdyenCheckCaptureAction */ @UnitTest @RunWith(MockitoJUnitRunner.class)
// Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java // abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> { // public enum Transition { // OK, NOK, WAIT; // // public static Set<String> getStringValues() { // Set<String> res = new HashSet<>(); // for (final Transition transitions : Transition.values()) { // res.add(transitions.toString()); // } // return res; // } // } // // @Override // public Set<String> getTransitions() { // return Transition.getStringValues(); // } // } // // Path: adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java // public class AbstractActionTest { // protected PaymentTransactionEntryModel createAuthorizedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createAuthorizedRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureReceivedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // // return entry; // } // // protected PaymentTransactionModel createAdyenTransaction() { // PaymentTransactionModel adyenTransaction = new PaymentTransactionModel(); // adyenTransaction.setPaymentProvider(PAYMENT_PROVIDER); // adyenTransaction.setEntries(new ArrayList<>()); // // return adyenTransaction; // } // } // Path: adyenv6ordermanagement/testsrc/com/adyen/v6/actions/returns/AdyenCaptureRefundActionTest.java import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.actions.order.AbstractActionTest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.basecommerce.enums.ReturnStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.returns.model.ReturnEntryModel; import de.hybris.platform.returns.model.ReturnProcessModel; import de.hybris.platform.returns.model.ReturnRequestModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.warehousing.returns.service.RefundAmountCalculationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; /* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.actions.returns; /** * Tests AdyenCheckCaptureAction */ @UnitTest @RunWith(MockitoJUnitRunner.class)
public class AdyenCaptureRefundActionTest extends AbstractActionTest {
Adyen/adyen-hybris
adyenv6ordermanagement/testsrc/com/adyen/v6/actions/returns/AdyenCaptureRefundActionTest.java
// Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java // abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> { // public enum Transition { // OK, NOK, WAIT; // // public static Set<String> getStringValues() { // Set<String> res = new HashSet<>(); // for (final Transition transitions : Transition.values()) { // res.add(transitions.toString()); // } // return res; // } // } // // @Override // public Set<String> getTransitions() { // return Transition.getStringValues(); // } // } // // Path: adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java // public class AbstractActionTest { // protected PaymentTransactionEntryModel createAuthorizedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createAuthorizedRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureReceivedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // // return entry; // } // // protected PaymentTransactionModel createAdyenTransaction() { // PaymentTransactionModel adyenTransaction = new PaymentTransactionModel(); // adyenTransaction.setPaymentProvider(PAYMENT_PROVIDER); // adyenTransaction.setEntries(new ArrayList<>()); // // return adyenTransaction; // } // }
import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.actions.order.AbstractActionTest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.basecommerce.enums.ReturnStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.returns.model.ReturnEntryModel; import de.hybris.platform.returns.model.ReturnProcessModel; import de.hybris.platform.returns.model.ReturnRequestModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.warehousing.returns.service.RefundAmountCalculationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
when(returnRequestModelMock.getOrder()).thenReturn(orderModelMock); when(returnRequestModelMock.getReturnEntries()).thenReturn(new ArrayList<ReturnEntryModel>()); when(returnProcessModelMock.getReturnRequest()).thenReturn(returnRequestModelMock); when(returnProcessModelMock.getCode()).thenReturn("1234"); when(refundAmountCalculationServiceMock.getCustomRefundAmount(returnRequestModelMock)) .thenReturn(null); originalRefundAmount = new BigDecimal("12.34"); when(refundAmountCalculationServiceMock.getOriginalRefundAmount(returnRequestModelMock)) .thenReturn(originalRefundAmount); adyenCaptureRefundAction = new AdyenCaptureRefundAction(); adyenCaptureRefundAction.setPaymentService(paymentServiceMock); adyenCaptureRefundAction.setRefundAmountCalculationService(refundAmountCalculationServiceMock); adyenCaptureRefundAction.setModelService(modelServiceMock); } /** * when no transactions at all * fail to refund */ @Test public void testNoTransactions() { List<PaymentTransactionModel> transactions = new ArrayList<>(); when(orderModelMock.getPaymentTransactions()).thenReturn(transactions); assertEquals(
// Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java // abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> { // public enum Transition { // OK, NOK, WAIT; // // public static Set<String> getStringValues() { // Set<String> res = new HashSet<>(); // for (final Transition transitions : Transition.values()) { // res.add(transitions.toString()); // } // return res; // } // } // // @Override // public Set<String> getTransitions() { // return Transition.getStringValues(); // } // } // // Path: adyenv6core/testsrc/com/adyen/v6/actions/order/AbstractActionTest.java // public class AbstractActionTest { // protected PaymentTransactionEntryModel createAuthorizedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createAuthorizedRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.AUTHORIZATION); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureReceivedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // entry.setAmount(new BigDecimal("12.34")); // // return entry; // } // // protected PaymentTransactionEntryModel createCaptureRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.CAPTURE); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.GENERAL_SYSTEM_ERROR.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundRejectedEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.REJECTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE.name()); // // return entry; // } // // protected PaymentTransactionEntryModel createRefundSuccessEntry() { // PaymentTransactionEntryModel entry = new PaymentTransactionEntryModel(); // entry.setType(PaymentTransactionType.REFUND_FOLLOW_ON); // entry.setTransactionStatus(TransactionStatus.ACCEPTED.name()); // entry.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name()); // // return entry; // } // // protected PaymentTransactionModel createAdyenTransaction() { // PaymentTransactionModel adyenTransaction = new PaymentTransactionModel(); // adyenTransaction.setPaymentProvider(PAYMENT_PROVIDER); // adyenTransaction.setEntries(new ArrayList<>()); // // return adyenTransaction; // } // } // Path: adyenv6ordermanagement/testsrc/com/adyen/v6/actions/returns/AdyenCaptureRefundActionTest.java import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.actions.order.AbstractActionTest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.basecommerce.enums.ReturnStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.PaymentService; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.returns.model.ReturnEntryModel; import de.hybris.platform.returns.model.ReturnProcessModel; import de.hybris.platform.returns.model.ReturnRequestModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.warehousing.returns.service.RefundAmountCalculationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; when(returnRequestModelMock.getOrder()).thenReturn(orderModelMock); when(returnRequestModelMock.getReturnEntries()).thenReturn(new ArrayList<ReturnEntryModel>()); when(returnProcessModelMock.getReturnRequest()).thenReturn(returnRequestModelMock); when(returnProcessModelMock.getCode()).thenReturn("1234"); when(refundAmountCalculationServiceMock.getCustomRefundAmount(returnRequestModelMock)) .thenReturn(null); originalRefundAmount = new BigDecimal("12.34"); when(refundAmountCalculationServiceMock.getOriginalRefundAmount(returnRequestModelMock)) .thenReturn(originalRefundAmount); adyenCaptureRefundAction = new AdyenCaptureRefundAction(); adyenCaptureRefundAction.setPaymentService(paymentServiceMock); adyenCaptureRefundAction.setRefundAmountCalculationService(refundAmountCalculationServiceMock); adyenCaptureRefundAction.setModelService(modelServiceMock); } /** * when no transactions at all * fail to refund */ @Test public void testNoTransactions() { List<PaymentTransactionModel> transactions = new ArrayList<>(); when(orderModelMock.getPaymentTransactions()).thenReturn(transactions); assertEquals(
AbstractWaitableAction.Transition.NOK.toString(),
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/ui/fragment/WriteIpAddressFragment.java
// Path: app/src/main/java/pl/hypeapp/endoscope/presenter/WriteIpAddressPresenter.java // public class WriteIpAddressPresenter extends TiPresenter<WriteIpAddressView> { // // public void validateIpAddress(String streamIpAddress) { // if (Patterns.IP_ADDRESS.matcher(streamIpAddress).matches()) { // getView().intentToPlayStreamActivity(streamIpAddress); // } else { // getView().onWrongIpAddress(); // } // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/activity/ConnectToStreamActivity.java // public class ConnectToStreamActivity extends TiActivity<ConnectToStreamPresenter, ConnectToStreamView> // implements ConnectToStreamView { // public static final int PAGE_INPUT = 0; // public static final int PAGE_QR_CODE = 1; // public static final int PAGE_NFC = 2; // public static final String INTENT_EXTRA_IP_CONNECT = "ip_connect"; // private ViewPager viewPager; // private WiFiStateChangeReceiver wiFiStateChangeReceiver = new WiFiStateChangeReceiver(); // @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3}) List<ImageView> dots; // private ConnectToStreamPagerAdapter connectToStreamPagerAdapter; // // @NonNull // @Override // public ConnectToStreamPresenter providePresenter() { // return new ConnectToStreamPresenter(); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_connect_stream); // ButterKnife.bind(this); // initViewPager(); // registerReceivers(); // } // // @Override // protected void onResume() { // super.onResume(); // getPresenter().onIntent(getIntent()); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // unregisterReceiver(wiFiStateChangeReceiver); // } // // @Override // protected void onNewIntent(Intent intent) { // getPresenter().onIntent(intent); // } // // @Override // public void passIntentToNfcReader(Intent intent) { // Fragment fragment = connectToStreamPagerAdapter.getItem(PAGE_NFC); // if (fragment instanceof NfcReaderFragment) { // NfcReaderFragment nfcReaderFragment = (NfcReaderFragment) fragment; // nfcReaderFragment.onNfcIntent(intent); // } // } // // @Override // @OnClick(R.id.input_layout) // public void SlideToInputPage() { // viewPager.setCurrentItem(PAGE_INPUT); // } // // @Override // @OnClick(R.id.qr_code_layout) // public void SlideToQrCodePage() { // viewPager.setCurrentItem(PAGE_QR_CODE); // } // // @Override // @OnClick(R.id.nfc_layout) // public void SlideToNfcPage() { // viewPager.setCurrentItem(PAGE_NFC); // } // // @Override // public void intentToPlayStreamActivity(String ipAddress) { // Intent i = new Intent(ConnectToStreamActivity.this, PlayStreamActivity.class); // i.putExtra(INTENT_EXTRA_IP_CONNECT, ipAddress); // startActivity(i); // } // // @Override // public void onBackPressed() { // Intent i = new Intent(ConnectToStreamActivity.this, MainMenuActivity.class); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(i); // } // // private void initViewPager() { // viewPager = (ViewPager) findViewById(R.id.about_connect_pager); // connectToStreamPagerAdapter = new ConnectToStreamPagerAdapter(getSupportFragmentManager()); // viewPager.addOnPageChangeListener(new OnDotPageChangeListener(dots)); // viewPager.setAdapter(connectToStreamPagerAdapter); // } // // private void registerReceivers() { // registerReceiver(wiFiStateChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); // registerReceiver(wiFiStateChangeReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/view/WriteIpAddressView.java // public interface WriteIpAddressView extends TiView { // // @CallOnMainThread // void intentToPlayStreamActivity(String ipAddress); // // @CallOnMainThread // void onWrongIpAddress(); // }
import android.os.Bundle; import android.support.annotation.NonNull; import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import net.grandcentrix.thirtyinch.TiFragment; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.presenter.WriteIpAddressPresenter; import pl.hypeapp.endoscope.ui.activity.ConnectToStreamActivity; import pl.hypeapp.endoscope.view.WriteIpAddressView;
package pl.hypeapp.endoscope.ui.fragment; public class WriteIpAddressFragment extends TiFragment<WriteIpAddressPresenter, WriteIpAddressView> implements WriteIpAddressView { @BindView(R.id.ip_edit_text) EditText inputIpAddress; @NonNull @Override public WriteIpAddressPresenter providePresenter() { return new WriteIpAddressPresenter(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_write_ip, container, false); ButterKnife.bind(this, v); int inputMaxLength = 15; inputIpAddress.setFilters(new InputFilter[]{new InputFilter.LengthFilter(inputMaxLength)}); return v; } @OnClick(R.id.connect_button) public void onClickConnect() { String streamIpAddress = inputIpAddress.getText().toString(); getPresenter().validateIpAddress(streamIpAddress); } @Override public void intentToPlayStreamActivity(String ipAddress) {
// Path: app/src/main/java/pl/hypeapp/endoscope/presenter/WriteIpAddressPresenter.java // public class WriteIpAddressPresenter extends TiPresenter<WriteIpAddressView> { // // public void validateIpAddress(String streamIpAddress) { // if (Patterns.IP_ADDRESS.matcher(streamIpAddress).matches()) { // getView().intentToPlayStreamActivity(streamIpAddress); // } else { // getView().onWrongIpAddress(); // } // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/activity/ConnectToStreamActivity.java // public class ConnectToStreamActivity extends TiActivity<ConnectToStreamPresenter, ConnectToStreamView> // implements ConnectToStreamView { // public static final int PAGE_INPUT = 0; // public static final int PAGE_QR_CODE = 1; // public static final int PAGE_NFC = 2; // public static final String INTENT_EXTRA_IP_CONNECT = "ip_connect"; // private ViewPager viewPager; // private WiFiStateChangeReceiver wiFiStateChangeReceiver = new WiFiStateChangeReceiver(); // @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3}) List<ImageView> dots; // private ConnectToStreamPagerAdapter connectToStreamPagerAdapter; // // @NonNull // @Override // public ConnectToStreamPresenter providePresenter() { // return new ConnectToStreamPresenter(); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_connect_stream); // ButterKnife.bind(this); // initViewPager(); // registerReceivers(); // } // // @Override // protected void onResume() { // super.onResume(); // getPresenter().onIntent(getIntent()); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // unregisterReceiver(wiFiStateChangeReceiver); // } // // @Override // protected void onNewIntent(Intent intent) { // getPresenter().onIntent(intent); // } // // @Override // public void passIntentToNfcReader(Intent intent) { // Fragment fragment = connectToStreamPagerAdapter.getItem(PAGE_NFC); // if (fragment instanceof NfcReaderFragment) { // NfcReaderFragment nfcReaderFragment = (NfcReaderFragment) fragment; // nfcReaderFragment.onNfcIntent(intent); // } // } // // @Override // @OnClick(R.id.input_layout) // public void SlideToInputPage() { // viewPager.setCurrentItem(PAGE_INPUT); // } // // @Override // @OnClick(R.id.qr_code_layout) // public void SlideToQrCodePage() { // viewPager.setCurrentItem(PAGE_QR_CODE); // } // // @Override // @OnClick(R.id.nfc_layout) // public void SlideToNfcPage() { // viewPager.setCurrentItem(PAGE_NFC); // } // // @Override // public void intentToPlayStreamActivity(String ipAddress) { // Intent i = new Intent(ConnectToStreamActivity.this, PlayStreamActivity.class); // i.putExtra(INTENT_EXTRA_IP_CONNECT, ipAddress); // startActivity(i); // } // // @Override // public void onBackPressed() { // Intent i = new Intent(ConnectToStreamActivity.this, MainMenuActivity.class); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(i); // } // // private void initViewPager() { // viewPager = (ViewPager) findViewById(R.id.about_connect_pager); // connectToStreamPagerAdapter = new ConnectToStreamPagerAdapter(getSupportFragmentManager()); // viewPager.addOnPageChangeListener(new OnDotPageChangeListener(dots)); // viewPager.setAdapter(connectToStreamPagerAdapter); // } // // private void registerReceivers() { // registerReceiver(wiFiStateChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); // registerReceiver(wiFiStateChangeReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/view/WriteIpAddressView.java // public interface WriteIpAddressView extends TiView { // // @CallOnMainThread // void intentToPlayStreamActivity(String ipAddress); // // @CallOnMainThread // void onWrongIpAddress(); // } // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/WriteIpAddressFragment.java import android.os.Bundle; import android.support.annotation.NonNull; import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import net.grandcentrix.thirtyinch.TiFragment; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.presenter.WriteIpAddressPresenter; import pl.hypeapp.endoscope.ui.activity.ConnectToStreamActivity; import pl.hypeapp.endoscope.view.WriteIpAddressView; package pl.hypeapp.endoscope.ui.fragment; public class WriteIpAddressFragment extends TiFragment<WriteIpAddressPresenter, WriteIpAddressView> implements WriteIpAddressView { @BindView(R.id.ip_edit_text) EditText inputIpAddress; @NonNull @Override public WriteIpAddressPresenter providePresenter() { return new WriteIpAddressPresenter(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_write_ip, container, false); ButterKnife.bind(this, v); int inputMaxLength = 15; inputIpAddress.setFilters(new InputFilter[]{new InputFilter.LengthFilter(inputMaxLength)}); return v; } @OnClick(R.id.connect_button) public void onClickConnect() { String streamIpAddress = inputIpAddress.getText().toString(); getPresenter().validateIpAddress(streamIpAddress); } @Override public void intentToPlayStreamActivity(String ipAddress) {
ConnectToStreamActivity connectToStreamActivity = (ConnectToStreamActivity) getActivity();
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/ui/activity/HowToUseActivity.java
// Path: app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java // public class HowToUsePagerAdapter extends FragmentPagerAdapter { // private static final int HOW_TO_USE_PAGES = 4; // // public HowToUsePagerAdapter(FragmentManager fm){ // super(fm); // } // // @Override // public Fragment getItem(int position) { // return HowToUseFragmentFactory.newInstance(position); // } // // @Override // public int getCount() { // return HOW_TO_USE_PAGES; // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/listener/OnDotPageChangeListener.java // public class OnDotPageChangeListener implements ViewPager.OnPageChangeListener { // private List<ImageView> dots = new ArrayList<>(); // private ImageView nextPageButton; // private TextView skipButton; // private TextView doneButton; // // public OnDotPageChangeListener(List<ImageView> dots) { // this.dots = dots; // } // // public OnDotPageChangeListener(List<ImageView> dots, // ImageView nextPageButton, TextView skipButton, TextView doneButton) { // this(dots); // this.nextPageButton = nextPageButton; // this.skipButton = skipButton; // this.doneButton = doneButton; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // changeDotFocus(position); // viewDoneButton(position); // viewSkipButton(position); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // private void changeDotFocus(int position) { // for (ImageView dot : dots) { // int dotPosition = Integer.parseInt(dot.getTag().toString()); // if (dotPosition == position) { // setActiveDot(dot); // } else { // setInactiveDot(dot); // } // } // } // // private void setActiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_active); // } // // private void setInactiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_inactive); // } // // private void viewDoneButton(int position) { // if ((nextPageButton != null) && (doneButton != null)) { // if (position < 3) { // nextPageButton.setVisibility(View.VISIBLE); // doneButton.setVisibility(View.GONE); // } else { // nextPageButton.setVisibility(View.GONE); // doneButton.setVisibility(View.VISIBLE); // } // } // } // // private void viewSkipButton(int position) { // if (skipButton != null) { // if (position > 0) { // skipButton.setVisibility(View.GONE); // } else { // skipButton.setVisibility(View.VISIBLE); // } // } // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.adapter.HowToUsePagerAdapter; import pl.hypeapp.endoscope.ui.listener.OnDotPageChangeListener;
package pl.hypeapp.endoscope.ui.activity; public class HowToUseActivity extends AppCompatActivity { public static final int LAST_PAGE = 3; private ViewPager viewPager; @BindView(R.id.next_page_button) ImageView nextPageButton; @BindView(R.id.skip_button) TextView skipButton; @BindView(R.id.done_button) TextView doneButton; @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3, R.id.circle_page4}) List<ImageView> dots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_how_to_use); ButterKnife.bind(this); initViewPager(); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.how_to_use_pager);
// Path: app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java // public class HowToUsePagerAdapter extends FragmentPagerAdapter { // private static final int HOW_TO_USE_PAGES = 4; // // public HowToUsePagerAdapter(FragmentManager fm){ // super(fm); // } // // @Override // public Fragment getItem(int position) { // return HowToUseFragmentFactory.newInstance(position); // } // // @Override // public int getCount() { // return HOW_TO_USE_PAGES; // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/listener/OnDotPageChangeListener.java // public class OnDotPageChangeListener implements ViewPager.OnPageChangeListener { // private List<ImageView> dots = new ArrayList<>(); // private ImageView nextPageButton; // private TextView skipButton; // private TextView doneButton; // // public OnDotPageChangeListener(List<ImageView> dots) { // this.dots = dots; // } // // public OnDotPageChangeListener(List<ImageView> dots, // ImageView nextPageButton, TextView skipButton, TextView doneButton) { // this(dots); // this.nextPageButton = nextPageButton; // this.skipButton = skipButton; // this.doneButton = doneButton; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // changeDotFocus(position); // viewDoneButton(position); // viewSkipButton(position); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // private void changeDotFocus(int position) { // for (ImageView dot : dots) { // int dotPosition = Integer.parseInt(dot.getTag().toString()); // if (dotPosition == position) { // setActiveDot(dot); // } else { // setInactiveDot(dot); // } // } // } // // private void setActiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_active); // } // // private void setInactiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_inactive); // } // // private void viewDoneButton(int position) { // if ((nextPageButton != null) && (doneButton != null)) { // if (position < 3) { // nextPageButton.setVisibility(View.VISIBLE); // doneButton.setVisibility(View.GONE); // } else { // nextPageButton.setVisibility(View.GONE); // doneButton.setVisibility(View.VISIBLE); // } // } // } // // private void viewSkipButton(int position) { // if (skipButton != null) { // if (position > 0) { // skipButton.setVisibility(View.GONE); // } else { // skipButton.setVisibility(View.VISIBLE); // } // } // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/ui/activity/HowToUseActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.adapter.HowToUsePagerAdapter; import pl.hypeapp.endoscope.ui.listener.OnDotPageChangeListener; package pl.hypeapp.endoscope.ui.activity; public class HowToUseActivity extends AppCompatActivity { public static final int LAST_PAGE = 3; private ViewPager viewPager; @BindView(R.id.next_page_button) ImageView nextPageButton; @BindView(R.id.skip_button) TextView skipButton; @BindView(R.id.done_button) TextView doneButton; @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3, R.id.circle_page4}) List<ImageView> dots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_how_to_use); ButterKnife.bind(this); initViewPager(); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.how_to_use_pager);
HowToUsePagerAdapter pagerAdapter = new HowToUsePagerAdapter(getSupportFragmentManager());
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/ui/activity/HowToUseActivity.java
// Path: app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java // public class HowToUsePagerAdapter extends FragmentPagerAdapter { // private static final int HOW_TO_USE_PAGES = 4; // // public HowToUsePagerAdapter(FragmentManager fm){ // super(fm); // } // // @Override // public Fragment getItem(int position) { // return HowToUseFragmentFactory.newInstance(position); // } // // @Override // public int getCount() { // return HOW_TO_USE_PAGES; // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/listener/OnDotPageChangeListener.java // public class OnDotPageChangeListener implements ViewPager.OnPageChangeListener { // private List<ImageView> dots = new ArrayList<>(); // private ImageView nextPageButton; // private TextView skipButton; // private TextView doneButton; // // public OnDotPageChangeListener(List<ImageView> dots) { // this.dots = dots; // } // // public OnDotPageChangeListener(List<ImageView> dots, // ImageView nextPageButton, TextView skipButton, TextView doneButton) { // this(dots); // this.nextPageButton = nextPageButton; // this.skipButton = skipButton; // this.doneButton = doneButton; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // changeDotFocus(position); // viewDoneButton(position); // viewSkipButton(position); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // private void changeDotFocus(int position) { // for (ImageView dot : dots) { // int dotPosition = Integer.parseInt(dot.getTag().toString()); // if (dotPosition == position) { // setActiveDot(dot); // } else { // setInactiveDot(dot); // } // } // } // // private void setActiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_active); // } // // private void setInactiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_inactive); // } // // private void viewDoneButton(int position) { // if ((nextPageButton != null) && (doneButton != null)) { // if (position < 3) { // nextPageButton.setVisibility(View.VISIBLE); // doneButton.setVisibility(View.GONE); // } else { // nextPageButton.setVisibility(View.GONE); // doneButton.setVisibility(View.VISIBLE); // } // } // } // // private void viewSkipButton(int position) { // if (skipButton != null) { // if (position > 0) { // skipButton.setVisibility(View.GONE); // } else { // skipButton.setVisibility(View.VISIBLE); // } // } // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.adapter.HowToUsePagerAdapter; import pl.hypeapp.endoscope.ui.listener.OnDotPageChangeListener;
package pl.hypeapp.endoscope.ui.activity; public class HowToUseActivity extends AppCompatActivity { public static final int LAST_PAGE = 3; private ViewPager viewPager; @BindView(R.id.next_page_button) ImageView nextPageButton; @BindView(R.id.skip_button) TextView skipButton; @BindView(R.id.done_button) TextView doneButton; @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3, R.id.circle_page4}) List<ImageView> dots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_how_to_use); ButterKnife.bind(this); initViewPager(); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.how_to_use_pager); HowToUsePagerAdapter pagerAdapter = new HowToUsePagerAdapter(getSupportFragmentManager());
// Path: app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java // public class HowToUsePagerAdapter extends FragmentPagerAdapter { // private static final int HOW_TO_USE_PAGES = 4; // // public HowToUsePagerAdapter(FragmentManager fm){ // super(fm); // } // // @Override // public Fragment getItem(int position) { // return HowToUseFragmentFactory.newInstance(position); // } // // @Override // public int getCount() { // return HOW_TO_USE_PAGES; // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/listener/OnDotPageChangeListener.java // public class OnDotPageChangeListener implements ViewPager.OnPageChangeListener { // private List<ImageView> dots = new ArrayList<>(); // private ImageView nextPageButton; // private TextView skipButton; // private TextView doneButton; // // public OnDotPageChangeListener(List<ImageView> dots) { // this.dots = dots; // } // // public OnDotPageChangeListener(List<ImageView> dots, // ImageView nextPageButton, TextView skipButton, TextView doneButton) { // this(dots); // this.nextPageButton = nextPageButton; // this.skipButton = skipButton; // this.doneButton = doneButton; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // changeDotFocus(position); // viewDoneButton(position); // viewSkipButton(position); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // private void changeDotFocus(int position) { // for (ImageView dot : dots) { // int dotPosition = Integer.parseInt(dot.getTag().toString()); // if (dotPosition == position) { // setActiveDot(dot); // } else { // setInactiveDot(dot); // } // } // } // // private void setActiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_active); // } // // private void setInactiveDot(ImageView dot) { // dot.setImageResource(R.drawable.circle_shape_inactive); // } // // private void viewDoneButton(int position) { // if ((nextPageButton != null) && (doneButton != null)) { // if (position < 3) { // nextPageButton.setVisibility(View.VISIBLE); // doneButton.setVisibility(View.GONE); // } else { // nextPageButton.setVisibility(View.GONE); // doneButton.setVisibility(View.VISIBLE); // } // } // } // // private void viewSkipButton(int position) { // if (skipButton != null) { // if (position > 0) { // skipButton.setVisibility(View.GONE); // } else { // skipButton.setVisibility(View.VISIBLE); // } // } // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/ui/activity/HowToUseActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import pl.hypeapp.endoscope.R; import pl.hypeapp.endoscope.adapter.HowToUsePagerAdapter; import pl.hypeapp.endoscope.ui.listener.OnDotPageChangeListener; package pl.hypeapp.endoscope.ui.activity; public class HowToUseActivity extends AppCompatActivity { public static final int LAST_PAGE = 3; private ViewPager viewPager; @BindView(R.id.next_page_button) ImageView nextPageButton; @BindView(R.id.skip_button) TextView skipButton; @BindView(R.id.done_button) TextView doneButton; @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3, R.id.circle_page4}) List<ImageView> dots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_how_to_use); ButterKnife.bind(this); initViewPager(); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.how_to_use_pager); HowToUsePagerAdapter pagerAdapter = new HowToUsePagerAdapter(getSupportFragmentManager());
viewPager.addOnPageChangeListener(new OnDotPageChangeListener(dots, nextPageButton, skipButton, doneButton));
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/HowToUseFragmentFactory.java // public class HowToUseFragmentFactory extends Fragment { // // public static HowToUseFragmentFactory newInstance(int position) { // Bundle args = new Bundle(); // HowToUseFragmentFactory fragment = new HowToUseFragmentFactory(); // args.putInt("htu_fragment", position); // fragment.setArguments(args); // return fragment; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // int layoutResource = getProperLayout(getArguments().getInt("htu_fragment", 0)); // View v = inflater.inflate(layoutResource, container, false); // return v; // } // // int getProperLayout(int position) { // switch (position) { // case 0: // return R.layout.fragment_htu1; // case 1: // return R.layout.fragment_htu2; // case 2: // return R.layout.fragment_htu3; // case 3: // return R.layout.fragment_htu4; // } // return 0; // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.HowToUseFragmentFactory;
package pl.hypeapp.endoscope.adapter; public class HowToUsePagerAdapter extends FragmentPagerAdapter { private static final int HOW_TO_USE_PAGES = 4; public HowToUsePagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) {
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/HowToUseFragmentFactory.java // public class HowToUseFragmentFactory extends Fragment { // // public static HowToUseFragmentFactory newInstance(int position) { // Bundle args = new Bundle(); // HowToUseFragmentFactory fragment = new HowToUseFragmentFactory(); // args.putInt("htu_fragment", position); // fragment.setArguments(args); // return fragment; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // int layoutResource = getProperLayout(getArguments().getInt("htu_fragment", 0)); // View v = inflater.inflate(layoutResource, container, false); // return v; // } // // int getProperLayout(int position) { // switch (position) { // case 0: // return R.layout.fragment_htu1; // case 1: // return R.layout.fragment_htu2; // case 2: // return R.layout.fragment_htu3; // case 3: // return R.layout.fragment_htu4; // } // return 0; // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/adapter/HowToUsePagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.HowToUseFragmentFactory; package pl.hypeapp.endoscope.adapter; public class HowToUsePagerAdapter extends FragmentPagerAdapter { private static final int HOW_TO_USE_PAGES = 4; public HowToUsePagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) {
return HowToUseFragmentFactory.newInstance(position);
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment;
package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0:
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment; package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0:
return new IpAddressFragment();
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment;
package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return new IpAddressFragment(); case 1:
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment; package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return new IpAddressFragment(); case 1:
return new QrCodeFragment();
hypeapps/Endoscope
app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment;
package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return new IpAddressFragment(); case 1: return new QrCodeFragment(); case 2:
// Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/IpAddressFragment.java // public class IpAddressFragment extends TiFragment<IpAddressPresenter, IpAddressView> implements IpAddressView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.ip_address) TextView ipAddressTextView; // // @NonNull // @Override // public IpAddressPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new IpAddressPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_ip_address, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setIpAddress(String ipAddress) { // ipAddressTextView.setText(ipAddress); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/NfcFragment.java // public class NfcFragment extends TiFragment<NfcPresenter, NfcView> implements NfcView, NfcAdapter.CreateNdefMessageCallback { // private static final String IP_DEFAULT = "255.255.255.255"; // // @NonNull // @Override // public NfcPresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new NfcPresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_stream_nfc, container, false); // } // // @Override // public void initNfcAdapter() { // NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); // if (nfcAdapter != null) { // nfcAdapter.setNdefPushMessageCallback(this, getActivity()); // nfcAdapter.disableForegroundDispatch(getActivity()); // } // } // // @Override // public NdefMessage createNdefMessage(NfcEvent nfcEvent) { // NdefRecord[] recordsToAttach = getPresenter().createRecords(); // //When creating an NdefMessage we need to provide an NdefRecord[] // return new NdefMessage(recordsToAttach); // } // } // // Path: app/src/main/java/pl/hypeapp/endoscope/ui/fragment/QrCodeFragment.java // public class QrCodeFragment extends TiFragment<QrCodePresenter, QrCodeView> implements QrCodeView { // private static final String IP_DEFAULT = "255.255.255.255"; // @BindView(R.id.qr_code) ImageView qrCodeContainer; // // @NonNull // @Override // public QrCodePresenter providePresenter() { // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // String ipAddress = sharedPreferences.getString("ip_local", IP_DEFAULT); // return new QrCodePresenter(ipAddress); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View v = inflater.inflate(R.layout.fragment_stream_qrcode, container, false); // ButterKnife.bind(this, v); // return v; // } // // @Override // public void setQrCodeBitmap(Bitmap qrCodeBitmap) { // qrCodeContainer.setImageBitmap(qrCodeBitmap); // } // } // Path: app/src/main/java/pl/hypeapp/endoscope/adapter/StartStreamPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import pl.hypeapp.endoscope.ui.fragment.IpAddressFragment; import pl.hypeapp.endoscope.ui.fragment.NfcFragment; import pl.hypeapp.endoscope.ui.fragment.QrCodeFragment; package pl.hypeapp.endoscope.adapter; public class StartStreamPagerAdapter extends FragmentPagerAdapter { public StartStreamPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return new IpAddressFragment(); case 1: return new QrCodeFragment(); case 2:
return new NfcFragment();
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/utils/FakePagerDutyEventsClientTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.domain.*; import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.utils; public class FakePagerDutyEventsClientTest { private final FakePagerDutyEventsClient fakePagerDutyEventsClient = FakePagerDutyEventsClient.create(); private Payload payload; private final String ROUTING_KEY = "ROUTING_KEY"; private final String DEDUP_KEY = "DedupKey"; @Before public void setup() { payload = Payload.Builder.newBuilder() .setSource("testing host") .setSeverity(Severity.INFO) .setSummary("This is an incident test to test PagerDutyEventsClient") .build(); } @Test
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/utils/FakePagerDutyEventsClientTest.java import com.github.dikhan.pagerduty.client.events.domain.*; import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.utils; public class FakePagerDutyEventsClientTest { private final FakePagerDutyEventsClient fakePagerDutyEventsClient = FakePagerDutyEventsClient.create(); private Payload payload; private final String ROUTING_KEY = "ROUTING_KEY"; private final String DEDUP_KEY = "DedupKey"; @Before public void setup() { payload = Payload.Builder.newBuilder() .setSource("testing host") .setSeverity(Severity.INFO) .setSummary("This is an incident test to test PagerDutyEventsClient") .build(); } @Test
public void triggerIncident() throws NotifyEventException {
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/utils/EventHelper.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/domain/EventResult.java // public class EventResult { // // private final String status; // private final String message; // private final String dedupKey; // private final String errors; // // private EventResult(EventResultBuilder eventResultBuilder) { // this.status = eventResultBuilder.getStatus(); // this.message = eventResultBuilder.getMessage(); // this.dedupKey = eventResultBuilder.getDedupKey(); // this.errors = eventResultBuilder.getErrors(); // } // // public static EventResult successEvent(String status, String message, String dedupKey) { // return new EventResultBuilder(status, message).success(dedupKey).build(); // } // // public static EventResult errorEvent(String status, String message, String errors) { // return new EventResultBuilder(status, message).error(errors).build(); // } // // public String getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getDedupKey() { // return dedupKey; // } // // public String getErrors() { // return errors; // } // // private static class EventResultBuilder { // private final String status; // private final String message; // private String dedupKey; // private String errors; // // public EventResultBuilder(String status, String message) { // this.status = status; // this.message = message; // } // // public EventResultBuilder success(String dedupKey) { // this.dedupKey = dedupKey; // return this; // } // // public EventResultBuilder error(String errors) { // this.errors = errors; // return this; // } // // public String getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getDedupKey() { // return dedupKey; // } // // public String getErrors() { // return errors; // } // // public EventResult build() { // return new EventResult(this); // } // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EventResult that = (EventResult) o; // // if (status != null ? !status.equals(that.status) : that.status != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // if (dedupKey != null ? !dedupKey.equals(that.dedupKey) : that.dedupKey != null) return false; // return !(errors != null ? !errors.equals(that.errors) : that.errors != null); // // } // // @Override // public int hashCode() { // int result = status != null ? status.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // result = 31 * result + (dedupKey != null ? dedupKey.hashCode() : 0); // result = 31 * result + (errors != null ? errors.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "EventResult{" + // "status='" + status + '\'' + // ", message='" + message + '\'' + // ", dedupKey='" + dedupKey + '\'' + // ", errors='" + errors + '\'' + // '}'; // } // }
import com.github.dikhan.pagerduty.client.events.domain.EventResult; import org.apache.http.HttpStatus;
package com.github.dikhan.pagerduty.client.events.utils; public class EventHelper { private static final int SC_RATE_LIMIT = 429; /** * Helper method to create a successful event result * @return successful event result */
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/domain/EventResult.java // public class EventResult { // // private final String status; // private final String message; // private final String dedupKey; // private final String errors; // // private EventResult(EventResultBuilder eventResultBuilder) { // this.status = eventResultBuilder.getStatus(); // this.message = eventResultBuilder.getMessage(); // this.dedupKey = eventResultBuilder.getDedupKey(); // this.errors = eventResultBuilder.getErrors(); // } // // public static EventResult successEvent(String status, String message, String dedupKey) { // return new EventResultBuilder(status, message).success(dedupKey).build(); // } // // public static EventResult errorEvent(String status, String message, String errors) { // return new EventResultBuilder(status, message).error(errors).build(); // } // // public String getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getDedupKey() { // return dedupKey; // } // // public String getErrors() { // return errors; // } // // private static class EventResultBuilder { // private final String status; // private final String message; // private String dedupKey; // private String errors; // // public EventResultBuilder(String status, String message) { // this.status = status; // this.message = message; // } // // public EventResultBuilder success(String dedupKey) { // this.dedupKey = dedupKey; // return this; // } // // public EventResultBuilder error(String errors) { // this.errors = errors; // return this; // } // // public String getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getDedupKey() { // return dedupKey; // } // // public String getErrors() { // return errors; // } // // public EventResult build() { // return new EventResult(this); // } // // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EventResult that = (EventResult) o; // // if (status != null ? !status.equals(that.status) : that.status != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // if (dedupKey != null ? !dedupKey.equals(that.dedupKey) : that.dedupKey != null) return false; // return !(errors != null ? !errors.equals(that.errors) : that.errors != null); // // } // // @Override // public int hashCode() { // int result = status != null ? status.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // result = 31 * result + (dedupKey != null ? dedupKey.hashCode() : 0); // result = 31 * result + (errors != null ? errors.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "EventResult{" + // "status='" + status + '\'' + // ", message='" + message + '\'' + // ", dedupKey='" + dedupKey + '\'' + // ", errors='" + errors + '\'' + // '}'; // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/utils/EventHelper.java import com.github.dikhan.pagerduty.client.events.domain.EventResult; import org.apache.http.HttpStatus; package com.github.dikhan.pagerduty.client.events.utils; public class EventHelper { private static final int SC_RATE_LIMIT = 429; /** * Helper method to create a successful event result * @return successful event result */
public static EventResult successEvent() {
dikhan/pagerduty-client
src/main/java/com/github/dikhan/pagerduty/client/events/domain/Payload.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/domain/Incident.java // protected static final String BLANK_FIELD = "BLANK";
import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import java.time.OffsetDateTime; import java.util.Objects; import static com.github.dikhan.pagerduty.client.events.domain.Incident.IncidentBuilder.BLANK_FIELD;
} public Object getCustomDetails() { return customDetails; } public static class Builder { private String summary; private String source; private Severity severity; private OffsetDateTime timestamp; private String component; private String group; private String eventClass; private JSONObject customDetails; /** * Builder which helps constructing new payload instances */ private Builder() { } public static Builder newBuilder() { return new Builder(); } /** * Create an empty payload with arbitrary field. Use for acknowledgeIncident and resolveIncident. */ public static Payload createEmpty() {
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/domain/Incident.java // protected static final String BLANK_FIELD = "BLANK"; // Path: src/main/java/com/github/dikhan/pagerduty/client/events/domain/Payload.java import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import java.time.OffsetDateTime; import java.util.Objects; import static com.github.dikhan.pagerduty.client.events.domain.Incident.IncidentBuilder.BLANK_FIELD; } public Object getCustomDetails() { return customDetails; } public static class Builder { private String summary; private String source; private Severity severity; private OffsetDateTime timestamp; private String component; private String group; private String eventClass; private JSONObject customDetails; /** * Builder which helps constructing new payload instances */ private Builder() { } public static Builder newBuilder() { return new Builder(); } /** * Create an empty payload with arbitrary field. Use for acknowledgeIncident and resolveIncident. */ public static Payload createEmpty() {
return newBuilder().setSummary(BLANK_FIELD).setSource(BLANK_FIELD).setSeverity(Severity.INFO).build();
dikhan/pagerduty-client
src/main/java/com/github/dikhan/pagerduty/client/events/PagerDutyEventsClient.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.domain.*; import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List;
package com.github.dikhan.pagerduty.client.events; public class PagerDutyEventsClient { private static final Logger log = LoggerFactory.getLogger(PagerDutyEventsClient.class); private final ApiService httpApiServiceImpl; protected PagerDutyEventsClient(PagerDutyClientBuilder pagerDutyClientBuilder) { String eventApi = pagerDutyClientBuilder.getEventApi(); String changeEventApi = pagerDutyClientBuilder.getChangeEventApi(); String proxyHost = pagerDutyClientBuilder.getProxyHost(); Integer proxyPort = pagerDutyClientBuilder.getProxyPort(); boolean doRetries = pagerDutyClientBuilder.getDoRetries(); this.httpApiServiceImpl = new ApiServiceFactory(eventApi, changeEventApi, proxyHost, proxyPort, doRetries).getDefault(); }
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/main/java/com/github/dikhan/pagerduty/client/events/PagerDutyEventsClient.java import com.github.dikhan.pagerduty.client.events.domain.*; import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; package com.github.dikhan.pagerduty.client.events; public class PagerDutyEventsClient { private static final Logger log = LoggerFactory.getLogger(PagerDutyEventsClient.class); private final ApiService httpApiServiceImpl; protected PagerDutyEventsClient(PagerDutyClientBuilder pagerDutyClientBuilder) { String eventApi = pagerDutyClientBuilder.getEventApi(); String changeEventApi = pagerDutyClientBuilder.getChangeEventApi(); String proxyHost = pagerDutyClientBuilder.getProxyHost(); Integer proxyPort = pagerDutyClientBuilder.getProxyPort(); boolean doRetries = pagerDutyClientBuilder.getDoRetries(); this.httpApiServiceImpl = new ApiServiceFactory(eventApi, changeEventApi, proxyHost, proxyPort, doRetries).getDefault(); }
public static void main(String[] args) throws NotifyEventException {
dikhan/pagerduty-client
src/main/java/com/github/dikhan/pagerduty/client/events/JacksonObjectMapper.java
// Path: src/main/java/com/github/dikhan/utils/JSONObjectSerializer.java // public class JSONObjectSerializer extends StdSerializer<JSONObject>{ // public JSONObjectSerializer() { // this(null); // } // // public JSONObjectSerializer(Class<JSONObject> jsonObject) { // super(jsonObject); // } // // @Override // public void serialize(JSONObject jsonObject, JsonGenerator jgen, // SerializerProvider provider) throws IOException{ // jgen.writeRawValue(jsonObject.toString()); // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.github.dikhan.utils.JSONObjectSerializer; import org.json.JSONObject; import java.io.IOException;
package com.github.dikhan.pagerduty.client.events; public class JacksonObjectMapper implements com.mashape.unirest.http.ObjectMapper { private static final ObjectMapper jacksonObjectMapper = makeObjectMapper(); private static ObjectMapper makeObjectMapper() { com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); SimpleModule module = new SimpleModule();
// Path: src/main/java/com/github/dikhan/utils/JSONObjectSerializer.java // public class JSONObjectSerializer extends StdSerializer<JSONObject>{ // public JSONObjectSerializer() { // this(null); // } // // public JSONObjectSerializer(Class<JSONObject> jsonObject) { // super(jsonObject); // } // // @Override // public void serialize(JSONObject jsonObject, JsonGenerator jgen, // SerializerProvider provider) throws IOException{ // jgen.writeRawValue(jsonObject.toString()); // } // } // Path: src/main/java/com/github/dikhan/pagerduty/client/events/JacksonObjectMapper.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.github.dikhan.utils.JSONObjectSerializer; import org.json.JSONObject; import java.io.IOException; package com.github.dikhan.pagerduty.client.events; public class JacksonObjectMapper implements com.mashape.unirest.http.ObjectMapper { private static final ObjectMapper jacksonObjectMapper = makeObjectMapper(); private static ObjectMapper makeObjectMapper() { com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); SimpleModule module = new SimpleModule();
module.addSerializer(JSONObject.class, new JSONObjectSerializer());
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/domain/TriggerIncidentBuilderTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.domain; public class TriggerIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/domain/TriggerIncidentBuilderTest.java import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.domain; public class TriggerIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
public void notAbleToCreateTriggerIncidentIfMandatoryFieldRoutingKeyIsNull() throws NotifyEventException {
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/domain/ChangeEventBuilderTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.domain; public class ChangeEventBuilderTest { @Test(expected = IllegalArgumentException.class)
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/domain/ChangeEventBuilderTest.java import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.domain; public class ChangeEventBuilderTest { @Test(expected = IllegalArgumentException.class)
public void notAbleToCreateChangeIfMandatoryFieldRoutingKeyIsNull() throws NotifyEventException {
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/domain/AcknowledgeIncidentBuilderTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.domain; public class AcknowledgeIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/domain/AcknowledgeIncidentBuilderTest.java import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.domain; public class AcknowledgeIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
public void notAbleToCreateTriggerIncidentIfMandatoryFieldRoutingKeyIsNull() throws NotifyEventException {
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/domain/IncidentBuilderTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.domain; public class IncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/domain/IncidentBuilderTest.java import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.domain; public class IncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
public void notAbleToCreateTriggerIncidentIfMandatoryFieldRoutingKeyIsNull() throws NotifyEventException {
dikhan/pagerduty-client
src/test/java/com/github/dikhan/pagerduty/client/events/domain/ResolveIncidentBuilderTest.java
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // }
import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test;
package com.github.dikhan.pagerduty.client.events.domain; public class ResolveIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
// Path: src/main/java/com/github/dikhan/pagerduty/client/events/exceptions/NotifyEventException.java // public class NotifyEventException extends Exception { // // public NotifyEventException(Throwable cause) { // super(cause); // } // // public NotifyEventException(String message) { // super(message); // } // } // Path: src/test/java/com/github/dikhan/pagerduty/client/events/domain/ResolveIncidentBuilderTest.java import com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException; import org.junit.Test; package com.github.dikhan.pagerduty.client.events.domain; public class ResolveIncidentBuilderTest { @Test(expected = IllegalArgumentException.class)
public void notAbleToCreateTriggerIncidentIfMandatoryFieldRoutingKeyIsNull() throws NotifyEventException {
richard-melvin/junit-theory-suite
src/main/java/com/github/radm/theories/runner/ConstraintFinder.java
// Path: src/main/java/com/github/radm/theories/pairwise/ArgumentSet.java // public class ArgumentSet implements Iterable<ArgVector> { // // static final Logger LOG = LoggerFactory.getLogger(ArgumentSet.class); // final List<String> argNames; // final List<List<Object>> argsValues; // // private final Map<String, Predicate<Object[]>> constraints = new HashMap<>(); // // /** // * Instantiates a new argument set. // * // * @param argNames // * the arg names // * @param argsValues // * the args values // */ // public ArgumentSet(List<String> argNames, List<List<Object>> argsValues) { // super(); // this.argNames = argNames; // this.argsValues = argsValues; // // assert argNames.size() == argsValues.size(); // } // // /** // * create an argument set where arguments are a list of array. // * // * @param argNames // * the arg names // * @param argsValues // * the arg values // * @return the argument set // */ // public static ArgumentSet fromArray(List<String> argNames, List<Object[]> argsValues) { // // List<List<Object>> vals = new ArrayList<>(argsValues.size()); // // for (Object[] o : argsValues) { // vals.add(Arrays.asList(o)); // } // // return new ArgumentSet(argNames, vals); // } // // /** // * Adds the constraint. // * // * @param argName // * the arg name // * @param constraint // * the constraint // * @return the argument set // */ // public ArgumentSet withConstraint(String argName, Predicate<Object[]> constraint) { // Predicate<Object[]> existing = constraints.get(argName); // if (existing == null) { // constraints.put(argName, constraint); // } else { // constraints.put(argName, existing.and(constraint)); // } // return this; // } // // /** // * Gets the consolidated constraint that can be evaluated at this point. // * // * @param argIndex // * the argument index // * @return the constraint, or null if none // */ // Predicate<Object[]> getConstraint(int argIndex) { // assert argIndex < argNames.size(); // return constraints.get(argNames.get(argIndex)); // // } // // /** // * Iterate over all possible values of combinations or argument values // */ // @Override // public Iterator<ArgVector> iterator() { // return new ExhaustiveIterator(this); // } // // /** // * Iterate over all pairwise combinations of argument values. // * // * @return the iterator // */ // public Iterator<ArgVector> pairwiseIterator() { // // // no point doing pairwise logic for small cases // if (argNames.size() <= 2) { // return iterator(); // } // // return new PairwiseIterator(this); // } // // /** // * Gets the arg names in declaration order. // * // * @return the arg names // */ // public List<String> getArgNames() { // return argNames; // } // // }
import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.junit.contrib.theories.Theory; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.TestClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.radm.theories.Constraint; import com.github.radm.theories.WithConstraints; import com.github.radm.theories.pairwise.ArgumentSet;
"WithConstraint used with unknown constraint name" + name + " in " + method.getName())); } MethodSignature testSignature = new MethodSignature(fm); boolean matchFound = false; for (MethodSignature namedConstraint : namedConstraints.get(name)) { if (namedConstraint.isSubListOf(testSignature)) { matchFound = true; } } if (!matchFound) { handler.accept(new Error( "WithConstraint used with no matching constraint names " + name + " in " + method.getName())); } } } /** * Apply matching constraints defined on current class to the set of test * method arguments. * * @param fm * the fm * @param as * the as */
// Path: src/main/java/com/github/radm/theories/pairwise/ArgumentSet.java // public class ArgumentSet implements Iterable<ArgVector> { // // static final Logger LOG = LoggerFactory.getLogger(ArgumentSet.class); // final List<String> argNames; // final List<List<Object>> argsValues; // // private final Map<String, Predicate<Object[]>> constraints = new HashMap<>(); // // /** // * Instantiates a new argument set. // * // * @param argNames // * the arg names // * @param argsValues // * the args values // */ // public ArgumentSet(List<String> argNames, List<List<Object>> argsValues) { // super(); // this.argNames = argNames; // this.argsValues = argsValues; // // assert argNames.size() == argsValues.size(); // } // // /** // * create an argument set where arguments are a list of array. // * // * @param argNames // * the arg names // * @param argsValues // * the arg values // * @return the argument set // */ // public static ArgumentSet fromArray(List<String> argNames, List<Object[]> argsValues) { // // List<List<Object>> vals = new ArrayList<>(argsValues.size()); // // for (Object[] o : argsValues) { // vals.add(Arrays.asList(o)); // } // // return new ArgumentSet(argNames, vals); // } // // /** // * Adds the constraint. // * // * @param argName // * the arg name // * @param constraint // * the constraint // * @return the argument set // */ // public ArgumentSet withConstraint(String argName, Predicate<Object[]> constraint) { // Predicate<Object[]> existing = constraints.get(argName); // if (existing == null) { // constraints.put(argName, constraint); // } else { // constraints.put(argName, existing.and(constraint)); // } // return this; // } // // /** // * Gets the consolidated constraint that can be evaluated at this point. // * // * @param argIndex // * the argument index // * @return the constraint, or null if none // */ // Predicate<Object[]> getConstraint(int argIndex) { // assert argIndex < argNames.size(); // return constraints.get(argNames.get(argIndex)); // // } // // /** // * Iterate over all possible values of combinations or argument values // */ // @Override // public Iterator<ArgVector> iterator() { // return new ExhaustiveIterator(this); // } // // /** // * Iterate over all pairwise combinations of argument values. // * // * @return the iterator // */ // public Iterator<ArgVector> pairwiseIterator() { // // // no point doing pairwise logic for small cases // if (argNames.size() <= 2) { // return iterator(); // } // // return new PairwiseIterator(this); // } // // /** // * Gets the arg names in declaration order. // * // * @return the arg names // */ // public List<String> getArgNames() { // return argNames; // } // // } // Path: src/main/java/com/github/radm/theories/runner/ConstraintFinder.java import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.junit.contrib.theories.Theory; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.TestClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.radm.theories.Constraint; import com.github.radm.theories.WithConstraints; import com.github.radm.theories.pairwise.ArgumentSet; "WithConstraint used with unknown constraint name" + name + " in " + method.getName())); } MethodSignature testSignature = new MethodSignature(fm); boolean matchFound = false; for (MethodSignature namedConstraint : namedConstraints.get(name)) { if (namedConstraint.isSubListOf(testSignature)) { matchFound = true; } } if (!matchFound) { handler.accept(new Error( "WithConstraint used with no matching constraint names " + name + " in " + method.getName())); } } } /** * Apply matching constraints defined on current class to the set of test * method arguments. * * @param fm * the fm * @param as * the as */
public void applyConstraintsTo(FrameworkMethod fm, ArgumentSet as) {
richard-melvin/junit-theory-suite
src/test/java/com/github/radm/theories/pairwise/test/ExhaustiveIteratorTest.java
// Path: src/main/java/com/github/radm/theories/pairwise/ArgumentSet.java // public class ArgumentSet implements Iterable<ArgVector> { // // static final Logger LOG = LoggerFactory.getLogger(ArgumentSet.class); // final List<String> argNames; // final List<List<Object>> argsValues; // // private final Map<String, Predicate<Object[]>> constraints = new HashMap<>(); // // /** // * Instantiates a new argument set. // * // * @param argNames // * the arg names // * @param argsValues // * the args values // */ // public ArgumentSet(List<String> argNames, List<List<Object>> argsValues) { // super(); // this.argNames = argNames; // this.argsValues = argsValues; // // assert argNames.size() == argsValues.size(); // } // // /** // * create an argument set where arguments are a list of array. // * // * @param argNames // * the arg names // * @param argsValues // * the arg values // * @return the argument set // */ // public static ArgumentSet fromArray(List<String> argNames, List<Object[]> argsValues) { // // List<List<Object>> vals = new ArrayList<>(argsValues.size()); // // for (Object[] o : argsValues) { // vals.add(Arrays.asList(o)); // } // // return new ArgumentSet(argNames, vals); // } // // /** // * Adds the constraint. // * // * @param argName // * the arg name // * @param constraint // * the constraint // * @return the argument set // */ // public ArgumentSet withConstraint(String argName, Predicate<Object[]> constraint) { // Predicate<Object[]> existing = constraints.get(argName); // if (existing == null) { // constraints.put(argName, constraint); // } else { // constraints.put(argName, existing.and(constraint)); // } // return this; // } // // /** // * Gets the consolidated constraint that can be evaluated at this point. // * // * @param argIndex // * the argument index // * @return the constraint, or null if none // */ // Predicate<Object[]> getConstraint(int argIndex) { // assert argIndex < argNames.size(); // return constraints.get(argNames.get(argIndex)); // // } // // /** // * Iterate over all possible values of combinations or argument values // */ // @Override // public Iterator<ArgVector> iterator() { // return new ExhaustiveIterator(this); // } // // /** // * Iterate over all pairwise combinations of argument values. // * // * @return the iterator // */ // public Iterator<ArgVector> pairwiseIterator() { // // // no point doing pairwise logic for small cases // if (argNames.size() <= 2) { // return iterator(); // } // // return new PairwiseIterator(this); // } // // /** // * Gets the arg names in declaration order. // * // * @return the arg names // */ // public List<String> getArgNames() { // return argNames; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.radm.theories.pairwise.ArgumentSet;
@Test public void expectedLength2() { assertEquals(4, countArguments(twoBooleans)); } @Test public void expectedLength3() { assertEquals(27, countArguments(threeIntegers)); } @Test public void expectedLength4() { assertEquals(2, countArguments(twoBooleansConstrained)); } @Test public void expectedLength5() { assertEquals(8, countArguments(threeIntsConstrained)); } @Test public void expectedLength6() { assertEquals(7 * 7 * 7 * 7, countArguments(fourDays)); } @Test public void expectedLength7() { assertEquals(5 * 5 * 5 * 5, countArguments(fourWeekDays)); }
// Path: src/main/java/com/github/radm/theories/pairwise/ArgumentSet.java // public class ArgumentSet implements Iterable<ArgVector> { // // static final Logger LOG = LoggerFactory.getLogger(ArgumentSet.class); // final List<String> argNames; // final List<List<Object>> argsValues; // // private final Map<String, Predicate<Object[]>> constraints = new HashMap<>(); // // /** // * Instantiates a new argument set. // * // * @param argNames // * the arg names // * @param argsValues // * the args values // */ // public ArgumentSet(List<String> argNames, List<List<Object>> argsValues) { // super(); // this.argNames = argNames; // this.argsValues = argsValues; // // assert argNames.size() == argsValues.size(); // } // // /** // * create an argument set where arguments are a list of array. // * // * @param argNames // * the arg names // * @param argsValues // * the arg values // * @return the argument set // */ // public static ArgumentSet fromArray(List<String> argNames, List<Object[]> argsValues) { // // List<List<Object>> vals = new ArrayList<>(argsValues.size()); // // for (Object[] o : argsValues) { // vals.add(Arrays.asList(o)); // } // // return new ArgumentSet(argNames, vals); // } // // /** // * Adds the constraint. // * // * @param argName // * the arg name // * @param constraint // * the constraint // * @return the argument set // */ // public ArgumentSet withConstraint(String argName, Predicate<Object[]> constraint) { // Predicate<Object[]> existing = constraints.get(argName); // if (existing == null) { // constraints.put(argName, constraint); // } else { // constraints.put(argName, existing.and(constraint)); // } // return this; // } // // /** // * Gets the consolidated constraint that can be evaluated at this point. // * // * @param argIndex // * the argument index // * @return the constraint, or null if none // */ // Predicate<Object[]> getConstraint(int argIndex) { // assert argIndex < argNames.size(); // return constraints.get(argNames.get(argIndex)); // // } // // /** // * Iterate over all possible values of combinations or argument values // */ // @Override // public Iterator<ArgVector> iterator() { // return new ExhaustiveIterator(this); // } // // /** // * Iterate over all pairwise combinations of argument values. // * // * @return the iterator // */ // public Iterator<ArgVector> pairwiseIterator() { // // // no point doing pairwise logic for small cases // if (argNames.size() <= 2) { // return iterator(); // } // // return new PairwiseIterator(this); // } // // /** // * Gets the arg names in declaration order. // * // * @return the arg names // */ // public List<String> getArgNames() { // return argNames; // } // // } // Path: src/test/java/com/github/radm/theories/pairwise/test/ExhaustiveIteratorTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.radm.theories.pairwise.ArgumentSet; @Test public void expectedLength2() { assertEquals(4, countArguments(twoBooleans)); } @Test public void expectedLength3() { assertEquals(27, countArguments(threeIntegers)); } @Test public void expectedLength4() { assertEquals(2, countArguments(twoBooleansConstrained)); } @Test public void expectedLength5() { assertEquals(8, countArguments(threeIntsConstrained)); } @Test public void expectedLength6() { assertEquals(7 * 7 * 7 * 7, countArguments(fourDays)); } @Test public void expectedLength7() { assertEquals(5 * 5 * 5 * 5, countArguments(fourWeekDays)); }
protected int countArguments(ArgumentSet as) {
codepine/testrail-api-java-client
src/test/java/com/codepine/api/testrail/internal/PlanModuleTest.java
// Path: src/main/java/com/codepine/api/testrail/model/Plan.java // @Data // public class Plan { // // private int id; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private String name; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private String description; // // private String url; // // private int projectId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private Integer milestoneId; // // private Integer assignedtoId; // // private Date createdOn; // // private int createdBy; // // @JsonProperty // @Getter(onMethod = @_({@JsonIgnore})) // private boolean isCompleted; // // private Date completedOn; // // private int passedCount; // // private int blockedCount; // // private int untestedCount; // // private int retestCount; // // private int failedCount; // // private int customStatus1Count; // // private int customStatus2Count; // // private int customStatus3Count; // // private int customStatus4Count; // // private int customStatus5Count; // // private int customStatus6Count; // // private int customStatus7Count; // // @JsonView({TestRail.Plans.Add.class}) // private List<Entry> entries; // // @Data // public static class Entry { // // private String id; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private String name; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private Integer suiteId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private String description; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private Integer assignedtoId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // @Getter(value = AccessLevel.PRIVATE) // private Boolean includeAll; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private List<Integer> caseIds; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private List<Integer> configIds; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private List<Run> runs; // // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public static class Run extends com.codepine.api.testrail.model.Run { // private String entryId; // private int entryIndex; // } // // public Boolean isIncludeAll() { // return getIncludeAll(); // } // } // }
import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import com.codepine.api.testrail.model.Plan; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.Test;
/* * The MIT License (MIT) * * Copyright (c) 2015 Kunal Shah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.codepine.api.testrail.internal; /** * Tests for {@link com.codepine.api.testrail.internal.PlanModule}. * <p>This test does not use mocks. It has some dependencies which it assumes are tested separately.</p> */ public class PlanModuleTest { private static final ObjectMapper objectMapper = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .registerModules(new PlanModule(), new UnixTimestampModule()); @Test public void W_planWithNoEntries_T_correctDeserialization() throws IOException { // WHEN
// Path: src/main/java/com/codepine/api/testrail/model/Plan.java // @Data // public class Plan { // // private int id; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private String name; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private String description; // // private String url; // // private int projectId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.Update.class}) // private Integer milestoneId; // // private Integer assignedtoId; // // private Date createdOn; // // private int createdBy; // // @JsonProperty // @Getter(onMethod = @_({@JsonIgnore})) // private boolean isCompleted; // // private Date completedOn; // // private int passedCount; // // private int blockedCount; // // private int untestedCount; // // private int retestCount; // // private int failedCount; // // private int customStatus1Count; // // private int customStatus2Count; // // private int customStatus3Count; // // private int customStatus4Count; // // private int customStatus5Count; // // private int customStatus6Count; // // private int customStatus7Count; // // @JsonView({TestRail.Plans.Add.class}) // private List<Entry> entries; // // @Data // public static class Entry { // // private String id; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private String name; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private Integer suiteId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private String description; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private Integer assignedtoId; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // @Getter(value = AccessLevel.PRIVATE) // private Boolean includeAll; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class, TestRail.Plans.UpdateEntry.class}) // private List<Integer> caseIds; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private List<Integer> configIds; // // @JsonView({TestRail.Plans.Add.class, TestRail.Plans.AddEntry.class}) // private List<Run> runs; // // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public static class Run extends com.codepine.api.testrail.model.Run { // private String entryId; // private int entryIndex; // } // // public Boolean isIncludeAll() { // return getIncludeAll(); // } // } // } // Path: src/test/java/com/codepine/api/testrail/internal/PlanModuleTest.java import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import com.codepine.api.testrail.model.Plan; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.Test; /* * The MIT License (MIT) * * Copyright (c) 2015 Kunal Shah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.codepine.api.testrail.internal; /** * Tests for {@link com.codepine.api.testrail.internal.PlanModule}. * <p>This test does not use mocks. It has some dependencies which it assumes are tested separately.</p> */ public class PlanModuleTest { private static final ObjectMapper objectMapper = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .registerModules(new PlanModule(), new UnixTimestampModule()); @Test public void W_planWithNoEntries_T_correctDeserialization() throws IOException { // WHEN
Plan actualPlan = objectMapper.readValue(this.getClass().getResourceAsStream("/plan_with_no_entries.json"), Plan.class);
codepine/testrail-api-java-client
src/main/java/com/codepine/api/testrail/internal/PageDeserializer.java
// Path: src/main/java/com/codepine/api/testrail/model/Links.java // public class Links { // // public String next; // // public String prev; // } // // Path: src/main/java/com/codepine/api/testrail/model/Page.java // @JsonDeserialize(using = PageDeserializer.class) // public class Page<T> { // // public int offset; // // public int limit; // // public int size; // // public Links _links; // // public T objects; // }
import com.codepine.api.testrail.model.Links; import com.codepine.api.testrail.model.Page; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List;
super(vc); } @Override public Page deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); int offset = node.get("offset").asInt(); int limit = node.get("limit").asInt(); int size = node.get("size").asInt(); JsonNode links = node.get("links"); String next = links.get("next").isNull() ? null : links.get("next").asText(); String prev = links.get("prev").isNull() ? null : links.get("prev").asText(); ArrayNode objects = (ArrayNode) node.get(field); List list = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModules(new CaseModule(), new FieldModule(), new PlanModule(), new ResultModule(), new UnixTimestampModule()); for(int i = 0; i < objects.size(); i++) { JsonNode element = objects.get(i); list.add(mapper.reader(type).with(new InjectableValues.Std().addValue(type.toString(), supplement)).readValue(element.toString())); } Page page = new Page(); page.limit = limit; page.offset = offset; page.size = size;
// Path: src/main/java/com/codepine/api/testrail/model/Links.java // public class Links { // // public String next; // // public String prev; // } // // Path: src/main/java/com/codepine/api/testrail/model/Page.java // @JsonDeserialize(using = PageDeserializer.class) // public class Page<T> { // // public int offset; // // public int limit; // // public int size; // // public Links _links; // // public T objects; // } // Path: src/main/java/com/codepine/api/testrail/internal/PageDeserializer.java import com.codepine.api.testrail.model.Links; import com.codepine.api.testrail.model.Page; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; super(vc); } @Override public Page deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); int offset = node.get("offset").asInt(); int limit = node.get("limit").asInt(); int size = node.get("size").asInt(); JsonNode links = node.get("links"); String next = links.get("next").isNull() ? null : links.get("next").asText(); String prev = links.get("prev").isNull() ? null : links.get("prev").asText(); ArrayNode objects = (ArrayNode) node.get(field); List list = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModules(new CaseModule(), new FieldModule(), new PlanModule(), new ResultModule(), new UnixTimestampModule()); for(int i = 0; i < objects.size(); i++) { JsonNode element = objects.get(i); list.add(mapper.reader(type).with(new InjectableValues.Std().addValue(type.toString(), supplement)).readValue(element.toString())); } Page page = new Page(); page.limit = limit; page.offset = offset; page.size = size;
page._links = new Links();
codepine/testrail-api-java-client
src/main/java/com/codepine/api/testrail/Request.java
// Path: src/main/java/com/codepine/api/testrail/model/Page.java // @JsonDeserialize(using = PageDeserializer.class) // public class Page<T> { // // public int offset; // // public int limit; // // public int size; // // public Links _links; // // public T objects; // }
import com.codepine.api.testrail.internal.*; import com.codepine.api.testrail.model.Page; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; import lombok.NonNull; import lombok.extern.log4j.Log4j; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
/* * The MIT License (MIT) * * Copyright (c) 2015 Kunal Shah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.codepine.api.testrail; /** * TestRail request. */ @Log4j public abstract class Request<T> { private static final UrlConnectionFactory DEFAULT_URL_CONNECTION_FACTORY = new UrlConnectionFactory(); private static final ObjectMapper JSON = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModules(new CaseModule(), new FieldModule(), new PlanModule(), new ResultModule(), new UnixTimestampModule()); @NonNull private final TestRailConfig config; @NonNull private final Method method; @NonNull private String restPath; private String apiSegment; private final Class<? extends T> responseClass; private final TypeReference<? extends T> responseType;
// Path: src/main/java/com/codepine/api/testrail/model/Page.java // @JsonDeserialize(using = PageDeserializer.class) // public class Page<T> { // // public int offset; // // public int limit; // // public int size; // // public Links _links; // // public T objects; // } // Path: src/main/java/com/codepine/api/testrail/Request.java import com.codepine.api.testrail.internal.*; import com.codepine.api.testrail.model.Page; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; import lombok.NonNull; import lombok.extern.log4j.Log4j; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * The MIT License (MIT) * * Copyright (c) 2015 Kunal Shah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.codepine.api.testrail; /** * TestRail request. */ @Log4j public abstract class Request<T> { private static final UrlConnectionFactory DEFAULT_URL_CONNECTION_FACTORY = new UrlConnectionFactory(); private static final ObjectMapper JSON = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModules(new CaseModule(), new FieldModule(), new PlanModule(), new ResultModule(), new UnixTimestampModule()); @NonNull private final TestRailConfig config; @NonNull private final Method method; @NonNull private String restPath; private String apiSegment; private final Class<? extends T> responseClass; private final TypeReference<? extends T> responseType;
private final TypeReference<Page<T>> pageType;
codepine/testrail-api-java-client
src/main/java/com/codepine/api/testrail/TestRail.java
// Path: src/main/java/com/codepine/api/testrail/internal/BooleanToIntSerializer.java // public class BooleanToIntSerializer extends JsonSerializer<Boolean> { // // @Override // public void serialize(final Boolean value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { // jgen.writeNumber(value == null ? 0 : value ? 1 : 0); // } // } // // Path: src/main/java/com/codepine/api/testrail/internal/ListToCsvSerializer.java // public class ListToCsvSerializer extends JsonSerializer<List<?>> { // // @Override // public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // if (value != null) { // jgen.writeString(Joiner.on(',').join(value)); // } // } // }
import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import com.codepine.api.testrail.internal.BooleanToIntSerializer; import com.codepine.api.testrail.internal.ListToCsvSerializer; import com.codepine.api.testrail.model.*; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public Update update(@NonNull Project project) { return new Update(project); } /** * Deletes an existing project. * * @param projectId the ID of the project to be deleted * @return the request * @throws java.lang.IllegalArgumentException if projectId is not positive */ public Delete delete(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new Delete(projectId); } public class Get extends Request<Project> { private static final String REST_PATH = "get_project/"; private Get(int projectId) { super(config, Method.GET, REST_PATH + projectId, Project.class); } } @Getter @Setter public class List extends Request<java.util.List<Project>> { private static final String REST_PATH = "get_projects"; @JsonView(List.class)
// Path: src/main/java/com/codepine/api/testrail/internal/BooleanToIntSerializer.java // public class BooleanToIntSerializer extends JsonSerializer<Boolean> { // // @Override // public void serialize(final Boolean value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { // jgen.writeNumber(value == null ? 0 : value ? 1 : 0); // } // } // // Path: src/main/java/com/codepine/api/testrail/internal/ListToCsvSerializer.java // public class ListToCsvSerializer extends JsonSerializer<List<?>> { // // @Override // public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // if (value != null) { // jgen.writeString(Joiner.on(',').join(value)); // } // } // } // Path: src/main/java/com/codepine/api/testrail/TestRail.java import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import com.codepine.api.testrail.internal.BooleanToIntSerializer; import com.codepine.api.testrail.internal.ListToCsvSerializer; import com.codepine.api.testrail.model.*; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public Update update(@NonNull Project project) { return new Update(project); } /** * Deletes an existing project. * * @param projectId the ID of the project to be deleted * @return the request * @throws java.lang.IllegalArgumentException if projectId is not positive */ public Delete delete(final int projectId) { checkArgument(projectId > 0, "projectId should be positive"); return new Delete(projectId); } public class Get extends Request<Project> { private static final String REST_PATH = "get_project/"; private Get(int projectId) { super(config, Method.GET, REST_PATH + projectId, Project.class); } } @Getter @Setter public class List extends Request<java.util.List<Project>> { private static final String REST_PATH = "get_projects"; @JsonView(List.class)
@JsonSerialize(using = BooleanToIntSerializer.class)
codepine/testrail-api-java-client
src/main/java/com/codepine/api/testrail/TestRail.java
// Path: src/main/java/com/codepine/api/testrail/internal/BooleanToIntSerializer.java // public class BooleanToIntSerializer extends JsonSerializer<Boolean> { // // @Override // public void serialize(final Boolean value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { // jgen.writeNumber(value == null ? 0 : value ? 1 : 0); // } // } // // Path: src/main/java/com/codepine/api/testrail/internal/ListToCsvSerializer.java // public class ListToCsvSerializer extends JsonSerializer<List<?>> { // // @Override // public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // if (value != null) { // jgen.writeString(Joiner.on(',').join(value)); // } // } // }
import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import com.codepine.api.testrail.internal.BooleanToIntSerializer; import com.codepine.api.testrail.internal.ListToCsvSerializer; import com.codepine.api.testrail.model.*; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class Get extends Request<Case> { private static final String REST_PATH = "get_case/"; private final java.util.List<CaseField> caseFields; private Get(int testCaseId, java.util.List<CaseField> caseFields) { super(config, Method.GET, REST_PATH + testCaseId, Case.class); this.caseFields = caseFields; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Case>> { private static final String REST_PATH = "get_cases/%s&suite_id=%s"; private final java.util.List<CaseField> caseFields; @JsonView(List.class) private Integer sectionId; @JsonView(List.class) private Date createdAfter; @JsonView(List.class) private Date createdBefore; @JsonView(List.class)
// Path: src/main/java/com/codepine/api/testrail/internal/BooleanToIntSerializer.java // public class BooleanToIntSerializer extends JsonSerializer<Boolean> { // // @Override // public void serialize(final Boolean value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { // jgen.writeNumber(value == null ? 0 : value ? 1 : 0); // } // } // // Path: src/main/java/com/codepine/api/testrail/internal/ListToCsvSerializer.java // public class ListToCsvSerializer extends JsonSerializer<List<?>> { // // @Override // public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // if (value != null) { // jgen.writeString(Joiner.on(',').join(value)); // } // } // } // Path: src/main/java/com/codepine/api/testrail/TestRail.java import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import com.codepine.api.testrail.internal.BooleanToIntSerializer; import com.codepine.api.testrail.internal.ListToCsvSerializer; import com.codepine.api.testrail.model.*; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Get extends Request<Case> { private static final String REST_PATH = "get_case/"; private final java.util.List<CaseField> caseFields; private Get(int testCaseId, java.util.List<CaseField> caseFields) { super(config, Method.GET, REST_PATH + testCaseId, Case.class); this.caseFields = caseFields; } @Override protected Object getSupplementForDeserialization() { return caseFields; } } @Getter @Setter @Accessors(fluent = true) public class List extends Request<java.util.List<Case>> { private static final String REST_PATH = "get_cases/%s&suite_id=%s"; private final java.util.List<CaseField> caseFields; @JsonView(List.class) private Integer sectionId; @JsonView(List.class) private Date createdAfter; @JsonView(List.class) private Date createdBefore; @JsonView(List.class)
@JsonSerialize(using = ListToCsvSerializer.class)
nightscout/android-uploader
core/src/test/java/com/nightscout/core/dexcom/EgvRecordTest.java
// Path: core/src/main/java/com/nightscout/core/model/G4Noise.java // public enum G4Noise // implements ProtoEnum { // NOISE_NONE(0), // CLEAN(1), // LIGHT(2), // MEDIUM(3), // HEAVY(4), // NOT_COMPUTED(5), // MAX(6); // // private final int value; // // private G4Noise(int value) { // this.value = value; // } // // @Override // public int getValue() { // return value; // } // }
import com.nightscout.core.dexcom.records.EGVRecord; import com.nightscout.core.model.G4Noise; import org.json.JSONObject; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package com.nightscout.core.dexcom; public class EgvRecordTest { // EGV Record: C4881A0B61341A0B0500583E // EGV: 5 Trend: NOT_COMPUTABLE display time: 1417056321000, system time: 186288324, display time offset: 186266721, noise level: None // // EGV Record: 80BD1A0B1D691A0B7800217D // EGV: 120 Trend: DOUBLE_UP display time: 1417069821000 system time: 186301824 noise level: None @Test public void shouldParseEgvRecord() throws Exception { byte[] record = new byte[]{(byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E}; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.getBgMgdl(), is(5)); assertThat(egvRecord.getTrend(), is(TrendArrow.NOT_COMPUTABLE)); assertThat(egvRecord.getRawDisplayTimeSeconds(), is(186266721L)); assertThat(egvRecord.getRawSystemTimeSeconds(), is(186288324L));
// Path: core/src/main/java/com/nightscout/core/model/G4Noise.java // public enum G4Noise // implements ProtoEnum { // NOISE_NONE(0), // CLEAN(1), // LIGHT(2), // MEDIUM(3), // HEAVY(4), // NOT_COMPUTED(5), // MAX(6); // // private final int value; // // private G4Noise(int value) { // this.value = value; // } // // @Override // public int getValue() { // return value; // } // } // Path: core/src/test/java/com/nightscout/core/dexcom/EgvRecordTest.java import com.nightscout.core.dexcom.records.EGVRecord; import com.nightscout.core.model.G4Noise; import org.json.JSONObject; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package com.nightscout.core.dexcom; public class EgvRecordTest { // EGV Record: C4881A0B61341A0B0500583E // EGV: 5 Trend: NOT_COMPUTABLE display time: 1417056321000, system time: 186288324, display time offset: 186266721, noise level: None // // EGV Record: 80BD1A0B1D691A0B7800217D // EGV: 120 Trend: DOUBLE_UP display time: 1417069821000 system time: 186301824 noise level: None @Test public void shouldParseEgvRecord() throws Exception { byte[] record = new byte[]{(byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E}; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.getBgMgdl(), is(5)); assertThat(egvRecord.getTrend(), is(TrendArrow.NOT_COMPUTABLE)); assertThat(egvRecord.getRawDisplayTimeSeconds(), is(186266721L)); assertThat(egvRecord.getRawSystemTimeSeconds(), is(186288324L));
assertThat(egvRecord.getNoiseMode(), is(G4Noise.NOT_COMPUTED));
nightscout/android-uploader
app/src/test/java/com/nightscout/android/settings/SettingsActivityTest.java
// Path: app/src/main/java/com/nightscout/android/preferences/PreferenceKeys.java // public final class PreferenceKeys { // public static final String DATA_DONATE = "data_donate"; // public static final String API_UPLOADER_ENABLED = "cloud_storage_api_enable"; // public static final String API_URIS = "cloud_storage_api_base"; // public static final String CAL_UPLOAD_ENABLED = "cloud_cal_data"; // public static final String SENSOR_UPLOAD_ENABLED = "cloud_sensor_data"; // public static final String MONGO_UPLOADER_ENABLED = "cloud_storage_mongodb_enable"; // public static final String MONGO_URI = "cloud_storage_mongodb_uri"; // public static final String MONGO_COLLECTION = "cloud_storage_mongodb_collection"; // public static final String MONGO_DEVICE_STATUS_COLLECTION = // "cloud_storage_mongodb_device_status_collection"; // public static final String ROOT_ENABLED = "root_support_enabled"; // public static final String I_UNDERSTAND = "i_understand"; // public static final String PREFERRED_UNITS = "display_options_units"; // public static final String PWD_NAME = "pwd_name"; // public static final String DONATE_DATA_QUERY = "donate_data_query"; // } // // Path: app/src/test/java/com/nightscout/android/test/RobolectricTestBase.java // @RunWith(RobolectricGradleRunner.class) // public class RobolectricTestBase { // private final boolean[] intentSeen = {false}; // // @Before // public final void setUpBase() { // // NPEs happen when using Robolectric + GA for some reason. Disable them for now. // // https://github.com/robolectric/robolectric/issues/1075 // getShadowApplication().declareActionUnbindable("com.google.android.gms.analytics.service.START"); // GoogleAnalytics.getInstance(getContext()).setAppOptOut(true); // } // // public void whenOnBroadcastReceived(String intentKey, final Function<Intent, Void> verifyCallback) { // getShadowApplication().registerReceiver(new BroadcastReceiver() { // @Override // public void onReceive(Context context, Intent intent) { // intentSeen[0] = true; // verifyCallback.apply(intent); // } // }, new IntentFilter(intentKey)); // } // // public void assertIntentSeen() { // assertThat(intentSeen[0], is(true)); // } // // public Context getContext() { // return getShadowApplication().getApplicationContext(); // } // // public ShadowApplication getShadowApplication() { // return Robolectric.getShadowApplication(); // } // }
import android.preference.EditTextPreference; import android.preference.PreferenceFragment; import com.nightscout.android.R; import com.nightscout.android.preferences.PreferenceKeys; import com.nightscout.android.test.RobolectricTestBase; import org.junit.Test; import org.robolectric.shadows.ShadowAlertDialog; import org.robolectric.util.FragmentTestUtil; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat;
package com.nightscout.android.settings; public class SettingsActivityTest extends RobolectricTestBase { private PreferenceFragment setUpPreferenceFragment(Class<? extends PreferenceFragment> clazz) { PreferenceFragment instance; try { instance = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } FragmentTestUtil.startVisibleFragment(instance); return instance; } @Test public void testValidation_RestApi_Invalid() { EditTextPreference editTextPreference = (EditTextPreference) setUpPreferenceFragment( SettingsActivity.MainPreferenceFragment.class)
// Path: app/src/main/java/com/nightscout/android/preferences/PreferenceKeys.java // public final class PreferenceKeys { // public static final String DATA_DONATE = "data_donate"; // public static final String API_UPLOADER_ENABLED = "cloud_storage_api_enable"; // public static final String API_URIS = "cloud_storage_api_base"; // public static final String CAL_UPLOAD_ENABLED = "cloud_cal_data"; // public static final String SENSOR_UPLOAD_ENABLED = "cloud_sensor_data"; // public static final String MONGO_UPLOADER_ENABLED = "cloud_storage_mongodb_enable"; // public static final String MONGO_URI = "cloud_storage_mongodb_uri"; // public static final String MONGO_COLLECTION = "cloud_storage_mongodb_collection"; // public static final String MONGO_DEVICE_STATUS_COLLECTION = // "cloud_storage_mongodb_device_status_collection"; // public static final String ROOT_ENABLED = "root_support_enabled"; // public static final String I_UNDERSTAND = "i_understand"; // public static final String PREFERRED_UNITS = "display_options_units"; // public static final String PWD_NAME = "pwd_name"; // public static final String DONATE_DATA_QUERY = "donate_data_query"; // } // // Path: app/src/test/java/com/nightscout/android/test/RobolectricTestBase.java // @RunWith(RobolectricGradleRunner.class) // public class RobolectricTestBase { // private final boolean[] intentSeen = {false}; // // @Before // public final void setUpBase() { // // NPEs happen when using Robolectric + GA for some reason. Disable them for now. // // https://github.com/robolectric/robolectric/issues/1075 // getShadowApplication().declareActionUnbindable("com.google.android.gms.analytics.service.START"); // GoogleAnalytics.getInstance(getContext()).setAppOptOut(true); // } // // public void whenOnBroadcastReceived(String intentKey, final Function<Intent, Void> verifyCallback) { // getShadowApplication().registerReceiver(new BroadcastReceiver() { // @Override // public void onReceive(Context context, Intent intent) { // intentSeen[0] = true; // verifyCallback.apply(intent); // } // }, new IntentFilter(intentKey)); // } // // public void assertIntentSeen() { // assertThat(intentSeen[0], is(true)); // } // // public Context getContext() { // return getShadowApplication().getApplicationContext(); // } // // public ShadowApplication getShadowApplication() { // return Robolectric.getShadowApplication(); // } // } // Path: app/src/test/java/com/nightscout/android/settings/SettingsActivityTest.java import android.preference.EditTextPreference; import android.preference.PreferenceFragment; import com.nightscout.android.R; import com.nightscout.android.preferences.PreferenceKeys; import com.nightscout.android.test.RobolectricTestBase; import org.junit.Test; import org.robolectric.shadows.ShadowAlertDialog; import org.robolectric.util.FragmentTestUtil; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; package com.nightscout.android.settings; public class SettingsActivityTest extends RobolectricTestBase { private PreferenceFragment setUpPreferenceFragment(Class<? extends PreferenceFragment> clazz) { PreferenceFragment instance; try { instance = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } FragmentTestUtil.startVisibleFragment(instance); return instance; } @Test public void testValidation_RestApi_Invalid() { EditTextPreference editTextPreference = (EditTextPreference) setUpPreferenceFragment( SettingsActivity.MainPreferenceFragment.class)
.findPreference(PreferenceKeys.API_URIS);
nightscout/android-uploader
core/src/test/java/com/nightscout/core/dexcom/MeterRecordTest.java
// Path: core/src/main/java/com/nightscout/core/dexcom/records/MeterRecord.java // public class MeterRecord extends GenericTimestampRecord { // public final static int RECORD_SIZE = 15; // private int meterTime; // private GlucoseReading reading; // // public MeterRecord(byte[] packet) { // super(packet); // if (packet.length != RECORD_SIZE) { // throw new InvalidRecordLengthException("Unexpected record size: " + packet.length + // ". Expected size: " + RECORD_SIZE + " record: " + Utils.bytesToHex(packet)); // } // int meterBG = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).getShort(8); // reading = new GlucoseReading(meterBG, GlucoseUnit.MGDL); // meterTime = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).getInt(10); // } // // public MeterRecord(int meterBgMgdl, int meterTime, Date displayTime, Date systemTime) { // super(displayTime, systemTime); // this.reading = new GlucoseReading(meterBgMgdl, GlucoseUnit.MGDL); // this.meterTime = meterTime; // } // // public MeterRecord(int meterBgMgdl, int meterTime, long displayTime, int systemTime) { // super(displayTime, systemTime); // this.reading = new GlucoseReading(meterBgMgdl, GlucoseUnit.MGDL); // this.meterTime = meterTime; // } // // public MeterRecord(MeterEntry meter) { // super(meter.disp_timestamp_sec, meter.sys_timestamp_sec); // this.reading = new GlucoseReading(meter.meter_bg_mgdl, GlucoseUnit.MGDL); // this.meterTime = meter.meter_time; // } // // public GlucoseReading getMeterBG() { // return reading; // } // // public int getBgMgdl() { // return reading.asMgdl(); // } // // public int getMeterTime() { // return meterTime; // } // // @Override // public MeterEntry toProtobuf() { // MeterEntry.Builder builder = new MeterEntry.Builder(); // return builder.sys_timestamp_sec(rawSystemTimeSeconds) // .disp_timestamp_sec(rawDisplayTimeSeconds) // .meter_time(meterTime) // .meter_bg_mgdl(reading.asMgdl()) // .build(); // } // // public static List<MeterEntry> toProtobufList(List<MeterRecord> list) { // return toProtobufList(list, MeterEntry.class); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // if (!super.equals(o)) return false; // // MeterRecord that = (MeterRecord) o; // // if (meterTime != that.meterTime) return false; // if (!reading.equals(that.reading)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + meterTime; // result = 31 * result + reading.hashCode(); // return result; // } // }
import static org.junit.Assert.assertThat; import com.nightscout.core.dexcom.records.MeterRecord; import org.junit.Test; import static org.hamcrest.Matchers.is;
// Meter Record: 2880180BC52B180B71000A80180BAC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 4CB51A0BE9601A0B46002EB51A0B73 // Record EGV: 70 Meter time: 186299694 display time: 1417071321000 system time: 186299724 // Meter Record: 63B51A0B00611A0B480045B51A0BB1 // Record EGV: 72 Meter time: 186299717 display time: 1417071344000 system time: 186299747 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 // Meter Record: 2880180BC52B180B71000A80180BAC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 4CB51A0BE9601A0B46002EB51A0B73 // Record EGV: 70 Meter time: 186299694 display time: 1417071321000 system time: 186299724 // Meter Record: 63B51A0B00611A0B480045B51A0BB1 // Record EGV: 72 Meter time: 186299717 display time: 1417071344000 system time: 186299747 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 package com.nightscout.core.dexcom; public class MeterRecordTest { // Meter Record: 28 80 18 0B C5 2B 18 0B 71 00 0A 80 18 0B AC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 @Test public void shouldParseMeterRecord() throws Exception { byte[] record = new byte[]{(byte) 0x28, (byte) 0x80, (byte) 0x18, (byte) 0x0B, (byte) 0xC5, (byte) 0x2B, (byte) 0x18, (byte) 0x0B, (byte) 0x71, (byte) 0x00, (byte) 0x0A, (byte) 0x80, (byte) 0x18, (byte) 0x0B, (byte) 0xAC};
// Path: core/src/main/java/com/nightscout/core/dexcom/records/MeterRecord.java // public class MeterRecord extends GenericTimestampRecord { // public final static int RECORD_SIZE = 15; // private int meterTime; // private GlucoseReading reading; // // public MeterRecord(byte[] packet) { // super(packet); // if (packet.length != RECORD_SIZE) { // throw new InvalidRecordLengthException("Unexpected record size: " + packet.length + // ". Expected size: " + RECORD_SIZE + " record: " + Utils.bytesToHex(packet)); // } // int meterBG = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).getShort(8); // reading = new GlucoseReading(meterBG, GlucoseUnit.MGDL); // meterTime = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).getInt(10); // } // // public MeterRecord(int meterBgMgdl, int meterTime, Date displayTime, Date systemTime) { // super(displayTime, systemTime); // this.reading = new GlucoseReading(meterBgMgdl, GlucoseUnit.MGDL); // this.meterTime = meterTime; // } // // public MeterRecord(int meterBgMgdl, int meterTime, long displayTime, int systemTime) { // super(displayTime, systemTime); // this.reading = new GlucoseReading(meterBgMgdl, GlucoseUnit.MGDL); // this.meterTime = meterTime; // } // // public MeterRecord(MeterEntry meter) { // super(meter.disp_timestamp_sec, meter.sys_timestamp_sec); // this.reading = new GlucoseReading(meter.meter_bg_mgdl, GlucoseUnit.MGDL); // this.meterTime = meter.meter_time; // } // // public GlucoseReading getMeterBG() { // return reading; // } // // public int getBgMgdl() { // return reading.asMgdl(); // } // // public int getMeterTime() { // return meterTime; // } // // @Override // public MeterEntry toProtobuf() { // MeterEntry.Builder builder = new MeterEntry.Builder(); // return builder.sys_timestamp_sec(rawSystemTimeSeconds) // .disp_timestamp_sec(rawDisplayTimeSeconds) // .meter_time(meterTime) // .meter_bg_mgdl(reading.asMgdl()) // .build(); // } // // public static List<MeterEntry> toProtobufList(List<MeterRecord> list) { // return toProtobufList(list, MeterEntry.class); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // if (!super.equals(o)) return false; // // MeterRecord that = (MeterRecord) o; // // if (meterTime != that.meterTime) return false; // if (!reading.equals(that.reading)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + meterTime; // result = 31 * result + reading.hashCode(); // return result; // } // } // Path: core/src/test/java/com/nightscout/core/dexcom/MeterRecordTest.java import static org.junit.Assert.assertThat; import com.nightscout.core.dexcom.records.MeterRecord; import org.junit.Test; import static org.hamcrest.Matchers.is; // Meter Record: 2880180BC52B180B71000A80180BAC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 4CB51A0BE9601A0B46002EB51A0B73 // Record EGV: 70 Meter time: 186299694 display time: 1417071321000 system time: 186299724 // Meter Record: 63B51A0B00611A0B480045B51A0BB1 // Record EGV: 72 Meter time: 186299717 display time: 1417071344000 system time: 186299747 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 // Meter Record: 2880180BC52B180B71000A80180BAC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 4CB51A0BE9601A0B46002EB51A0B73 // Record EGV: 70 Meter time: 186299694 display time: 1417071321000 system time: 186299724 // Meter Record: 63B51A0B00611A0B480045B51A0BB1 // Record EGV: 72 Meter time: 186299717 display time: 1417071344000 system time: 186299747 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 package com.nightscout.core.dexcom; public class MeterRecordTest { // Meter Record: 28 80 18 0B C5 2B 18 0B 71 00 0A 80 18 0B AC // Record EGV: 113 Meter time: 186155018 display time: 1416926645000 system time: 186155048 // Meter Record: 7CD01A0B1A7C1A0B06015ED01A0B06 // Record EGV: 262 Meter time: 186306654 display time: 1417078282000 system time: 186306684 @Test public void shouldParseMeterRecord() throws Exception { byte[] record = new byte[]{(byte) 0x28, (byte) 0x80, (byte) 0x18, (byte) 0x0B, (byte) 0xC5, (byte) 0x2B, (byte) 0x18, (byte) 0x0B, (byte) 0x71, (byte) 0x00, (byte) 0x0A, (byte) 0x80, (byte) 0x18, (byte) 0x0B, (byte) 0xAC};
MeterRecord meterRecord = new MeterRecord(record);
nightscout/android-uploader
app/src/main/java/com/nightscout/android/wearables/Pebble.java
// Path: core/src/main/java/com/nightscout/core/utils/GlucoseReading.java // public class GlucoseReading { // private int valueMgdl; // // public GlucoseReading(float value, GlucoseUnit units) { // this.valueMgdl = (units == GlucoseUnit.MGDL) ? // Math.round(value) : Math.round(value * Constants.MMOL_L_TO_MG_DL); // } // // public float asMmol() { // return valueMgdl * Constants.MG_DL_TO_MMOL_L; // } // // public String asMmolStr() { // return String.format("%.1f", asMmol()); // } // // public int asMgdl() { // return valueMgdl; // } // // public String asMgdlStr() { // return String.valueOf(valueMgdl); // } // // public float as(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdl() : asMmol(); // } // // public String asStr(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdlStr() : asMmolStr(); // } // // public GlucoseReading subtract(GlucoseReading reading) { // return new GlucoseReading(valueMgdl - reading.asMgdl(), GlucoseUnit.MGDL); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // GlucoseReading that = (GlucoseReading) o; // // if (valueMgdl != that.valueMgdl) return false; // // return true; // } // // @Override // public int hashCode() { // return valueMgdl; // } // }
import android.content.Context; import android.util.Log; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import com.nightscout.android.drivers.AndroidUploaderDevice; import com.nightscout.core.dexcom.TrendArrow; import com.nightscout.core.model.GlucoseUnit; import com.nightscout.core.utils.GlucoseReading; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.util.UUID;
package com.nightscout.android.wearables; public class Pebble { // CGM_ICON_KEY = 0x0, // TUPLE_CSTRING, MAX 2 BYTES (10) // CGM_BG_KEY = 0x1, // TUPLE_CSTRING, MAX 4 BYTES (253 OR 22.2) // CGM_TCGM_KEY = 0x2, // TUPLE_INT, 4 BYTES (CGM TIME) // CGM_TAPP_KEY = 0x3, // TUPLE_INT, 4 BYTES (APP / PHONE TIME) // CGM_DLTA_KEY = 0x4, // TUPLE_CSTRING, MAX 5 BYTES (BG DELTA, -100 or -10.0) // CGM_UBAT_KEY = 0x5, // TUPLE_CSTRING, MAX 3 BYTES (UPLOADER BATTERY, 100) // CGM_NAME_KEY = 0x6 // TUPLE_CSTRING, MAX 9 BYTES (Christine) public static final UUID PEBBLEAPP_UUID = UUID.fromString("2c3f5ab3-7506-44e7-b8d0-2c63de32e1ec"); public static final int ICON_KEY = 0; public static final int BG_KEY = 1; public static final int RECORD_TIME_KEY = 2; public static final int PHONE_TIME_KEY = 3; public static final int BG_DELTA_KEY = 4; public static final int UPLOADER_BATTERY_KEY = 5; public static final int NAME_KEY = 6; private static final String TAG = Pebble.class.getSimpleName(); private Context context; private PebbleDictionary currentReading; private GlucoseUnit units = GlucoseUnit.MGDL; private String pwdName = "";
// Path: core/src/main/java/com/nightscout/core/utils/GlucoseReading.java // public class GlucoseReading { // private int valueMgdl; // // public GlucoseReading(float value, GlucoseUnit units) { // this.valueMgdl = (units == GlucoseUnit.MGDL) ? // Math.round(value) : Math.round(value * Constants.MMOL_L_TO_MG_DL); // } // // public float asMmol() { // return valueMgdl * Constants.MG_DL_TO_MMOL_L; // } // // public String asMmolStr() { // return String.format("%.1f", asMmol()); // } // // public int asMgdl() { // return valueMgdl; // } // // public String asMgdlStr() { // return String.valueOf(valueMgdl); // } // // public float as(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdl() : asMmol(); // } // // public String asStr(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdlStr() : asMmolStr(); // } // // public GlucoseReading subtract(GlucoseReading reading) { // return new GlucoseReading(valueMgdl - reading.asMgdl(), GlucoseUnit.MGDL); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // GlucoseReading that = (GlucoseReading) o; // // if (valueMgdl != that.valueMgdl) return false; // // return true; // } // // @Override // public int hashCode() { // return valueMgdl; // } // } // Path: app/src/main/java/com/nightscout/android/wearables/Pebble.java import android.content.Context; import android.util.Log; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import com.nightscout.android.drivers.AndroidUploaderDevice; import com.nightscout.core.dexcom.TrendArrow; import com.nightscout.core.model.GlucoseUnit; import com.nightscout.core.utils.GlucoseReading; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.util.UUID; package com.nightscout.android.wearables; public class Pebble { // CGM_ICON_KEY = 0x0, // TUPLE_CSTRING, MAX 2 BYTES (10) // CGM_BG_KEY = 0x1, // TUPLE_CSTRING, MAX 4 BYTES (253 OR 22.2) // CGM_TCGM_KEY = 0x2, // TUPLE_INT, 4 BYTES (CGM TIME) // CGM_TAPP_KEY = 0x3, // TUPLE_INT, 4 BYTES (APP / PHONE TIME) // CGM_DLTA_KEY = 0x4, // TUPLE_CSTRING, MAX 5 BYTES (BG DELTA, -100 or -10.0) // CGM_UBAT_KEY = 0x5, // TUPLE_CSTRING, MAX 3 BYTES (UPLOADER BATTERY, 100) // CGM_NAME_KEY = 0x6 // TUPLE_CSTRING, MAX 9 BYTES (Christine) public static final UUID PEBBLEAPP_UUID = UUID.fromString("2c3f5ab3-7506-44e7-b8d0-2c63de32e1ec"); public static final int ICON_KEY = 0; public static final int BG_KEY = 1; public static final int RECORD_TIME_KEY = 2; public static final int PHONE_TIME_KEY = 3; public static final int BG_DELTA_KEY = 4; public static final int UPLOADER_BATTERY_KEY = 5; public static final int NAME_KEY = 6; private static final String TAG = Pebble.class.getSimpleName(); private Context context; private PebbleDictionary currentReading; private GlucoseUnit units = GlucoseUnit.MGDL; private String pwdName = "";
private GlucoseReading lastReading;
nightscout/android-uploader
core/src/main/java/com/nightscout/core/dexcom/SpecialValue.java
// Path: core/src/main/java/com/nightscout/core/utils/GlucoseReading.java // public class GlucoseReading { // private int valueMgdl; // // public GlucoseReading(float value, GlucoseUnit units) { // this.valueMgdl = (units == GlucoseUnit.MGDL) ? // Math.round(value) : Math.round(value * Constants.MMOL_L_TO_MG_DL); // } // // public float asMmol() { // return valueMgdl * Constants.MG_DL_TO_MMOL_L; // } // // public String asMmolStr() { // return String.format("%.1f", asMmol()); // } // // public int asMgdl() { // return valueMgdl; // } // // public String asMgdlStr() { // return String.valueOf(valueMgdl); // } // // public float as(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdl() : asMmol(); // } // // public String asStr(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdlStr() : asMmolStr(); // } // // public GlucoseReading subtract(GlucoseReading reading) { // return new GlucoseReading(valueMgdl - reading.asMgdl(), GlucoseUnit.MGDL); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // GlucoseReading that = (GlucoseReading) o; // // if (valueMgdl != that.valueMgdl) return false; // // return true; // } // // @Override // public int hashCode() { // return valueMgdl; // } // }
import com.google.common.base.Optional; import com.nightscout.core.utils.GlucoseReading;
package com.nightscout.core.dexcom; public enum SpecialValue { NONE("??0", 0), SENSOR_NOT_ACTIVE("?SN", 1), MINIMALLY_EGV_AB("??2", 2), NO_ANTENNA("?NA", 3), SENSOR_OUT_OF_CAL("?NC", 5), COUNTS_AB("?CD", 6), ABSOLUTE_AB("?AD", 9), POWER_AB("???", 10), RF_BAD_STATUS("?RF", 12); private String name; private int val; SpecialValue(String s, int i) { name = s; val = i; } public int getValue() { return val; } public String toString() { return name; } public static Optional<SpecialValue> getEGVSpecialValue(int val) { for (SpecialValue e : values()) { if (e.getValue() == val) return Optional.of(e); } return Optional.absent(); }
// Path: core/src/main/java/com/nightscout/core/utils/GlucoseReading.java // public class GlucoseReading { // private int valueMgdl; // // public GlucoseReading(float value, GlucoseUnit units) { // this.valueMgdl = (units == GlucoseUnit.MGDL) ? // Math.round(value) : Math.round(value * Constants.MMOL_L_TO_MG_DL); // } // // public float asMmol() { // return valueMgdl * Constants.MG_DL_TO_MMOL_L; // } // // public String asMmolStr() { // return String.format("%.1f", asMmol()); // } // // public int asMgdl() { // return valueMgdl; // } // // public String asMgdlStr() { // return String.valueOf(valueMgdl); // } // // public float as(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdl() : asMmol(); // } // // public String asStr(GlucoseUnit units) { // return (units == GlucoseUnit.MGDL) ? asMgdlStr() : asMmolStr(); // } // // public GlucoseReading subtract(GlucoseReading reading) { // return new GlucoseReading(valueMgdl - reading.asMgdl(), GlucoseUnit.MGDL); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // GlucoseReading that = (GlucoseReading) o; // // if (valueMgdl != that.valueMgdl) return false; // // return true; // } // // @Override // public int hashCode() { // return valueMgdl; // } // } // Path: core/src/main/java/com/nightscout/core/dexcom/SpecialValue.java import com.google.common.base.Optional; import com.nightscout.core.utils.GlucoseReading; package com.nightscout.core.dexcom; public enum SpecialValue { NONE("??0", 0), SENSOR_NOT_ACTIVE("?SN", 1), MINIMALLY_EGV_AB("??2", 2), NO_ANTENNA("?NA", 3), SENSOR_OUT_OF_CAL("?NC", 5), COUNTS_AB("?CD", 6), ABSOLUTE_AB("?AD", 9), POWER_AB("???", 10), RF_BAD_STATUS("?RF", 12); private String name; private int val; SpecialValue(String s, int i) { name = s; val = i; } public int getValue() { return val; } public String toString() { return name; } public static Optional<SpecialValue> getEGVSpecialValue(int val) { for (SpecialValue e : values()) { if (e.getValue() == val) return Optional.of(e); } return Optional.absent(); }
public static Optional<SpecialValue> getEGVSpecialValue(GlucoseReading reading) {
lesfurets/selenium-lxc
src/main/java/net/courtanet/selenium/common/selenium/junit/SiteTest.java
// Path: src/main/java/net/courtanet/selenium/common/selenium/SeleniumDriver.java // public enum SeleniumDriver { // // INSTANCE; // // private static final Logger LOGGER = Logger.getLogger(SeleniumDriver.class); // // private static final String IPHONE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)" // // + " AppleWebKit/534.46 (KHTML, like Gecko)" // // + " Version/5.1 Mobile/9A334 Safari/7534.48.3"; // // public WebDriver getDriver() { // LOGGER.info("Starting Firefox WebDriver for LesFurets"); // // FirefoxProfile profile = new FirefoxProfile(); // profile.setPreference("dom.max_script_run_time", "999"); // // if (isMobile()) { // // use iphone user agent // LOGGER.info("Using Firefox with iPhone user agent"); // profile.setPreference("general.useragent.override", IPHONE_USER_AGENT); // } // // DesiredCapabilities capability = DesiredCapabilities.firefox(); // capability.setCapability(FirefoxDriver.PROFILE, profile); // // if (REMOTE_GRID_ENABLE.propertyBooleanValue()) { // // use selenium grid // LOGGER.info("Using remote WebDriver : " + REMOTE_GRID_URL.propertyValue()); // try { // return new RemoteWebDriver(new URL(REMOTE_GRID_URL.propertyValue()), capability); // } catch (MalformedURLException e) { // throw new RuntimeException("invalid grid URL: " + REMOTE_GRID_URL.propertyValue(), e); // } // } else { // // use local firefox // return new FirefoxDriver(capability); // } // } // }
import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import net.courtanet.selenium.common.selenium.SeleniumDriver;
/* * Copyright (C) by Courtanet, All Rights Reserved. */ package net.courtanet.selenium.common.selenium.junit; public abstract class SiteTest { @Rule public TestDescription watchman = new TestDescription(); private WebDriver driver; public WebDriver getDriver() { return driver; } @Before public void setUp() {
// Path: src/main/java/net/courtanet/selenium/common/selenium/SeleniumDriver.java // public enum SeleniumDriver { // // INSTANCE; // // private static final Logger LOGGER = Logger.getLogger(SeleniumDriver.class); // // private static final String IPHONE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)" // // + " AppleWebKit/534.46 (KHTML, like Gecko)" // // + " Version/5.1 Mobile/9A334 Safari/7534.48.3"; // // public WebDriver getDriver() { // LOGGER.info("Starting Firefox WebDriver for LesFurets"); // // FirefoxProfile profile = new FirefoxProfile(); // profile.setPreference("dom.max_script_run_time", "999"); // // if (isMobile()) { // // use iphone user agent // LOGGER.info("Using Firefox with iPhone user agent"); // profile.setPreference("general.useragent.override", IPHONE_USER_AGENT); // } // // DesiredCapabilities capability = DesiredCapabilities.firefox(); // capability.setCapability(FirefoxDriver.PROFILE, profile); // // if (REMOTE_GRID_ENABLE.propertyBooleanValue()) { // // use selenium grid // LOGGER.info("Using remote WebDriver : " + REMOTE_GRID_URL.propertyValue()); // try { // return new RemoteWebDriver(new URL(REMOTE_GRID_URL.propertyValue()), capability); // } catch (MalformedURLException e) { // throw new RuntimeException("invalid grid URL: " + REMOTE_GRID_URL.propertyValue(), e); // } // } else { // // use local firefox // return new FirefoxDriver(capability); // } // } // } // Path: src/main/java/net/courtanet/selenium/common/selenium/junit/SiteTest.java import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import net.courtanet.selenium.common.selenium.SeleniumDriver; /* * Copyright (C) by Courtanet, All Rights Reserved. */ package net.courtanet.selenium.common.selenium.junit; public abstract class SiteTest { @Rule public TestDescription watchman = new TestDescription(); private WebDriver driver; public WebDriver getDriver() { return driver; } @Before public void setUp() {
driver = SeleniumDriver.INSTANCE.getDriver();
infinispan/infinispan-simple-tutorials
integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/InfinispanHibernateCacheSpringLocal.java
// Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import java.util.List;
package org.infinispan.tutorial.simple.hibernate.cache.spring.local; @SpringBootApplication public class InfinispanHibernateCacheSpringLocal { private static final Logger log = LoggerFactory.getLogger(InfinispanHibernateCacheSpringLocal.class); @Autowired private EntityManagerFactory emf; @Bean public CommandLineRunner demo() { return (args) -> { SecondLevelCacheStatistics eventCacheStats; SecondLevelCacheStatistics personCacheStats; Statistics stats; // Persist 3 entities, stats should show 3 second level cache puts persistEntities();
// Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/InfinispanHibernateCacheSpringLocal.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import java.util.List; package org.infinispan.tutorial.simple.hibernate.cache.spring.local; @SpringBootApplication public class InfinispanHibernateCacheSpringLocal { private static final Logger log = LoggerFactory.getLogger(InfinispanHibernateCacheSpringLocal.class); @Autowired private EntityManagerFactory emf; @Bean public CommandLineRunner demo() { return (args) -> { SecondLevelCacheStatistics eventCacheStats; SecondLevelCacheStatistics personCacheStats; Statistics stats; // Persist 3 entities, stats should show 3 second level cache puts persistEntities();
eventCacheStats = getCacheStatistics(Event.class.getName());
infinispan/infinispan-simple-tutorials
integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/InfinispanHibernateCacheSpringLocal.java
// Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import java.util.List;
stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Repeat query, expect: // * two cache hits for the number of entities in cache // * a query cache hit queryEntities(); stats = getStatistics(); printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2); printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1); // Update one of the persisted entities, stats should show a cache hit and a cache put updateEntity(2L); eventCacheStats = getCacheStatistics(Event.class.getName()); printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1); printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1); // Repeat query after update, expect: // * no cache hits or puts since entities are already cached // * a query cache miss and query cache put, because when an entity is updated, // any queries for that type are invalidated queryEntities(); stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(),1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Save cache-expiring entity, stats should show a second level cache put saveExpiringEntity();
// Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/spring-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/spring/local/InfinispanHibernateCacheSpringLocal.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import java.util.List; stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Repeat query, expect: // * two cache hits for the number of entities in cache // * a query cache hit queryEntities(); stats = getStatistics(); printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2); printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1); // Update one of the persisted entities, stats should show a cache hit and a cache put updateEntity(2L); eventCacheStats = getCacheStatistics(Event.class.getName()); printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1); printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1); // Repeat query after update, expect: // * no cache hits or puts since entities are already cached // * a query cache miss and query cache put, because when an entity is updated, // any queries for that type are invalidated queryEntities(); stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(),1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Save cache-expiring entity, stats should show a second level cache put saveExpiringEntity();
personCacheStats = getCacheStatistics(Person.class.getName());
infinispan/infinispan-simple-tutorials
integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/util/ClearStatistics.java // public class ClearStatistics { // // @Inject // private EntityManager em; // // @AroundInvoke // public Object clearStatistics(InvocationContext ic) throws Exception { // em.unwrap(Session.class).getSessionFactory().getStatistics().clear(); // return ic.proceed(); // } // // }
import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.util.ClearStatistics; import javax.ejb.Stateless; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.util.List;
package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller; @Stateless @Interceptors(ClearStatistics.class) public class PersistenceManager { @Inject private EntityManager em; public void persistEntities() {
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/util/ClearStatistics.java // public class ClearStatistics { // // @Inject // private EntityManager em; // // @AroundInvoke // public Object clearStatistics(InvocationContext ic) throws Exception { // em.unwrap(Session.class).getSessionFactory().getStatistics().clear(); // return ic.proceed(); // } // // } // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.util.ClearStatistics; import javax.ejb.Stateless; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.util.List; package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller; @Stateless @Interceptors(ClearStatistics.class) public class PersistenceManager { @Inject private EntityManager em; public void persistEntities() {
em.persist(new Event("Caught a pokemon!"));
infinispan/infinispan-simple-tutorials
integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/util/ClearStatistics.java // public class ClearStatistics { // // @Inject // private EntityManager em; // // @AroundInvoke // public Object clearStatistics(InvocationContext ic) throws Exception { // em.unwrap(Session.class).getSessionFactory().getStatistics().clear(); // return ic.proceed(); // } // // }
import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.util.ClearStatistics; import javax.ejb.Stateless; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.util.List;
package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller; @Stateless @Interceptors(ClearStatistics.class) public class PersistenceManager { @Inject private EntityManager em; public void persistEntities() { em.persist(new Event("Caught a pokemon!")); em.persist(new Event("Hatched an egg")); em.persist(new Event("Became a gym leader")); } public void findEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); out.append(String.format("Found entity: %s%n", event)); } public void updateEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); event.setName("Caught a Snorlax!!"); out.append(String.format("Updated entity: %s%n", event)); } public void deleteEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); em.remove(event); out.append(String.format("Removed entity: %s%n", event)); } public void evictEntity(long id) { em.getEntityManagerFactory().getCache().evict(Event.class, id); } public void persistExpiringEntity() {
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/util/ClearStatistics.java // public class ClearStatistics { // // @Inject // private EntityManager em; // // @AroundInvoke // public Object clearStatistics(InvocationContext ic) throws Exception { // em.unwrap(Session.class).getSessionFactory().getStatistics().clear(); // return ic.proceed(); // } // // } // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.util.ClearStatistics; import javax.ejb.Stateless; import javax.inject.Inject; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.util.List; package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller; @Stateless @Interceptors(ClearStatistics.class) public class PersistenceManager { @Inject private EntityManager em; public void persistEntities() { em.persist(new Event("Caught a pokemon!")); em.persist(new Event("Hatched an egg")); em.persist(new Event("Became a gym leader")); } public void findEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); out.append(String.format("Found entity: %s%n", event)); } public void updateEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); event.setName("Caught a Snorlax!!"); out.append(String.format("Updated entity: %s%n", event)); } public void deleteEntity(long id, StringBuilder out) { Event event = em.find(Event.class, id); em.remove(event); out.append(String.format("Removed entity: %s%n", event)); } public void evictEntity(long id) { em.getEntityManagerFactory().getCache().evict(Event.class, id); } public void persistExpiringEntity() {
em.persist(new Person("Satoshi"));
infinispan/infinispan-simple-tutorials
infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME;
package org.infinispan.tutorial.simple.remote.query; /** * The Remote Query simple tutorial. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteQuery { public static void main(String[] args) throws Exception {
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; package org.infinispan.tutorial.simple.remote.query; /** * The Remote Query simple tutorial. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteQuery { public static void main(String[] args) throws Exception {
ConfigurationBuilder builder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/persistence/sql-store/src/main/java/org/infinispan/tutorial/simple/remote/persistence/SQLStoreLibraryMain.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI; import java.util.Scanner;
package org.infinispan.tutorial.simple.remote.persistence; public class SQLStoreLibraryMain { public static final String AUTHORS_CACHE = "authors-cache"; public static final String BOOKS_CACHE = "books-cache"; public static void main(String[] args) throws Exception { DBCreator dbCreator = new DBCreator(); dbCreator.startDBServer("9123"); dbCreator.createAndPopulate();
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/persistence/sql-store/src/main/java/org/infinispan/tutorial/simple/remote/persistence/SQLStoreLibraryMain.java import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI; import java.util.Scanner; package org.infinispan.tutorial.simple.remote.persistence; public class SQLStoreLibraryMain { public static final String AUTHORS_CACHE = "authors-cache"; public static final String BOOKS_CACHE = "books-cache"; public static void main(String[] args) throws Exception { DBCreator dbCreator = new DBCreator(); dbCreator.startDBServer("9123"); dbCreator.createAndPopulate();
ConfigurationBuilder configurationBuilder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.tutorial.simple.connect.Infinispan; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.UUID; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME;
package org.infinispan.tutorial.simple.remote.query; /** * The Remote Continuous Query simple tutorial. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteContinuousQuery { // USERS will be used to create random posts private static final List<String> USERS = Arrays.asList( "gustavoalle", "remerson", "anistor", "karesti", "ttarrant", "belen_esteban", "dberindei", "galderz", "wburns", "pruivo", "oliveira", "vrigamonti"); // HASHTAGS will be used to create random posts private static final List<String> HASHTAGS = Arrays.asList( "love", "instagood", "photooftheday", "fashion", "beautiful", "happy", "cute", "tbt", "like4like", "followme", "infinispan"); private static final String CACHE_NAME = "instaposts"; public static void main(String[] args) throws Exception { // Connect to the server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.tutorial.simple.connect.Infinispan; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.UUID; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; package org.infinispan.tutorial.simple.remote.query; /** * The Remote Continuous Query simple tutorial. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteContinuousQuery { // USERS will be used to create random posts private static final List<String> USERS = Arrays.asList( "gustavoalle", "remerson", "anistor", "karesti", "ttarrant", "belen_esteban", "dberindei", "galderz", "wburns", "pruivo", "oliveira", "vrigamonti"); // HASHTAGS will be used to create random posts private static final List<String> HASHTAGS = Arrays.asList( "love", "instagood", "photooftheday", "fashion", "beautiful", "happy", "cute", "tbt", "like4like", "followme", "infinispan"); private static final String CACHE_NAME = "instaposts"; public static void main(String[] args) throws Exception { // Connect to the server
RemoteCacheManager client = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import javax.transaction.TransactionManager; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup; import org.infinispan.commons.configuration.XMLStringConfiguration; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI;
package org.infinispan.tutorial.simple.remote.transaction; /** * The Hot Rod transaction simple tutorial. * <p> * Hot Rod Transactions are available as of Infinispan version 9.3. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Pedro Ruivo */ public class InfinispanRemoteTx { private static final String CACHE_NAME = "simple-tx-cache"; public static void main(String[] args) throws Exception { // Create a configuration for a locally-running server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java import javax.transaction.TransactionManager; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup; import org.infinispan.commons.configuration.XMLStringConfiguration; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI; package org.infinispan.tutorial.simple.remote.transaction; /** * The Hot Rod transaction simple tutorial. * <p> * Hot Rod Transactions are available as of Infinispan version 9.3. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Pedro Ruivo */ public class InfinispanRemoteTx { private static final String CACHE_NAME = "simple-tx-cache"; public static void main(String[] args) throws Exception { // Create a configuration for a locally-running server
ConfigurationBuilder builder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.tutorial.simple.connect.Infinispan;
package org.infinispan.tutorial.simple.remote.percache; /** * * You can define per-cache configuration using org.infinispan templates or * cache definitions in XML format. Then, if you invoke the `getCache()` method * for a remote cache that does not exist, Infinispan creates the cache with * the configuration instead of returning null. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author <a href="mailto:[email protected]">Don Naro</a> */ public class InfinispanRemotePerCache { public static void main(String[] args) throws Exception { // Create a configuration for a locally-running server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.tutorial.simple.connect.Infinispan; package org.infinispan.tutorial.simple.remote.percache; /** * * You can define per-cache configuration using org.infinispan templates or * cache definitions in XML format. Then, if you invoke the `getCache()` method * for a remote cache that does not exist, Infinispan creates the cache with * the configuration instead of returning null. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author <a href="mailto:[email protected]">Don Naro</a> */ public class InfinispanRemotePerCache { public static void main(String[] args) throws Exception { // Create a configuration for a locally-running server
ConfigurationBuilder builder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/tasks/src/main/java/org/infinispan/tutorial/simple/server/tasks/InfinispanServerTasks.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestURI; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JAVASCRIPT; import static org.infinispan.commons.util.Util.getResourceAsString;
package org.infinispan.tutorial.simple.server.tasks; public class InfinispanServerTasks { public static void main(String[] args) throws Exception {
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/tasks/src/main/java/org/infinispan/tutorial/simple/server/tasks/InfinispanServerTasks.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestURI; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JAVASCRIPT; import static org.infinispan.commons.util.Util.getResourceAsString; package org.infinispan.tutorial.simple.server.tasks; public class InfinispanServerTasks { public static void main(String[] args) throws Exception {
RemoteCacheManager remoteCacheManager = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import java.time.Duration; import java.time.Instant; import java.util.Random; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.NearCacheMode; import org.infinispan.tutorial.simple.connect.Infinispan;
package org.infinispan.tutorial.simple.nearcache; public class InfinispanNearCache { public static final String CACHE_WITH_NEAR_CACHING = "testCacheNearCaching"; public static void main(String[] args) {
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java import java.time.Duration; import java.time.Instant; import java.util.Random; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.NearCacheMode; import org.infinispan.tutorial.simple.connect.Infinispan; package org.infinispan.tutorial.simple.nearcache; public class InfinispanNearCache { public static final String CACHE_WITH_NEAR_CACHING = "testCacheNearCaching"; public static void main(String[] args) {
ConfigurationBuilder builder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI;
package org.infinispan.tutorial.simple.encoding; public class InfinispanEncodingCaches { public static void main(String[] args) throws Exception {
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI; package org.infinispan.tutorial.simple.encoding; public class InfinispanEncodingCaches { public static void main(String[] args) throws Exception {
ConfigurationBuilder builder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger;
package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal {
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger; package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal {
public static final String EVENT_REGION_NAME = "wildfly-local.war#events." + Event.class.getName();
infinispan/infinispan-simple-tutorials
integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger;
package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal { public static final String EVENT_REGION_NAME = "wildfly-local.war#events." + Event.class.getName();
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger; package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal { public static final String EVENT_REGION_NAME = "wildfly-local.war#events." + Event.class.getName();
public static final String PERSON_REGION_NAME = "wildfly-local.war#events." + Person.class.getName();
infinispan/infinispan-simple-tutorials
integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger;
package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal { public static final String EVENT_REGION_NAME = "wildfly-local.war#events." + Event.class.getName(); public static final String PERSON_REGION_NAME = "wildfly-local.war#events." + Person.class.getName(); @Inject private Logger log; @Inject private EntityManager em; @Inject
// Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/controller/PersistenceManager.java // @Stateless // @Interceptors(ClearStatistics.class) // public class PersistenceManager { // // @Inject // private EntityManager em; // // public void persistEntities() { // em.persist(new Event("Caught a pokemon!")); // em.persist(new Event("Hatched an egg")); // em.persist(new Event("Became a gym leader")); // } // // public void findEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // out.append(String.format("Found entity: %s%n", event)); // } // // public void updateEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // event.setName("Caught a Snorlax!!"); // out.append(String.format("Updated entity: %s%n", event)); // } // // public void deleteEntity(long id, StringBuilder out) { // Event event = em.find(Event.class, id); // em.remove(event); // out.append(String.format("Removed entity: %s%n", event)); // } // // public void evictEntity(long id) { // em.getEntityManagerFactory().getCache().evict(Event.class, id); // } // // public void persistExpiringEntity() { // em.persist(new Person("Satoshi")); // } // // public void queryEntities(StringBuilder out) { // TypedQuery<Event> query = em.createQuery("from Event", Event.class); // query.setHint("org.hibernate.cacheable", Boolean.TRUE); // List<Event> events = query.getResultList(); // out.append(String.format("Queried events: %s%n", events)); // } // // public void findExpiringEntity(long id, StringBuilder out) { // Person person = em.find(Person.class, id); // out.append(String.format("Found expiring entity: %s%n", person)); // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/wildfly-local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/wildfly/local/InfinispanHibernateCacheWildflyLocal.java import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.controller.PersistenceManager; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.wildfly.local.model.Person; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.logging.Logger; package org.infinispan.tutorial.simple.hibernate.cache.wildfly.local; /** * Start Wildfly, then: * * mvn clean package wildfly:deploy * for i in {1..15}; do curl http://localhost:8080/wildfly-local/infinispan/hibernate-cache/$i; done * */ @Path("/") public class InfinispanHibernateCacheWildflyLocal { public static final String EVENT_REGION_NAME = "wildfly-local.war#events." + Event.class.getName(); public static final String PERSON_REGION_NAME = "wildfly-local.war#events." + Person.class.getName(); @Inject private Logger log; @Inject private EntityManager em; @Inject
private PersistenceManager ejb;
infinispan/infinispan-simple-tutorials
infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.tutorial.simple.connect.Infinispan;
package org.infinispan.tutorial.simple.remote.listen; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteListen { public static void main(String[] args) throws InterruptedException { // Connect to the server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.tutorial.simple.connect.Infinispan; package org.infinispan.tutorial.simple.remote.listen; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteListen { public static void main(String[] args) throws InterruptedException { // Connect to the server
RemoteCacheManager cacheManager = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.multimap.MultimapCacheManager; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.client.hotrod.multimap.RemoteMultimapCacheManagerFactory; import org.infinispan.tutorial.simple.connect.Infinispan;
package org.infinispan.tutorial.simple.remote.multimap; /** * The Remote Multimap simple tutorial. * <p> * Remote multimap is available as of Infinispan version 9.2. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteMultimap { public static void main(String[] args) throws Exception { // Connect to the server and create a cache
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.multimap.MultimapCacheManager; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.client.hotrod.multimap.RemoteMultimapCacheManagerFactory; import org.infinispan.tutorial.simple.connect.Infinispan; package org.infinispan.tutorial.simple.remote.multimap; /** * The Remote Multimap simple tutorial. * <p> * Remote multimap is available as of Infinispan version 9.2. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Katia Aresti, [email protected] */ public class InfinispanRemoteMultimap { public static void main(String[] args) throws Exception { // Connect to the server and create a cache
RemoteCacheManager cacheManager = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/security/tls-authorization/src/main/java/org/infinispan/tutorial/simple/security/tls/InfinispanTlsConnection.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
package org.infinispan.tutorial.simple.security.tls; /** * Different client configurations that demonstrate SSL/TLS encryption with * server and client certificates as well as security authorization. * * @author <a href="mailto:[email protected]">Wolf-Dieter Fink</a> * */ public class InfinispanTlsConnection { public static void main(String[] args) { System.out.println(" Read the System env TEST if such exist."); String testEnv = System.getenv("TEST"); List<SSLConfig> sslConfigsToTest; if(testEnv == null || testEnv.isEmpty()) { System.out.println(" TEST env not defined. Test all SSL configurations."); sslConfigsToTest = List.of(SSLConfig.values()); } else { System.out.println(" TEST env defined: " + testEnv); sslConfigsToTest = Arrays.stream(testEnv.split(",")) .map(SSLConfig::valueOf) .collect(Collectors.toList()); } System.out.println(" Run tests " + sslConfigsToTest); System.out.println(" ======================= Start client(s)"); ConfigurationBuilder builder = new ConfigurationBuilder();
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/security/tls-authorization/src/main/java/org/infinispan/tutorial/simple/security/tls/InfinispanTlsConnection.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.tutorial.simple.connect.Infinispan; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; package org.infinispan.tutorial.simple.security.tls; /** * Different client configurations that demonstrate SSL/TLS encryption with * server and client certificates as well as security authorization. * * @author <a href="mailto:[email protected]">Wolf-Dieter Fink</a> * */ public class InfinispanTlsConnection { public static void main(String[] args) { System.out.println(" Read the System env TEST if such exist."); String testEnv = System.getenv("TEST"); List<SSLConfig> sslConfigsToTest; if(testEnv == null || testEnv.isEmpty()) { System.out.println(" TEST env not defined. Test all SSL configurations."); sslConfigsToTest = List.of(SSLConfig.values()); } else { System.out.println(" TEST env defined: " + testEnv); sslConfigsToTest = Arrays.stream(testEnv.split(",")) .map(SSLConfig::valueOf) .collect(Collectors.toList()); } System.out.println(" Run tests " + sslConfigsToTest); System.out.println(" ======================= Start client(s)"); ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host(Infinispan.HOST)
infinispan/infinispan-simple-tutorials
infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI;
package org.infinispan.tutorial.simple.remote; /** * Run the Infinispan Server using the Docker Image * Or make sure you create a user that is called 'admin'. * Check more about authorization in the Infinispan Documentation. */ public class InfinispanAuthorizationCache { public static void main(String[] args) throws Exception {
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.tutorial.simple.connect.Infinispan; import java.net.URI; package org.infinispan.tutorial.simple.remote; /** * Run the Infinispan Server using the Docker Image * Or make sure you create a user that is called 'admin'. * Check more about authorization in the Infinispan Documentation. */ public class InfinispanAuthorizationCache { public static void main(String[] args) throws Exception {
ConfigurationBuilder configurationBuilder = Infinispan.connectionConfig();
infinispan/infinispan-simple-tutorials
infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // }
import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; import org.infinispan.tutorial.simple.connect.Infinispan;
package org.infinispan.tutorial.simple.remote.counter; /** * Remote Counter simple tutorial. * <p> * Remote counters are available as of Infinispan version 9.2. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Pedro Ruivo */ public class InfinispanRemoteCounter { public static void main(String[] args) throws Exception { // Connect to the server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // Path: infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; import org.infinispan.tutorial.simple.connect.Infinispan; package org.infinispan.tutorial.simple.remote.counter; /** * Remote Counter simple tutorial. * <p> * Remote counters are available as of Infinispan version 9.2. * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * * @author Pedro Ruivo */ public class InfinispanRemoteCounter { public static void main(String[] args) throws Exception { // Connect to the server
RemoteCacheManager cacheManager = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // // Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public static final String TUTORIAL_CACHE_NAME = "test";
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.tutorial.simple.connect.Infinispan; import static org.infinispan.tutorial.simple.connect.Infinispan.TUTORIAL_CACHE_NAME;
package org.infinispan.tutorial.simple.remote; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteCache { public static void main(String[] args) { // Connect to the server
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // // Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public static final String TUTORIAL_CACHE_NAME = "test"; // Path: infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.tutorial.simple.connect.Infinispan; import static org.infinispan.tutorial.simple.connect.Infinispan.TUTORIAL_CACHE_NAME; package org.infinispan.tutorial.simple.remote; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteCache { public static void main(String[] args) { // Connect to the server
RemoteCacheManager cacheManager = Infinispan.connect();
infinispan/infinispan-simple-tutorials
infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // // Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public static final String TUTORIAL_CACHE_NAME = "test";
import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.tutorial.simple.connect.Infinispan; import static org.infinispan.tutorial.simple.connect.Infinispan.TUTORIAL_CACHE_NAME;
package org.infinispan.tutorial.simple.remote; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteCache { public static void main(String[] args) { // Connect to the server RemoteCacheManager cacheManager = Infinispan.connect(); // Obtain the remote cache
// Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public class Infinispan { // // public static final String USER = "admin"; // public static final String PASSWORD = "password"; // // public static final String TUTORIAL_CACHE_NAME = "test"; // public static final String HOST = "127.0.0.1"; // // public static final String TUTORIAL_CACHE_CONFIG = // "<distributed-cache name=\"CACHE_NAME\">\n" // + " <encoding media-type=\"application/x-protostream\"/>\n" // + "</distributed-cache>"; // // /** // * Returns the configuration builder with the connection information // * // * @return a Configuration Builder with the connection config // */ // public static final ConfigurationBuilder connectionConfig() { // ConfigurationBuilder builder = new ConfigurationBuilder(); // builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT).security() // .authentication() // //Add user credentials. // .username(USER) // .password(PASSWORD); // // // Docker 4 Mac Workaround. Don't use BASIC intelligence in production // builder.clientIntelligence(ClientIntelligence.BASIC); // // // Make sure the remote cache is available. // // If the cache does not exist, the cache will be created // builder.remoteCache(TUTORIAL_CACHE_NAME) // .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); // return builder; // } // // /** // * Connect to the running Infinispan Server in localhost:11222. // * // * This method illustrates how to connect to a running Infinispan Server with a downloaded // * distribution or a container. // * // * @return a connected RemoteCacheManager // */ // public static final RemoteCacheManager connect() { // ConfigurationBuilder builder = connectionConfig(); // // RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // // // Clear the cache in case it already exists from a previous running tutorial // cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); // // // Return the connected cache manager // return cacheManager; // } // // } // // Path: infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/Infinispan.java // public static final String TUTORIAL_CACHE_NAME = "test"; // Path: infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.tutorial.simple.connect.Infinispan; import static org.infinispan.tutorial.simple.connect.Infinispan.TUTORIAL_CACHE_NAME; package org.infinispan.tutorial.simple.remote; /** * * Infinispan Server includes a default property realm that requires * authentication. Create some credentials before you run this tutorial. * */ public class InfinispanRemoteCache { public static void main(String[] args) { // Connect to the server RemoteCacheManager cacheManager = Infinispan.connect(); // Obtain the remote cache
RemoteCache<String, String> cache = cacheManager.getCache(TUTORIAL_CACHE_NAME);
infinispan/infinispan-simple-tutorials
integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/InfinispanHibernateCacheLocal.java
// Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Person;
package org.infinispan.tutorial.simple.hibernate.cache.local; /** * Example on how to use Infinispan as Hibernate cache provider * in a standalone, single-node, environment. * * This example assumes that the JPA persistence configuration file * is present in the default lookup location: META-INF/persistence.xml * * Run with these properties to hide Hibernate messages: * -Dlog4j.configurationFile=src/main/resources/log4j2-tutorial.xml */ public class InfinispanHibernateCacheLocal { private static EntityManagerFactory emf; public static void main(String[] args) throws Exception { // Create JPA persistence manager emf = Persistence.createEntityManagerFactory("events"); SecondLevelCacheStatistics eventCacheStats; SecondLevelCacheStatistics personCacheStats; Statistics stats; // Persist 3 entities, stats should show 3 second level cache puts persistEntities();
// Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/InfinispanHibernateCacheLocal.java import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Person; package org.infinispan.tutorial.simple.hibernate.cache.local; /** * Example on how to use Infinispan as Hibernate cache provider * in a standalone, single-node, environment. * * This example assumes that the JPA persistence configuration file * is present in the default lookup location: META-INF/persistence.xml * * Run with these properties to hide Hibernate messages: * -Dlog4j.configurationFile=src/main/resources/log4j2-tutorial.xml */ public class InfinispanHibernateCacheLocal { private static EntityManagerFactory emf; public static void main(String[] args) throws Exception { // Create JPA persistence manager emf = Persistence.createEntityManagerFactory("events"); SecondLevelCacheStatistics eventCacheStats; SecondLevelCacheStatistics personCacheStats; Statistics stats; // Persist 3 entities, stats should show 3 second level cache puts persistEntities();
eventCacheStats = getCacheStatistics(Event.class.getName());
infinispan/infinispan-simple-tutorials
integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/InfinispanHibernateCacheLocal.java
// Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // }
import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Person;
stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Repeat query, expect: // * two cache hits for the number of entities in cache // * a query cache hit queryEntities(); stats = getStatistics(); printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2); printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1); // Update one of the persisted entities, stats should show a cache hit and a cache put updateEntity(2L); eventCacheStats = getCacheStatistics(Event.class.getName()); printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1); printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1); // Repeat query after update, expect: // * no cache hits or puts since entities are already cached // * a query cache miss and query cache put, because when an entity is updated, // any queries for that type are invalidated queryEntities(); stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(),1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Save cache-expiring entity, stats should show a second level cache put saveExpiringEntity();
// Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Event.java // @Entity // @Cacheable // public class Event { // // @Id // @GeneratedValue // private Long id; // // private String name; // // private LocalDateTime timestamp = LocalDateTime.now(); // // public Event(String name) { // this.name = name; // } // // public Event() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public LocalDateTime getTimestamp() { // return timestamp; // } // // public void setTimestamp(LocalDateTime timestamp) { // this.timestamp = timestamp; // } // // @Override // public String toString() { // return "Event{" + // "id=" + id + // ", name='" + name + '\'' + // ", time=" + timestamp + // '}'; // } // // } // // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/model/Person.java // @Entity // @Cacheable // public class Person { // // @Id // @GeneratedValue // private Long id; // private String name; // // public Person(String name) { // this.name = name; // } // // public Person() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String firstName) { // this.name = firstName; // } // // @Override // public String toString() { // return "Person{" + // "id=" + id + // ", name='" + name + '\'' + // '}'; // } // // } // Path: integrations/hibernate/local/src/main/java/org/infinispan/tutorial/simple/hibernate/cache/local/InfinispanHibernateCacheLocal.java import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Event; import org.infinispan.tutorial.simple.hibernate.cache.local.model.Person; stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Repeat query, expect: // * two cache hits for the number of entities in cache // * a query cache hit queryEntities(); stats = getStatistics(); printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2); printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1); // Update one of the persisted entities, stats should show a cache hit and a cache put updateEntity(2L); eventCacheStats = getCacheStatistics(Event.class.getName()); printfAssert("Event entity cache hits: %d (expected %d)%n", eventCacheStats.getHitCount(), 1); printfAssert("Event entity cache puts: %d (expected %d)%n", eventCacheStats.getPutCount(), 1); // Repeat query after update, expect: // * no cache hits or puts since entities are already cached // * a query cache miss and query cache put, because when an entity is updated, // any queries for that type are invalidated queryEntities(); stats = getStatistics(); printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(),1); printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1); // Save cache-expiring entity, stats should show a second level cache put saveExpiringEntity();
personCacheStats = getCacheStatistics(Person.class.getName());
TooTallNate/Java-WebSocket
src/test/java/org/java_websocket/framing/PingFrameTest.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the PingFrame class */ public class PingFrameTest { @Test public void testConstructor() { PingFrame frame = new PingFrame();
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/test/java/org/java_websocket/framing/PingFrameTest.java import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the PingFrame class */ public class PingFrameTest { @Test public void testConstructor() { PingFrame frame = new PingFrame();
assertEquals("Opcode must be equal", Opcode.PING, frame.getOpcode());
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java
// Path: src/main/java/org/java_websocket/WebSocketAdapter.java // public abstract class WebSocketAdapter implements WebSocketListener { // // private PingFrame pingFrame; // // /** // * This default implementation does not do anything. Go ahead and overwrite it. // * // * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, // * Draft, ClientHandshake) // */ // @Override // public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, // ClientHandshake request) throws InvalidDataException { // return new HandshakeImpl1Server(); // } // // @Override // public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, // ServerHandshake response) throws InvalidDataException { // //To overwrite // } // // /** // * This default implementation does not do anything which will cause the connections to always // * progress. // * // * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, // * ClientHandshake) // */ // @Override // public void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) // throws InvalidDataException { // //To overwrite // } // // /** // * This default implementation will send a pong in response to the received ping. The pong frame // * will have the same payload as the ping frame. // * // * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) // */ // @Override // public void onWebsocketPing(WebSocket conn, Framedata f) { // conn.sendFrame(new PongFrame((PingFrame) f)); // } // // /** // * This default implementation does not do anything. Go ahead and overwrite it. // * // * @see org.java_websocket.WebSocketListener#onWebsocketPong(WebSocket, Framedata) // */ // @Override // public void onWebsocketPong(WebSocket conn, Framedata f) { // //To overwrite // } // // /** // * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application // * data. // * // * @param conn The <tt>WebSocket</tt> connection from which the ping frame will be sent. // * @return PingFrame to be sent. // * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) // */ // @Override // public PingFrame onPreparePing(WebSocket conn) { // if (pingFrame == null) { // pingFrame = new PingFrame(); // } // return pingFrame; // } // } // // Path: src/main/java/org/java_websocket/WebSocketServerFactory.java // public interface WebSocketServerFactory extends WebSocketFactory { // // @Override // WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d); // // @Override // WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> drafts); // // /** // * Allows to wrap the SocketChannel( key.channel() ) to insert a protocol layer( like ssl or proxy // * authentication) beyond the ws layer. // * // * @param channel The SocketChannel to wrap // * @param key a SelectionKey of an open SocketChannel. // * @return The channel on which the read and write operations will be performed.<br> // * @throws IOException may be thrown while writing on the channel // */ // ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException; // // /** // * Allows to shutdown the websocket factory for a clean shutdown // */ // void close(); // }
import org.java_websocket.WebSocketServerFactory; import org.java_websocket.drafts.Draft; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.List; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.server; public class DefaultWebSocketServerFactory implements WebSocketServerFactory { @Override
// Path: src/main/java/org/java_websocket/WebSocketAdapter.java // public abstract class WebSocketAdapter implements WebSocketListener { // // private PingFrame pingFrame; // // /** // * This default implementation does not do anything. Go ahead and overwrite it. // * // * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, // * Draft, ClientHandshake) // */ // @Override // public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, // ClientHandshake request) throws InvalidDataException { // return new HandshakeImpl1Server(); // } // // @Override // public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, // ServerHandshake response) throws InvalidDataException { // //To overwrite // } // // /** // * This default implementation does not do anything which will cause the connections to always // * progress. // * // * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, // * ClientHandshake) // */ // @Override // public void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) // throws InvalidDataException { // //To overwrite // } // // /** // * This default implementation will send a pong in response to the received ping. The pong frame // * will have the same payload as the ping frame. // * // * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) // */ // @Override // public void onWebsocketPing(WebSocket conn, Framedata f) { // conn.sendFrame(new PongFrame((PingFrame) f)); // } // // /** // * This default implementation does not do anything. Go ahead and overwrite it. // * // * @see org.java_websocket.WebSocketListener#onWebsocketPong(WebSocket, Framedata) // */ // @Override // public void onWebsocketPong(WebSocket conn, Framedata f) { // //To overwrite // } // // /** // * Default implementation for onPreparePing, returns a (cached) PingFrame that has no application // * data. // * // * @param conn The <tt>WebSocket</tt> connection from which the ping frame will be sent. // * @return PingFrame to be sent. // * @see org.java_websocket.WebSocketListener#onPreparePing(WebSocket) // */ // @Override // public PingFrame onPreparePing(WebSocket conn) { // if (pingFrame == null) { // pingFrame = new PingFrame(); // } // return pingFrame; // } // } // // Path: src/main/java/org/java_websocket/WebSocketServerFactory.java // public interface WebSocketServerFactory extends WebSocketFactory { // // @Override // WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d); // // @Override // WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> drafts); // // /** // * Allows to wrap the SocketChannel( key.channel() ) to insert a protocol layer( like ssl or proxy // * authentication) beyond the ws layer. // * // * @param channel The SocketChannel to wrap // * @param key a SelectionKey of an open SocketChannel. // * @return The channel on which the read and write operations will be performed.<br> // * @throws IOException may be thrown while writing on the channel // */ // ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException; // // /** // * Allows to shutdown the websocket factory for a clean shutdown // */ // void close(); // } // Path: src/main/java/org/java_websocket/server/DefaultWebSocketServerFactory.java import org.java_websocket.WebSocketServerFactory; import org.java_websocket.drafts.Draft; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.List; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.server; public class DefaultWebSocketServerFactory implements WebSocketServerFactory { @Override
public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) {
TooTallNate/Java-WebSocket
src/test/java/org/java_websocket/framing/CloseFrameTest.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the CloseFrame class */ public class CloseFrameTest { @Test public void testConstructor() { CloseFrame frame = new CloseFrame();
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/test/java/org/java_websocket/framing/CloseFrameTest.java import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the CloseFrame class */ public class CloseFrameTest { @Test public void testConstructor() { CloseFrame frame = new CloseFrame();
assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode());
TooTallNate/Java-WebSocket
src/main/example/SSLServerExample.java
// Path: src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java // public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { // // protected SSLContext sslcontext; // protected ExecutorService exec; // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext) { // this(sslContext, Executors.newSingleThreadScheduledExecutor()); // } // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService exec) { // if (sslContext == null || exec == null) { // throw new IllegalArgumentException(); // } // this.sslcontext = sslContext; // this.exec = exec; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // /* // * See https://github.com/TooTallNate/Java-WebSocket/issues/466 // * // * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. // * E.g. firefox requests this cipher and this causes some dcs/instable connections // */ // List<String> ciphers = new ArrayList<>(Arrays.asList(e.getEnabledCipherSuites())); // ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); // e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { // return new WebSocketImpl(a, d); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> d) { // return new WebSocketImpl(a, d); // } // // @Override // public void close() { // exec.shutdown(); // } // }
import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ public class SSLServerExample { /* * Keystore with certificate created like so (in JKS format): * *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer( 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = "JKS"; String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") .toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance(STORETYPE); File kf = new File(KEYSTORE); ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, KEYPASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = null; sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// Path: src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java // public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { // // protected SSLContext sslcontext; // protected ExecutorService exec; // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext) { // this(sslContext, Executors.newSingleThreadScheduledExecutor()); // } // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService exec) { // if (sslContext == null || exec == null) { // throw new IllegalArgumentException(); // } // this.sslcontext = sslContext; // this.exec = exec; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // /* // * See https://github.com/TooTallNate/Java-WebSocket/issues/466 // * // * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. // * E.g. firefox requests this cipher and this causes some dcs/instable connections // */ // List<String> ciphers = new ArrayList<>(Arrays.asList(e.getEnabledCipherSuites())); // ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); // e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { // return new WebSocketImpl(a, d); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> d) { // return new WebSocketImpl(a, d); // } // // @Override // public void close() { // exec.shutdown(); // } // } // Path: src/main/example/SSLServerExample.java import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ public class SSLServerExample { /* * Keystore with certificate created like so (in JKS format): * *keytool -genkey -keyalg RSA -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer( 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = "JKS"; String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") .toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance(STORETYPE); File kf = new File(KEYSTORE); ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, KEYPASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = null; sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
chatserver.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
TooTallNate/Java-WebSocket
src/test/java/org/java_websocket/framing/FramedataImpl1Test.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.java_websocket.enums.Opcode; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.ByteBuffer;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the FramedataImpl1 class */ public class FramedataImpl1Test { @Test public void testDefaultValues() {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/test/java/org/java_websocket/framing/FramedataImpl1Test.java import org.java_websocket.enums.Opcode; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.ByteBuffer; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the FramedataImpl1 class */ public class FramedataImpl1Test { @Test public void testDefaultValues() {
FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY);
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/framing/ContinuousFrame.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.java_websocket.enums.Opcode;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a continuous frame */ public class ContinuousFrame extends DataFrame { /** * constructor which sets the opcode of this frame to continuous */ public ContinuousFrame() {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/main/java/org/java_websocket/framing/ContinuousFrame.java import org.java_websocket.enums.Opcode; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a continuous frame */ public class ContinuousFrame extends DataFrame { /** * constructor which sets the opcode of this frame to continuous */ public ContinuousFrame() {
super(Opcode.CONTINUOUS);
TooTallNate/Java-WebSocket
src/test/java/org/java_websocket/framing/BinaryFrameTest.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the BinaryFrame class */ public class BinaryFrameTest { @Test public void testConstructor() { BinaryFrame frame = new BinaryFrame();
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/test/java/org/java_websocket/framing/BinaryFrameTest.java import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * JUnit Test for the BinaryFrame class */ public class BinaryFrameTest { @Test public void testConstructor() { BinaryFrame frame = new BinaryFrame();
assertEquals("Opcode must be equal", Opcode.BINARY, frame.getOpcode());
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/framing/PingFrame.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.java_websocket.enums.Opcode;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a ping frame */ public class PingFrame extends ControlFrame { /** * constructor which sets the opcode of this frame to ping */ public PingFrame() {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/main/java/org/java_websocket/framing/PingFrame.java import org.java_websocket.enums.Opcode; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a ping frame */ public class PingFrame extends ControlFrame { /** * constructor which sets the opcode of this frame to ping */ public PingFrame() {
super(Opcode.PING);
TooTallNate/Java-WebSocket
src/main/example/SSLServerCustomWebsocketFactoryExample.java
// Path: src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java // public class CustomSSLWebSocketServerFactory extends DefaultSSLWebSocketServerFactory { // // /** // * The enabled protocols saved as a String array // */ // private final String[] enabledProtocols; // // /** // * The enabled ciphersuites saved as a String array // */ // private final String[] enabledCiphersuites; // // /** // * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher // * suites. // * // * @param sslContext - can not be <code>null</code> // * @param enabledProtocols - only these protocols are enabled, when <code>null</code> default // * settings will be used. // * @param enabledCiphersuites - only these cipher suites are enabled, when <code>null</code> // * default settings will be used. // */ // public CustomSSLWebSocketServerFactory(SSLContext sslContext, String[] enabledProtocols, // String[] enabledCiphersuites) { // this(sslContext, Executors.newSingleThreadScheduledExecutor(), enabledProtocols, // enabledCiphersuites); // } // // /** // * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher // * suites. // * // * @param sslContext - can not be <code>null</code> // * @param executerService - can not be <code>null</code> // * @param enabledProtocols - only these protocols are enabled, when <code>null</code> default // * settings will be used. // * @param enabledCiphersuites - only these cipher suites are enabled, when <code>null</code> // * default settings will be used. // */ // public CustomSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, // String[] enabledProtocols, String[] enabledCiphersuites) { // super(sslContext, executerService); // this.enabledProtocols = enabledProtocols; // this.enabledCiphersuites = enabledCiphersuites; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // if (enabledProtocols != null) { // e.setEnabledProtocols(enabledProtocols); // } // if (enabledCiphersuites != null) { // e.setEnabledCipherSuites(enabledCiphersuites); // } // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // }
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManagerFactory; import org.java_websocket.server.CustomSSLWebSocketServerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * Example for using the CustomSSLWebSocketServerFactory to allow just specific cipher suites */ public class SSLServerCustomWebsocketFactoryExample { /* * Keystore with certificate created like so (in JKS format): * *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer( 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = "JKS"; String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") .toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance(STORETYPE); File kf = new File(KEYSTORE); ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, KEYPASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); //Lets remove some ciphers and protocols SSLEngine engine = sslContext.createSSLEngine(); List<String> ciphers = new ArrayList<String>(Arrays.asList(engine.getEnabledCipherSuites())); ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); List<String> protocols = new ArrayList<String>(Arrays.asList(engine.getEnabledProtocols())); protocols.remove("SSLv3");
// Path: src/main/java/org/java_websocket/server/CustomSSLWebSocketServerFactory.java // public class CustomSSLWebSocketServerFactory extends DefaultSSLWebSocketServerFactory { // // /** // * The enabled protocols saved as a String array // */ // private final String[] enabledProtocols; // // /** // * The enabled ciphersuites saved as a String array // */ // private final String[] enabledCiphersuites; // // /** // * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher // * suites. // * // * @param sslContext - can not be <code>null</code> // * @param enabledProtocols - only these protocols are enabled, when <code>null</code> default // * settings will be used. // * @param enabledCiphersuites - only these cipher suites are enabled, when <code>null</code> // * default settings will be used. // */ // public CustomSSLWebSocketServerFactory(SSLContext sslContext, String[] enabledProtocols, // String[] enabledCiphersuites) { // this(sslContext, Executors.newSingleThreadScheduledExecutor(), enabledProtocols, // enabledCiphersuites); // } // // /** // * New CustomSSLWebSocketServerFactory configured to only support given protocols and given cipher // * suites. // * // * @param sslContext - can not be <code>null</code> // * @param executerService - can not be <code>null</code> // * @param enabledProtocols - only these protocols are enabled, when <code>null</code> default // * settings will be used. // * @param enabledCiphersuites - only these cipher suites are enabled, when <code>null</code> // * default settings will be used. // */ // public CustomSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService executerService, // String[] enabledProtocols, String[] enabledCiphersuites) { // super(sslContext, executerService); // this.enabledProtocols = enabledProtocols; // this.enabledCiphersuites = enabledCiphersuites; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // if (enabledProtocols != null) { // e.setEnabledProtocols(enabledProtocols); // } // if (enabledCiphersuites != null) { // e.setEnabledCipherSuites(enabledCiphersuites); // } // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // } // Path: src/main/example/SSLServerCustomWebsocketFactoryExample.java import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManagerFactory; import org.java_websocket.server.CustomSSLWebSocketServerFactory; import java.io.File; import java.io.FileInputStream; import java.nio.file.Paths; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * Example for using the CustomSSLWebSocketServerFactory to allow just specific cipher suites */ public class SSLServerCustomWebsocketFactoryExample { /* * Keystore with certificate created like so (in JKS format): * *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer( 8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = "JKS"; String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks") .toString(); String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance(STORETYPE); File kf = new File(KEYSTORE); ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, KEYPASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); //Lets remove some ciphers and protocols SSLEngine engine = sslContext.createSSLEngine(); List<String> ciphers = new ArrayList<String>(Arrays.asList(engine.getEnabledCipherSuites())); ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); List<String> protocols = new ArrayList<String>(Arrays.asList(engine.getEnabledProtocols())); protocols.remove("SSLv3");
CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory(sslContext,
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/framing/BinaryFrame.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.java_websocket.enums.Opcode;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a binary frame */ public class BinaryFrame extends DataFrame { /** * constructor which sets the opcode of this frame to binary */ public BinaryFrame() {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/main/java/org/java_websocket/framing/BinaryFrame.java import org.java_websocket.enums.Opcode; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a binary frame */ public class BinaryFrame extends DataFrame { /** * constructor which sets the opcode of this frame to binary */ public BinaryFrame() {
super(Opcode.BINARY);
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/WebSocketAdapter.java
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // }
import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft,
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // } // Path: src/main/java/org/java_websocket/WebSocketAdapter.java import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft,
ClientHandshake request) throws InvalidDataException {
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/WebSocketAdapter.java
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // }
import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException {
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // } // Path: src/main/java/org/java_websocket/WebSocketAdapter.java import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException {
return new HandshakeImpl1Server();
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/WebSocketAdapter.java
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // }
import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException { return new HandshakeImpl1Server(); } @Override public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, ServerHandshake response) throws InvalidDataException { //To overwrite } /** * This default implementation does not do anything which will cause the connections to always * progress. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, * ClientHandshake) */ @Override public void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) throws InvalidDataException { //To overwrite } /** * This default implementation will send a pong in response to the received ping. The pong frame * will have the same payload as the ping frame. * * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) */ @Override public void onWebsocketPing(WebSocket conn, Framedata f) {
// Path: src/main/java/org/java_websocket/framing/PingFrame.java // public class PingFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to ping // */ // public PingFrame() { // super(Opcode.PING); // } // } // // Path: src/main/java/org/java_websocket/framing/PongFrame.java // public class PongFrame extends ControlFrame { // // /** // * constructor which sets the opcode of this frame to pong // */ // public PongFrame() { // super(Opcode.PONG); // } // // /** // * constructor which sets the opcode of this frame to ping copying over the payload of the ping // * // * @param pingFrame the PingFrame which payload is to copy // */ // public PongFrame(PingFrame pingFrame) { // super(Opcode.PONG); // setPayload(pingFrame.getPayloadData()); // } // } // // Path: src/main/java/org/java_websocket/handshake/ClientHandshake.java // public interface ClientHandshake extends Handshakedata { // // /** // * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2 // * // * @return the HTTP Request-URI // */ // String getResourceDescriptor(); // } // // Path: src/main/java/org/java_websocket/handshake/HandshakeImpl1Server.java // public class HandshakeImpl1Server extends HandshakedataImpl1 implements ServerHandshakeBuilder { // // /** // * Attribute for the http status // */ // private short httpstatus; // // /** // * Attribute for the http status message // */ // private String httpstatusmessage; // // @Override // public String getHttpStatusMessage() { // return httpstatusmessage; // } // // @Override // public short getHttpStatus() { // return httpstatus; // } // // @Override // public void setHttpStatusMessage(String message) { // this.httpstatusmessage = message; // } // // @Override // public void setHttpStatus(short status) { // httpstatus = status; // } // } // Path: src/main/java/org/java_websocket/WebSocketAdapter.java import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.PongFrame; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; /** * This class default implements all methods of the WebSocketListener that can be overridden * optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { private PingFrame pingFrame; /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, * Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft, ClientHandshake request) throws InvalidDataException { return new HandshakeImpl1Server(); } @Override public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, ServerHandshake response) throws InvalidDataException { //To overwrite } /** * This default implementation does not do anything which will cause the connections to always * progress. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, * ClientHandshake) */ @Override public void onWebsocketHandshakeSentAsClient(WebSocket conn, ClientHandshake request) throws InvalidDataException { //To overwrite } /** * This default implementation will send a pong in response to the received ping. The pong frame * will have the same payload as the ping frame. * * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) */ @Override public void onWebsocketPing(WebSocket conn, Framedata f) {
conn.sendFrame(new PongFrame((PingFrame) f));
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/framing/CloseFrame.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // // Path: src/main/java/org/java_websocket/util/ByteBufferUtils.java // public class ByteBufferUtils { // // /** // * Private constructor for static class // */ // private ByteBufferUtils() { // } // // /** // * Transfer from one ByteBuffer to another ByteBuffer // * // * @param source the ByteBuffer to copy from // * @param dest the ByteBuffer to copy to // * @return the number of transferred bytes // */ // public static int transferByteBuffer(ByteBuffer source, ByteBuffer dest) { // if (source == null || dest == null) { // throw new IllegalArgumentException(); // } // int fremain = source.remaining(); // int toremain = dest.remaining(); // if (fremain > toremain) { // int limit = Math.min(fremain, toremain); // source.limit(limit); // dest.put(source); // return limit; // } else { // dest.put(source); // return fremain; // } // } // // /** // * Get a ByteBuffer with zero capacity // * // * @return empty ByteBuffer // */ // public static ByteBuffer getEmptyByteBuffer() { // return ByteBuffer.allocate(0); // } // }
import org.java_websocket.util.Charsetfunctions; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.util.ByteBufferUtils;
*/ private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException { try { payload.position(payload.position() + 2); reason = Charsetfunctions.stringUtf8(payload); } catch (IllegalArgumentException e) { throw new InvalidDataException(CloseFrame.NO_UTF8); } finally { payload.position(mark); } } /** * Update the payload to represent the close code and the reason */ private void updatePayload() { byte[] by = Charsetfunctions.utf8Bytes(reason); ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(code); buf.position(2); ByteBuffer pay = ByteBuffer.allocate(2 + by.length); pay.put(buf); pay.put(by); pay.rewind(); super.setPayload(pay); } @Override public ByteBuffer getPayloadData() { if (code == NOCODE) {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // // Path: src/main/java/org/java_websocket/util/ByteBufferUtils.java // public class ByteBufferUtils { // // /** // * Private constructor for static class // */ // private ByteBufferUtils() { // } // // /** // * Transfer from one ByteBuffer to another ByteBuffer // * // * @param source the ByteBuffer to copy from // * @param dest the ByteBuffer to copy to // * @return the number of transferred bytes // */ // public static int transferByteBuffer(ByteBuffer source, ByteBuffer dest) { // if (source == null || dest == null) { // throw new IllegalArgumentException(); // } // int fremain = source.remaining(); // int toremain = dest.remaining(); // if (fremain > toremain) { // int limit = Math.min(fremain, toremain); // source.limit(limit); // dest.put(source); // return limit; // } else { // dest.put(source); // return fremain; // } // } // // /** // * Get a ByteBuffer with zero capacity // * // * @return empty ByteBuffer // */ // public static ByteBuffer getEmptyByteBuffer() { // return ByteBuffer.allocate(0); // } // } // Path: src/main/java/org/java_websocket/framing/CloseFrame.java import org.java_websocket.util.Charsetfunctions; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.util.ByteBufferUtils; */ private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException { try { payload.position(payload.position() + 2); reason = Charsetfunctions.stringUtf8(payload); } catch (IllegalArgumentException e) { throw new InvalidDataException(CloseFrame.NO_UTF8); } finally { payload.position(mark); } } /** * Update the payload to represent the close code and the reason */ private void updatePayload() { byte[] by = Charsetfunctions.utf8Bytes(reason); ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(code); buf.position(2); ByteBuffer pay = ByteBuffer.allocate(2 + by.length); pay.put(buf); pay.put(by); pay.rewind(); super.setPayload(pay); } @Override public ByteBuffer getPayloadData() { if (code == NOCODE) {
return ByteBufferUtils.getEmptyByteBuffer();
TooTallNate/Java-WebSocket
src/main/example/SSLServerLetsEncryptExample.java
// Path: src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java // public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { // // protected SSLContext sslcontext; // protected ExecutorService exec; // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext) { // this(sslContext, Executors.newSingleThreadScheduledExecutor()); // } // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService exec) { // if (sslContext == null || exec == null) { // throw new IllegalArgumentException(); // } // this.sslcontext = sslContext; // this.exec = exec; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // /* // * See https://github.com/TooTallNate/Java-WebSocket/issues/466 // * // * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. // * E.g. firefox requests this cipher and this causes some dcs/instable connections // */ // List<String> ciphers = new ArrayList<>(Arrays.asList(e.getEnabledCipherSuites())); // ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); // e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { // return new WebSocketImpl(a, d); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> d) { // return new WebSocketImpl(a, d); // } // // @Override // public void close() { // exec.shutdown(); // } // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.xml.bind.DatatypeConverter; import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * SSL Example using the LetsEncrypt certificate See https://github.com/TooTallNate/Java-WebSocket/wiki/Getting-a-SSLContext-from-different-sources#getting-a-sslcontext-using-a-lets-encrypt-certificate */ public class SSLServerLetsEncryptExample { public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer(8887); SSLContext context = getContext(); if (context != null) {
// Path: src/main/java/org/java_websocket/server/DefaultSSLWebSocketServerFactory.java // public class DefaultSSLWebSocketServerFactory implements WebSocketServerFactory { // // protected SSLContext sslcontext; // protected ExecutorService exec; // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext) { // this(sslContext, Executors.newSingleThreadScheduledExecutor()); // } // // public DefaultSSLWebSocketServerFactory(SSLContext sslContext, ExecutorService exec) { // if (sslContext == null || exec == null) { // throw new IllegalArgumentException(); // } // this.sslcontext = sslContext; // this.exec = exec; // } // // @Override // public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { // SSLEngine e = sslcontext.createSSLEngine(); // /* // * See https://github.com/TooTallNate/Java-WebSocket/issues/466 // * // * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly. // * E.g. firefox requests this cipher and this causes some dcs/instable connections // */ // List<String> ciphers = new ArrayList<>(Arrays.asList(e.getEnabledCipherSuites())); // ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); // e.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); // e.setUseClientMode(false); // return new SSLSocketChannel2(channel, e, exec, key); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, Draft d) { // return new WebSocketImpl(a, d); // } // // @Override // public WebSocketImpl createWebSocket(WebSocketAdapter a, List<Draft> d) { // return new WebSocketImpl(a, d); // } // // @Override // public void close() { // exec.shutdown(); // } // } // Path: src/main/example/SSLServerLetsEncryptExample.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.xml.bind.DatatypeConverter; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * SSL Example using the LetsEncrypt certificate See https://github.com/TooTallNate/Java-WebSocket/wiki/Getting-a-SSLContext-from-different-sources#getting-a-sslcontext-using-a-lets-encrypt-certificate */ public class SSLServerLetsEncryptExample { public static void main(String[] args) throws Exception { ChatServer chatserver = new ChatServer(8887); SSLContext context = getContext(); if (context != null) {
chatserver.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(getContext()));
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/framing/PongFrame.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // }
import org.java_websocket.enums.Opcode;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a pong frame */ public class PongFrame extends ControlFrame { /** * constructor which sets the opcode of this frame to pong */ public PongFrame() {
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // Path: src/main/java/org/java_websocket/framing/PongFrame.java import org.java_websocket.enums.Opcode; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.framing; /** * Class to represent a pong frame */ public class PongFrame extends ControlFrame { /** * constructor which sets the opcode of this frame to pong */ public PongFrame() {
super(Opcode.PONG);
TooTallNate/Java-WebSocket
src/main/java/org/java_websocket/WebSocket.java
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // // Path: src/main/java/org/java_websocket/enums/ReadyState.java // public enum ReadyState { // NOT_YET_CONNECTED, OPEN, CLOSING, CLOSED // } // // Path: src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java // public class WebsocketNotConnectedException extends RuntimeException { // // /** // * Serializable // */ // private static final long serialVersionUID = -785314021592982715L; // }
import org.java_websocket.enums.Opcode; import org.java_websocket.enums.ReadyState; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.Framedata; import org.java_websocket.protocols.IProtocol; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Collection; import javax.net.ssl.SSLSession; import org.java_websocket.drafts.Draft;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; public interface WebSocket { /** * sends the closing handshake. may be send in response to an other handshake. * * @param code the closing code * @param message the closing message */ void close(int code, String message); /** * sends the closing handshake. may be send in response to an other handshake. * * @param code the closing code */ void close(int code); /** * Convenience function which behaves like close(CloseFrame.NORMAL) */ void close(); /** * This will close the connection immediately without a proper close handshake. The code and the * message therefore won't be transferred over the wire also they will be forwarded to * onClose/onWebsocketClose. * * @param code the closing code * @param message the closing message **/ void closeConnection(int code, String message); /** * Send Text data to the other end. * * @param text the text data to send * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(String text); /** * Send Binary data (plain bytes) to the other end. * * @param bytes the binary data to send * @throws IllegalArgumentException the data is null * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(ByteBuffer bytes); /** * Send Binary data (plain bytes) to the other end. * * @param bytes the byte array to send * @throws IllegalArgumentException the data is null * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(byte[] bytes); /** * Send a frame to the other end * * @param framedata the frame to send to the other end */ void sendFrame(Framedata framedata); /** * Send a collection of frames to the other end * * @param frames the frames to send to the other end */ void sendFrame(Collection<Framedata> frames); /** * Send a ping to the other end * * @throws WebsocketNotConnectedException websocket is not yet connected */ void sendPing(); /** * Allows to send continuous/fragmented frames conveniently. <br> For more into on this frame type * see http://tools.ietf.org/html/rfc6455#section-5.4<br> * <p> * If the first frame you send is also the last then it is not a fragmented frame and will * received via onMessage instead of onFragmented even though it was send by this method. * * @param op This is only important for the first frame in the sequence. Opcode.TEXT, * Opcode.BINARY are allowed. * @param buffer The buffer which contains the payload. It may have no bytes remaining. * @param fin true means the current frame is the last in the sequence. **/
// Path: src/main/java/org/java_websocket/enums/Opcode.java // public enum Opcode { // CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING // // more to come // } // // Path: src/main/java/org/java_websocket/enums/ReadyState.java // public enum ReadyState { // NOT_YET_CONNECTED, OPEN, CLOSING, CLOSED // } // // Path: src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java // public class WebsocketNotConnectedException extends RuntimeException { // // /** // * Serializable // */ // private static final long serialVersionUID = -785314021592982715L; // } // Path: src/main/java/org/java_websocket/WebSocket.java import org.java_websocket.enums.Opcode; import org.java_websocket.enums.ReadyState; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.Framedata; import org.java_websocket.protocols.IProtocol; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Collection; import javax.net.ssl.SSLSession; import org.java_websocket.drafts.Draft; /* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket; public interface WebSocket { /** * sends the closing handshake. may be send in response to an other handshake. * * @param code the closing code * @param message the closing message */ void close(int code, String message); /** * sends the closing handshake. may be send in response to an other handshake. * * @param code the closing code */ void close(int code); /** * Convenience function which behaves like close(CloseFrame.NORMAL) */ void close(); /** * This will close the connection immediately without a proper close handshake. The code and the * message therefore won't be transferred over the wire also they will be forwarded to * onClose/onWebsocketClose. * * @param code the closing code * @param message the closing message **/ void closeConnection(int code, String message); /** * Send Text data to the other end. * * @param text the text data to send * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(String text); /** * Send Binary data (plain bytes) to the other end. * * @param bytes the binary data to send * @throws IllegalArgumentException the data is null * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(ByteBuffer bytes); /** * Send Binary data (plain bytes) to the other end. * * @param bytes the byte array to send * @throws IllegalArgumentException the data is null * @throws WebsocketNotConnectedException websocket is not yet connected */ void send(byte[] bytes); /** * Send a frame to the other end * * @param framedata the frame to send to the other end */ void sendFrame(Framedata framedata); /** * Send a collection of frames to the other end * * @param frames the frames to send to the other end */ void sendFrame(Collection<Framedata> frames); /** * Send a ping to the other end * * @throws WebsocketNotConnectedException websocket is not yet connected */ void sendPing(); /** * Allows to send continuous/fragmented frames conveniently. <br> For more into on this frame type * see http://tools.ietf.org/html/rfc6455#section-5.4<br> * <p> * If the first frame you send is also the last then it is not a fragmented frame and will * received via onMessage instead of onFragmented even though it was send by this method. * * @param op This is only important for the first frame in the sequence. Opcode.TEXT, * Opcode.BINARY are allowed. * @param buffer The buffer which contains the payload. It may have no bytes remaining. * @param fin true means the current frame is the last in the sequence. **/
void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin);
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/connection/DeepConnectionTest.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import com.stratio.connector.commons.connection.ConnectionHandler; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.security.ICredentials;
/** * */ package com.stratio.connector.deep.connection; /** * Unit tests related to the {@link DeepConnection} class. */ @RunWith(PowerMockRunner.class) public class DeepConnectionTest { private final static String MOCK_CONSTANT = "MOCK"; private final static String CASSANDRA_CONSTANT = "cassandra"; private final static String UNKNOWN_CONSTANT = "unknown"; @Mock private ConnectorClusterConfig config; @Mock private ICredentials credentials; @Mock private Map<String, String> clusterOptions; @Mock private ConnectionHandler connectionHandler; @Test public void createNewDeepConnectionWithDataSourceNameTest() throws ConnectionException, InitializationException { // Set up DataStoreName dataStoreName = new DataStoreName(CASSANDRA_CONSTANT); // Stubbing when(config.getClusterOptions()).thenReturn(clusterOptions); when(clusterOptions.get(any(String.class))).thenReturn(MOCK_CONSTANT);
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/connection/DeepConnectionTest.java import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import com.stratio.connector.commons.connection.ConnectionHandler; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.security.ICredentials; /** * */ package com.stratio.connector.deep.connection; /** * Unit tests related to the {@link DeepConnection} class. */ @RunWith(PowerMockRunner.class) public class DeepConnectionTest { private final static String MOCK_CONSTANT = "MOCK"; private final static String CASSANDRA_CONSTANT = "cassandra"; private final static String UNKNOWN_CONSTANT = "unknown"; @Mock private ConnectorClusterConfig config; @Mock private ICredentials credentials; @Mock private Map<String, String> clusterOptions; @Mock private ConnectionHandler connectionHandler; @Test public void createNewDeepConnectionWithDataSourceNameTest() throws ConnectionException, InitializationException { // Set up DataStoreName dataStoreName = new DataStoreName(CASSANDRA_CONSTANT); // Stubbing when(config.getClusterOptions()).thenReturn(clusterOptions); when(clusterOptions.get(any(String.class))).thenReturn(MOCK_CONSTANT);
when(clusterOptions.get(DeepConnectorConstants.EXTRACTOR_IMPL_CLASS)).thenReturn("com.stratio.deep.cassandra.extractor.CassandraCellExtractor");
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/MongoConnectionConfigurationBuilder.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants;
package com.stratio.connector.deep; public class MongoConnectionConfigurationBuilder { public static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("mongodb"); private static final String MONGO_CELL_CLASS = "com.stratio.deep.mongodb.extractor.MongoCellExtractor"; public static final String HOST = "10.200.0.58"; public static final String PORT = "27100"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.INNERCLASS, MONGO_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/MongoConnectionConfigurationBuilder.java import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; package com.stratio.connector.deep; public class MongoConnectionConfigurationBuilder { public static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("mongodb"); private static final String MONGO_CELL_CLASS = "com.stratio.deep.mongodb.extractor.MongoCellExtractor"; public static final String HOST = "10.200.0.58"; public static final String PORT = "27100"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.INNERCLASS, MONGO_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
connectorOptions.put(DeepConnectorConstants.PROPERTY_DEFAULT_LIMIT,
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/connection/DeepConnection.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import com.stratio.deep.commons.entity.Cells; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.stratio.connector.commons.connection.Connection; import com.stratio.connector.commons.util.ConnectorParser; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.security.ICredentials; import com.stratio.deep.commons.config.ExtractorConfig;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.connection; /** * .Connection object exist in the ConnectionHandler and contains all the connection info & config. * {@link com.stratio.connector.commons.connection.Connection} * */ public class DeepConnection extends Connection<Object> { private boolean isConnect = false; private final ExtractorConfig<Cells> extractorConfig; /** * Constructor using credentials and cluster config. * * @param credentials * the credentials. * @param config * The cluster configuration. */ public DeepConnection(ICredentials credentials, ConnectorClusterConfig config) throws ConnectionException { if (credentials != null) { // TODO check the credentials } Map<String, String> clusterOptions = config.getClusterOptions(); Map<String, String> connectorOptions = config.getConnectorOptions(); // Creating a configuration for the Extractor and initialize it ExtractorConfig<Cells> extractorconfig = new ExtractorConfig<>(Cells.class);
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/main/java/com/stratio/connector/deep/connection/DeepConnection.java import com.stratio.deep.commons.entity.Cells; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.stratio.connector.commons.connection.Connection; import com.stratio.connector.commons.util.ConnectorParser; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.security.ICredentials; import com.stratio.deep.commons.config.ExtractorConfig; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.connection; /** * .Connection object exist in the ConnectionHandler and contains all the connection info & config. * {@link com.stratio.connector.commons.connection.Connection} * */ public class DeepConnection extends Connection<Object> { private boolean isConnect = false; private final ExtractorConfig<Cells> extractorConfig; /** * Constructor using credentials and cluster config. * * @param credentials * the credentials. * @param config * The cluster configuration. */ public DeepConnection(ICredentials credentials, ConnectorClusterConfig config) throws ConnectionException { if (credentials != null) { // TODO check the credentials } Map<String, String> clusterOptions = config.getClusterOptions(); Map<String, String> connectorOptions = config.getConnectorOptions(); // Creating a configuration for the Extractor and initialize it ExtractorConfig<Cells> extractorconfig = new ExtractorConfig<>(Cells.class);
String extractorImplClassName = clusterOptions.get(DeepConnectorConstants.EXTRACTOR_IMPL_CLASS);
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/functions/NotEquals.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // }
import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines Class that defines, Spark function that determines if the value in the given field is different to the provided term. */ public class NotEquals implements Function<Cells, Boolean> { private static final long serialVersionUID = 927384912608139416L; /** * Term to be compared. */
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // } // Path: src/main/java/com/stratio/connector/deep/engine/query/functions/NotEquals.java import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines Class that defines, Spark function that determines if the value in the given field is different to the provided term. */ public class NotEquals implements Function<Cells, Boolean> { private static final long serialVersionUID = 927384912608139416L; /** * Term to be compared. */
private final Term<?> term;
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/PrepareFunctionalTest.java
// Path: src/test/java/com/stratio/connector/deep/ESConnectionConfigurationBuilder.java // public static final Integer ES_NATIVE_PORT = 9300;
import static com.stratio.connector.deep.ESConnectionConfigurationBuilder.ES_NATIVE_PORT; import static com.stratio.deep.commons.utils.Utils.quote; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.UnknownHostException; import org.apache.log4j.Logger; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.node.Node; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.google.common.io.Resources; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient;
package com.stratio.connector.deep; public class PrepareFunctionalTest implements CommonsPrepareTestData { private static final Logger logger = Logger.getLogger(PrepareFunctionalTest.class); public static Cluster cluster; public static Session session; /** * The Mongo client. */ public static MongoClient mongoClient; /** * The Elasticsearch client. */ public static Client elasticClient; /** * The elasticsearch node connection. */ public static Node node; public static void prepareDataForES() { elasticClient = new TransportClient(ImmutableSettings.settingsBuilder() .put("cluster.name", ESConnectionConfigurationBuilder.ES_CLUSTERNAME).build()) .addTransportAddress(new InetSocketTransportAddress(ESConnectionConfigurationBuilder.HOST,
// Path: src/test/java/com/stratio/connector/deep/ESConnectionConfigurationBuilder.java // public static final Integer ES_NATIVE_PORT = 9300; // Path: src/test/java/com/stratio/connector/deep/PrepareFunctionalTest.java import static com.stratio.connector.deep.ESConnectionConfigurationBuilder.ES_NATIVE_PORT; import static com.stratio.deep.commons.utils.Utils.quote; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.UnknownHostException; import org.apache.log4j.Logger; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.node.Node; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.google.common.io.Resources; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient; package com.stratio.connector.deep; public class PrepareFunctionalTest implements CommonsPrepareTestData { private static final Logger logger = Logger.getLogger(PrepareFunctionalTest.class); public static Cluster cluster; public static Session session; /** * The Mongo client. */ public static MongoClient mongoClient; /** * The Elasticsearch client. */ public static Client elasticClient; /** * The elasticsearch node connection. */ public static Node node; public static void prepareDataForES() { elasticClient = new TransportClient(ImmutableSettings.settingsBuilder() .put("cluster.name", ESConnectionConfigurationBuilder.ES_CLUSTERNAME).build()) .addTransportAddress(new InetSocketTransportAddress(ESConnectionConfigurationBuilder.HOST,
ES_NATIVE_PORT.intValue()));
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java
// Path: src/main/java/com/stratio/connector/deep/connection/DeepConnectionHandler.java // public class DeepConnectionHandler extends ConnectionHandler { // // /** // * Basic constructor. // * // * @param configuration // * The configuration // */ // public DeepConnectionHandler(IConfiguration configuration) { // super(configuration); // } // // /** // * Use config & Credentials to create Deep native connection. // * // * @param iCredentials // * The credentials // * @param connectorClusterConfig // * The connector cluster configuration // * // * @return DeepConnection // **/ // @Override // protected Connection createNativeConnection(ICredentials iCredentials, ConnectorClusterConfig connectorClusterConfig) // throws ConnectionException { // // Connection connection; // // connection = new DeepConnection(iCredentials, connectorClusterConfig); // // // return connection; // } // // }
import com.stratio.connector.commons.engine.CommonsQueryEngine; import com.stratio.connector.deep.connection.DeepConnectionHandler; import com.stratio.crossdata.common.connector.IResultHandler; import com.stratio.crossdata.common.exceptions.ConnectorException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.logicalplan.LogicalWorkflow; import com.stratio.crossdata.common.result.QueryResult; import com.stratio.deep.core.context.DeepSparkContext;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query; /** * * Subclass that extends CommonsQueryEngine. * */ public class DeepQueryEngine extends CommonsQueryEngine { private final DeepSparkContext deepContext;
// Path: src/main/java/com/stratio/connector/deep/connection/DeepConnectionHandler.java // public class DeepConnectionHandler extends ConnectionHandler { // // /** // * Basic constructor. // * // * @param configuration // * The configuration // */ // public DeepConnectionHandler(IConfiguration configuration) { // super(configuration); // } // // /** // * Use config & Credentials to create Deep native connection. // * // * @param iCredentials // * The credentials // * @param connectorClusterConfig // * The connector cluster configuration // * // * @return DeepConnection // **/ // @Override // protected Connection createNativeConnection(ICredentials iCredentials, ConnectorClusterConfig connectorClusterConfig) // throws ConnectionException { // // Connection connection; // // connection = new DeepConnection(iCredentials, connectorClusterConfig); // // // return connection; // } // // } // Path: src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java import com.stratio.connector.commons.engine.CommonsQueryEngine; import com.stratio.connector.deep.connection.DeepConnectionHandler; import com.stratio.crossdata.common.connector.IResultHandler; import com.stratio.crossdata.common.exceptions.ConnectorException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.logicalplan.LogicalWorkflow; import com.stratio.crossdata.common.result.QueryResult; import com.stratio.deep.core.context.DeepSparkContext; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query; /** * * Subclass that extends CommonsQueryEngine. * */ public class DeepQueryEngine extends CommonsQueryEngine { private final DeepSparkContext deepContext;
private final DeepConnectionHandler deepConnectionHandler;
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/functions/GreaterEqualThan.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // }
import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines GreaterEqualThan, Spark function that determines if the value in the given field is greater or equal than the provided term. */ public class GreaterEqualThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2927596112428729111L; /** * Value to be compared. */
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // } // Path: src/main/java/com/stratio/connector/deep/engine/query/functions/GreaterEqualThan.java import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines GreaterEqualThan, Spark function that determines if the value in the given field is greater or equal than the provided term. */ public class GreaterEqualThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2927596112428729111L; /** * Value to be compared. */
private final Term<?> term;
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/DeepConnectorAerospikeFT.java
// Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static ColumnName createColumn(String catalogName, String tableName, String columnName) { // // return new ColumnName(catalogName, tableName, columnName); // } // // Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static Project createProject(String clusterName, String catalogName, String tableName, // List<String> columnList) { // // List<ColumnName> columns = new ArrayList<>(); // for (String column : columnList) { // columns.add(new ColumnName(catalogName, tableName, column)); // } // // TableName table = new TableName(catalogName, tableName); // HashSet<Operations> operations = new HashSet<>(); // operations.add(Operations.PROJECT); // // return new Project(operations, table, new ClusterName(clusterName), columns); // } // // Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static Select createSelect(List<ColumnName> columnsList, List<String> aliasNamesList) { // // Map<Selector, String> columnsAliases = new LinkedHashMap<>(); // Map<String, ColumnType> columnsTypes = new LinkedHashMap<>(); // Map<Selector, ColumnType> typeMapFromColumnName = new LinkedHashMap<>(); // // Iterator<String> aliasesIt = aliasNamesList.iterator(); // for (ColumnName column : columnsList) { // ColumnSelector columnSelector = new ColumnSelector(column); // columnsAliases.put(columnSelector, aliasesIt.next()); // // columnsTypes.put(column.getQualifiedName(), new ColumnType(DataType.TEXT)); // typeMapFromColumnName.put(columnSelector, new ColumnType(DataType.TEXT)); // } // // Set<Operations> operations = new HashSet<>(); // operations.add(Operations.PROJECT); // // return new Select(operations, columnsAliases, columnsTypes, typeMapFromColumnName); // } // // Path: src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java // public class DeepQueryEngine extends CommonsQueryEngine { // // private final DeepSparkContext deepContext; // // private final DeepConnectionHandler deepConnectionHandler; // // /** // * Basic constructor. // * // * @param deepContext // * The Deep Context // * @param deepConnectionHandler // * The connection handler // */ // public DeepQueryEngine(DeepSparkContext deepContext, DeepConnectionHandler deepConnectionHandler) { // super(deepConnectionHandler); // this.deepContext = deepContext; // this.deepConnectionHandler = deepConnectionHandler; // } // // /* // * (non-Javadoc) // * // * @see // * com.stratio.crossdata.common.connector.IQueryEngine#execute(com.stratio.crossdata.common.logicalplan.LogicalWorkflow // * ) // */ // @Override // public QueryResult executeWorkFlow(LogicalWorkflow workflow) throws UnsupportedException, ExecutionException { // QueryExecutor executor = new QueryExecutor(deepContext, deepConnectionHandler); // QueryResult queryResult = executor.executeWorkFlow(workflow); // // return queryResult; // // } // // @Override protected void asyncExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler) throws UnsupportedException { // throw new UnsupportedException("method asyncExecuteWorkFlow not supported"); // // } // // /** // * Execute a paged query, // * @param queryId the queryID, // * @param workflow the workflow. // * @param resultHandler the resultHandler. // * @param pageSize the pageSize. // * @throws ConnectorException if any error happens. // */ // @Override protected void pagedExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler, int pageSize) throws ConnectorException{ // throw new UnsupportedException("method pagedExecuteWorkFlow not supported"); // } // // // /* // * (non-Javadoc) // * // * @see com.stratio.crossdata.common.connector.IQueryEngine#stop(java.lang.String) // */ // @Override // public void stop(String queryId) throws UnsupportedException, ExecutionException { // throw new UnsupportedException("method stop not supported"); // // // } // // // // }
import static com.stratio.connector.deep.LogicalWorkflowBuilder.createColumn; import static com.stratio.connector.deep.LogicalWorkflowBuilder.createProject; import static com.stratio.connector.deep.LogicalWorkflowBuilder.createSelect; import static junit.framework.TestCase.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.aerospike.client.AerospikeClient; import com.aerospike.client.AerospikeException; import com.aerospike.client.Bin; import com.aerospike.client.Host; import com.aerospike.client.Key; import com.aerospike.client.Record; import com.aerospike.client.ScanCallback; import com.aerospike.client.policy.ScanPolicy; import com.stratio.connector.deep.engine.query.DeepQueryEngine; import com.stratio.crossdata.common.data.Row; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.logicalplan.LogicalStep; import com.stratio.crossdata.common.logicalplan.LogicalWorkflow; import com.stratio.crossdata.common.logicalplan.Project; import com.stratio.crossdata.common.result.QueryResult;
package com.stratio.connector.deep; /** * Functional tests using MongoDB */ public class DeepConnectorAerospikeFT { private static final Logger logger = Logger.getLogger(DeepConnectorAerospikeFT.class); private static final String KEYSPACE = "test"; private static final String MYTABLE1_CONSTANT = "input"; private static final String AEROSPIKE_CLUSTERNAME_CONSTANT = "aerospike";
// Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static ColumnName createColumn(String catalogName, String tableName, String columnName) { // // return new ColumnName(catalogName, tableName, columnName); // } // // Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static Project createProject(String clusterName, String catalogName, String tableName, // List<String> columnList) { // // List<ColumnName> columns = new ArrayList<>(); // for (String column : columnList) { // columns.add(new ColumnName(catalogName, tableName, column)); // } // // TableName table = new TableName(catalogName, tableName); // HashSet<Operations> operations = new HashSet<>(); // operations.add(Operations.PROJECT); // // return new Project(operations, table, new ClusterName(clusterName), columns); // } // // Path: src/test/java/com/stratio/connector/deep/LogicalWorkflowBuilder.java // public static Select createSelect(List<ColumnName> columnsList, List<String> aliasNamesList) { // // Map<Selector, String> columnsAliases = new LinkedHashMap<>(); // Map<String, ColumnType> columnsTypes = new LinkedHashMap<>(); // Map<Selector, ColumnType> typeMapFromColumnName = new LinkedHashMap<>(); // // Iterator<String> aliasesIt = aliasNamesList.iterator(); // for (ColumnName column : columnsList) { // ColumnSelector columnSelector = new ColumnSelector(column); // columnsAliases.put(columnSelector, aliasesIt.next()); // // columnsTypes.put(column.getQualifiedName(), new ColumnType(DataType.TEXT)); // typeMapFromColumnName.put(columnSelector, new ColumnType(DataType.TEXT)); // } // // Set<Operations> operations = new HashSet<>(); // operations.add(Operations.PROJECT); // // return new Select(operations, columnsAliases, columnsTypes, typeMapFromColumnName); // } // // Path: src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java // public class DeepQueryEngine extends CommonsQueryEngine { // // private final DeepSparkContext deepContext; // // private final DeepConnectionHandler deepConnectionHandler; // // /** // * Basic constructor. // * // * @param deepContext // * The Deep Context // * @param deepConnectionHandler // * The connection handler // */ // public DeepQueryEngine(DeepSparkContext deepContext, DeepConnectionHandler deepConnectionHandler) { // super(deepConnectionHandler); // this.deepContext = deepContext; // this.deepConnectionHandler = deepConnectionHandler; // } // // /* // * (non-Javadoc) // * // * @see // * com.stratio.crossdata.common.connector.IQueryEngine#execute(com.stratio.crossdata.common.logicalplan.LogicalWorkflow // * ) // */ // @Override // public QueryResult executeWorkFlow(LogicalWorkflow workflow) throws UnsupportedException, ExecutionException { // QueryExecutor executor = new QueryExecutor(deepContext, deepConnectionHandler); // QueryResult queryResult = executor.executeWorkFlow(workflow); // // return queryResult; // // } // // @Override protected void asyncExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler) throws UnsupportedException { // throw new UnsupportedException("method asyncExecuteWorkFlow not supported"); // // } // // /** // * Execute a paged query, // * @param queryId the queryID, // * @param workflow the workflow. // * @param resultHandler the resultHandler. // * @param pageSize the pageSize. // * @throws ConnectorException if any error happens. // */ // @Override protected void pagedExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler, int pageSize) throws ConnectorException{ // throw new UnsupportedException("method pagedExecuteWorkFlow not supported"); // } // // // /* // * (non-Javadoc) // * // * @see com.stratio.crossdata.common.connector.IQueryEngine#stop(java.lang.String) // */ // @Override // public void stop(String queryId) throws UnsupportedException, ExecutionException { // throw new UnsupportedException("method stop not supported"); // // // } // // // // } // Path: src/test/java/com/stratio/connector/deep/DeepConnectorAerospikeFT.java import static com.stratio.connector.deep.LogicalWorkflowBuilder.createColumn; import static com.stratio.connector.deep.LogicalWorkflowBuilder.createProject; import static com.stratio.connector.deep.LogicalWorkflowBuilder.createSelect; import static junit.framework.TestCase.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.aerospike.client.AerospikeClient; import com.aerospike.client.AerospikeException; import com.aerospike.client.Bin; import com.aerospike.client.Host; import com.aerospike.client.Key; import com.aerospike.client.Record; import com.aerospike.client.ScanCallback; import com.aerospike.client.policy.ScanPolicy; import com.stratio.connector.deep.engine.query.DeepQueryEngine; import com.stratio.crossdata.common.data.Row; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.logicalplan.LogicalStep; import com.stratio.crossdata.common.logicalplan.LogicalWorkflow; import com.stratio.crossdata.common.logicalplan.Project; import com.stratio.crossdata.common.result.QueryResult; package com.stratio.connector.deep; /** * Functional tests using MongoDB */ public class DeepConnectorAerospikeFT { private static final Logger logger = Logger.getLogger(DeepConnectorAerospikeFT.class); private static final String KEYSPACE = "test"; private static final String MYTABLE1_CONSTANT = "input"; private static final String AEROSPIKE_CLUSTERNAME_CONSTANT = "aerospike";
private static DeepQueryEngine deepQueryEngine;
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/connection/ConnectionHandlerTest.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.whenNew; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.internal.util.reflection.Whitebox; import org.powermock.modules.junit4.PowerMockRunner; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.connector.IConfiguration; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.crossdata.common.security.ICredentials; import com.stratio.deep.commons.extractor.utils.ExtractorConstants;
package com.stratio.connector.deep.connection; /** * Created by dgomez on 18/09/14. */ @RunWith(PowerMockRunner.class) public class ConnectionHandlerTest { private static final String CLUSTER_NAME = "cluster_name"; private DeepConnectionHandler connectionHandler = null; @Mock private IConfiguration iConfiguration; @Before public void before() throws Exception { iConfiguration = mock(IConfiguration.class); connectionHandler = new DeepConnectionHandler(iConfiguration); } /** * Method: createConnection(String clusterName, Connection connection) */ @Test public void testCreateConnection() throws Exception { ICredentials credentials = mock(ICredentials.class); Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, "127.0.0.1"); options.put(ExtractorConstants.HOSTS, "127.0.0.1 , 127.0.0.2"); options.put(ExtractorConstants.PORT, "PORT");
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/connection/ConnectionHandlerTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.whenNew; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.internal.util.reflection.Whitebox; import org.powermock.modules.junit4.PowerMockRunner; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.connector.IConfiguration; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.crossdata.common.security.ICredentials; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; package com.stratio.connector.deep.connection; /** * Created by dgomez on 18/09/14. */ @RunWith(PowerMockRunner.class) public class ConnectionHandlerTest { private static final String CLUSTER_NAME = "cluster_name"; private DeepConnectionHandler connectionHandler = null; @Mock private IConfiguration iConfiguration; @Before public void before() throws Exception { iConfiguration = mock(IConfiguration.class); connectionHandler = new DeepConnectionHandler(iConfiguration); } /** * Method: createConnection(String clusterName, Connection connection) */ @Test public void testCreateConnection() throws Exception { ICredentials credentials = mock(ICredentials.class); Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, "127.0.0.1"); options.put(ExtractorConstants.HOSTS, "127.0.0.1 , 127.0.0.2"); options.put(ExtractorConstants.PORT, "PORT");
options.put(DeepConnectorConstants.EXTRACTOR_IMPL_CLASS, "PORT");
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/functions/GreaterThan.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // }
import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines GreaterThan, Spark function that determines if the value in the given field is greater than the provided term. */ public class GreaterThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2675616112608139116L; /** * Term to be compared. */
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // } // Path: src/main/java/com/stratio/connector/deep/engine/query/functions/GreaterThan.java import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines GreaterThan, Spark function that determines if the value in the given field is greater than the provided term. */ public class GreaterThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2675616112608139116L; /** * Term to be compared. */
private final Term<?> term;
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/ESConnectionConfigurationBuilder.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants;
package com.stratio.connector.deep; public class ESConnectionConfigurationBuilder { private static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("elasticsearch"); private static final String ES_CELL_CLASS = "com.stratio.deep.es.extractor.ESCellExtractor"; public static final String HOST = "10.200.0.58"; public static final String PORT = "9200"; public static final Integer ES_NATIVE_PORT = 9300; public static final String ES_CLUSTERNAME = "statioESCluster"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.INNERCLASS, ES_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/ESConnectionConfigurationBuilder.java import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; package com.stratio.connector.deep; public class ESConnectionConfigurationBuilder { private static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("elasticsearch"); private static final String ES_CELL_CLASS = "com.stratio.deep.es.extractor.ESCellExtractor"; public static final String HOST = "10.200.0.58"; public static final String PORT = "9200"; public static final Integer ES_NATIVE_PORT = 9300; public static final String ES_CLUSTERNAME = "statioESCluster"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.PORT, PORT); options.put(ExtractorConstants.INNERCLASS, ES_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
connectorOptions.put(DeepConnectorConstants.PROPERTY_DEFAULT_LIMIT,
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/CassandraConnectionConfigurationBuilder.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants;
package com.stratio.connector.deep; public class CassandraConnectionConfigurationBuilder { private static final String CASSANDRA_CELL_CLASS = "com.stratio.deep.cassandra.extractor.CassandraCellExtractor"; public static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("cassandra"); public static final String CQLPORT = "9042"; public static final String RPCPORT = "9160"; public static final String HOST = "10.200.0.58"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, CQLPORT); options.put(ExtractorConstants.RPCPORT, RPCPORT); options.put(ExtractorConstants.INNERCLASS, CASSANDRA_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/CassandraConnectionConfigurationBuilder.java import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; package com.stratio.connector.deep; public class CassandraConnectionConfigurationBuilder { private static final String CASSANDRA_CELL_CLASS = "com.stratio.deep.cassandra.extractor.CassandraCellExtractor"; public static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("cassandra"); public static final String CQLPORT = "9042"; public static final String RPCPORT = "9160"; public static final String HOST = "10.200.0.58"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.PORT, CQLPORT); options.put(ExtractorConstants.RPCPORT, RPCPORT); options.put(ExtractorConstants.INNERCLASS, CASSANDRA_CELL_CLASS); Map<String, String> connectorOptions = new HashMap<>();
connectorOptions.put(DeepConnectorConstants.PROPERTY_DEFAULT_LIMIT,
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/HDFSConnectionConfigurationBuilder.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants;
package com.stratio.connector.deep; public class HDFSConnectionConfigurationBuilder { private static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("hdfs"); public static final String HOST = "10.200.0.60"; public static final String PORT = "9000"; private static final String HDFS = "hdfs"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.HOSTS, HOST); options.put(ExtractorConstants.PORTS, PORT); options.put(ExtractorConstants.INNERCLASS, HDFS); options.put(ExtractorConstants.FS_FILE_SEPARATOR, ","); options.put(ExtractorConstants.FS_FILE_PATH, "/"); // options.put(ExtractorConstants.FS_SCHEMA,"[id:java.lang.String,author:java.lang.String," + // "title:java.lang.String,year:java.lang.Integer,length:java.lang.Integer,single:java.lang.String]"); options.put(ExtractorConstants.TYPE, ExtractorConstants.HDFS_TYPE); options.put(ExtractorConstants.TABLE, "songs"); options.put(ExtractorConstants.CATALOG, "test"); options.put(ExtractorConstants.HDFS_FILE_EXTENSION, ".csv"); Map<String, String> connectorOptions = new HashMap<>();
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/test/java/com/stratio/connector/deep/HDFSConnectionConfigurationBuilder.java import java.util.HashMap; import java.util.Map; import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.data.DataStoreName; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; package com.stratio.connector.deep; public class HDFSConnectionConfigurationBuilder { private static final ClusterName CLUSTERNAME_CONSTANT = new ClusterName("hdfs"); public static final String HOST = "10.200.0.60"; public static final String PORT = "9000"; private static final String HDFS = "hdfs"; /** * Create the configuration object to config the connector cluster information * * @return Cluster configuration object */ public static ConnectorClusterConfig prepareConfiguration() { Map<String, String> options = new HashMap<>(); options.put(ExtractorConstants.HOST, HOST); options.put(ExtractorConstants.HOSTS, HOST); options.put(ExtractorConstants.PORTS, PORT); options.put(ExtractorConstants.INNERCLASS, HDFS); options.put(ExtractorConstants.FS_FILE_SEPARATOR, ","); options.put(ExtractorConstants.FS_FILE_PATH, "/"); // options.put(ExtractorConstants.FS_SCHEMA,"[id:java.lang.String,author:java.lang.String," + // "title:java.lang.String,year:java.lang.Integer,length:java.lang.Integer,single:java.lang.String]"); options.put(ExtractorConstants.TYPE, ExtractorConstants.HDFS_TYPE); options.put(ExtractorConstants.TABLE, "songs"); options.put(ExtractorConstants.CATALOG, "test"); options.put(ExtractorConstants.HDFS_FILE_EXTENSION, ".csv"); Map<String, String> connectorOptions = new HashMap<>();
connectorOptions.put(DeepConnectorConstants.PROPERTY_DEFAULT_LIMIT,
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/functions/LessEqualThan.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // }
import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines LessEqualThan, Spark function that determines if the value in the given field is less or equal than the provided term. */ public class LessEqualThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2775666112428131116L; /** * Term to be compared. */
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // } // Path: src/main/java/com/stratio/connector/deep/engine/query/functions/LessEqualThan.java import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines LessEqualThan, Spark function that determines if the value in the given field is less or equal than the provided term. */ public class LessEqualThan implements Function<Cells, Boolean> { private static final long serialVersionUID = 2775666112428131116L; /** * Term to be compared. */
private final Term<?> term;
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/engine/query/functions/DeepEquals.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // }
import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName;
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines DeepEquals, Spark function that determines if the value in the given field is equals to the provided term. * */ public class DeepEquals implements Function<Cells, Boolean> { private static final long serialVersionUID = -6143471452730703044L; /** * Term to be compared. */
// Path: src/main/java/com/stratio/connector/deep/engine/query/structures/Term.java // public abstract class Term<T extends Comparable<T>> extends ValueCell<T> implements Comparable<T>, // Serializable { // // /** // * Class logger. // */ // private static final Logger LOG = Logger.getLogger(Term.class); // // private static final long serialVersionUID = -4258938152892510227L; // protected Class<? extends Comparable<?>> clazz; // protected T value; // // /** // * Basic constructor. // * @param clazz // * Class of the type that extends Comparable // * @param value // * Value of the Term // */ // public Term(Class<? extends Comparable<?>> clazz, T value) { // this.clazz = clazz; // this.value = value; // } // // /** // * Get the Term Java Class. // * // * @return A {@link java.lang.Class}. // */ // public Class<? extends Comparable<?>> getTermClass() { // return clazz; // } // // /** // * Get the term value. // * // * @return A {@link java.lang.Object} with the value. // */ // public T getTermValue() { // return value; // } // // @Override // public String getStringValue() { // return value.toString(); // } // // @Override // public String toString() { // return value.toString(); // } // // /* // * (non-Javadoc) // * // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(T o) { // // if (!(this.clazz.isInstance(o))) { // // try { // if ((this.clazz).equals(Long.class) && o.getClass().equals(Integer.class)) { // Long obj = Long.valueOf(o.toString()); // return Long.valueOf(this.getStringValue()).compareTo(obj); // } else if ((this.clazz).equals(Double.class) && o.getClass().equals(Float.class)) { // Double obj = Double.valueOf(o.toString()); // return Double.valueOf(this.getStringValue()).compareTo(obj); // } // } catch (NumberFormatException | ClassCastException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + o.getClass(), e); // } // return this.value.compareTo(o); // } // return this.value.compareTo(o); // } // // /** // * Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those // * provided by {@link java.util.HashMap}. // * // * @return a hash code value for this object. // * @see Object#equals(Object) // * @see System#identityHashCode // */ // @Override // public int hashCode() { // return clazz.hashCode() * this.getTermValue().hashCode(); // } // // /** // * Indicates whether some other object is "equal to" this one. // * <p/> // * The {@code equals} method implements an equivalence relation on non-null object references: // * // * @param obj // * the reference object with which to compare. // * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. // * @see #hashCode() // * @see java.util.HashMap // */ // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (!(this.clazz.isInstance(obj))) { // try { // if (obj instanceof String) { // String stringObj = (String) obj; // return this.getStringValue().equals(stringObj); // } else if (obj instanceof Float) { // Float floatObj = (Float) obj; // return Float.valueOf(this.getStringValue()).equals(floatObj); // } else if (obj instanceof Integer) { // Integer integerObj = (Integer) obj; // return Integer.valueOf(this.getStringValue()).equals(integerObj); // } else if (obj instanceof Long) { // Long longObj = (Long) obj; // return Long.valueOf(this.getStringValue()).equals(longObj); // } // } catch (NumberFormatException e) { // LOG.error("Sorry, unable to Cast incompatible types ->" + this.clazz + " & " + obj.getClass(), e); // } // return super.equals(obj); // } // return this.value.equals(obj); // } // } // Path: src/main/java/com/stratio/connector/deep/engine/query/functions/DeepEquals.java import com.stratio.deep.commons.entity.Cells; import org.apache.spark.api.java.function.Function; import com.stratio.connector.deep.engine.query.structures.Term; import com.stratio.crossdata.common.data.ColumnName; /* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.deep.engine.query.functions; /** * Class that defines DeepEquals, Spark function that determines if the value in the given field is equals to the provided term. * */ public class DeepEquals implements Function<Cells, Boolean> { private static final long serialVersionUID = -6143471452730703044L; /** * Term to be compared. */
private final Term<?> term;
Stratio/stratio-connector-deep
src/test/java/com/stratio/connector/deep/ConnectionsHandler.java
// Path: src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java // public class DeepQueryEngine extends CommonsQueryEngine { // // private final DeepSparkContext deepContext; // // private final DeepConnectionHandler deepConnectionHandler; // // /** // * Basic constructor. // * // * @param deepContext // * The Deep Context // * @param deepConnectionHandler // * The connection handler // */ // public DeepQueryEngine(DeepSparkContext deepContext, DeepConnectionHandler deepConnectionHandler) { // super(deepConnectionHandler); // this.deepContext = deepContext; // this.deepConnectionHandler = deepConnectionHandler; // } // // /* // * (non-Javadoc) // * // * @see // * com.stratio.crossdata.common.connector.IQueryEngine#execute(com.stratio.crossdata.common.logicalplan.LogicalWorkflow // * ) // */ // @Override // public QueryResult executeWorkFlow(LogicalWorkflow workflow) throws UnsupportedException, ExecutionException { // QueryExecutor executor = new QueryExecutor(deepContext, deepConnectionHandler); // QueryResult queryResult = executor.executeWorkFlow(workflow); // // return queryResult; // // } // // @Override protected void asyncExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler) throws UnsupportedException { // throw new UnsupportedException("method asyncExecuteWorkFlow not supported"); // // } // // /** // * Execute a paged query, // * @param queryId the queryID, // * @param workflow the workflow. // * @param resultHandler the resultHandler. // * @param pageSize the pageSize. // * @throws ConnectorException if any error happens. // */ // @Override protected void pagedExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler, int pageSize) throws ConnectorException{ // throw new UnsupportedException("method pagedExecuteWorkFlow not supported"); // } // // // /* // * (non-Javadoc) // * // * @see com.stratio.crossdata.common.connector.IQueryEngine#stop(java.lang.String) // */ // @Override // public void stop(String queryId) throws UnsupportedException, ExecutionException { // throw new UnsupportedException("method stop not supported"); // // // } // // // // }
import com.stratio.connector.deep.engine.query.DeepQueryEngine; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.exceptions.UnsupportedException;
package com.stratio.connector.deep; public class ConnectionsHandler { protected final DeepConnector deepConnector; public ConnectionsHandler() throws InitializationException { this.deepConnector = new DeepConnector(); this.deepConnector.init(null); } public void connect(ConnectorClusterConfig configuration) throws ConnectionException { this.deepConnector.connect(null, configuration); } public DeepConnector getDeepContextConnector() { return this.deepConnector; }
// Path: src/main/java/com/stratio/connector/deep/engine/query/DeepQueryEngine.java // public class DeepQueryEngine extends CommonsQueryEngine { // // private final DeepSparkContext deepContext; // // private final DeepConnectionHandler deepConnectionHandler; // // /** // * Basic constructor. // * // * @param deepContext // * The Deep Context // * @param deepConnectionHandler // * The connection handler // */ // public DeepQueryEngine(DeepSparkContext deepContext, DeepConnectionHandler deepConnectionHandler) { // super(deepConnectionHandler); // this.deepContext = deepContext; // this.deepConnectionHandler = deepConnectionHandler; // } // // /* // * (non-Javadoc) // * // * @see // * com.stratio.crossdata.common.connector.IQueryEngine#execute(com.stratio.crossdata.common.logicalplan.LogicalWorkflow // * ) // */ // @Override // public QueryResult executeWorkFlow(LogicalWorkflow workflow) throws UnsupportedException, ExecutionException { // QueryExecutor executor = new QueryExecutor(deepContext, deepConnectionHandler); // QueryResult queryResult = executor.executeWorkFlow(workflow); // // return queryResult; // // } // // @Override protected void asyncExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler) throws UnsupportedException { // throw new UnsupportedException("method asyncExecuteWorkFlow not supported"); // // } // // /** // * Execute a paged query, // * @param queryId the queryID, // * @param workflow the workflow. // * @param resultHandler the resultHandler. // * @param pageSize the pageSize. // * @throws ConnectorException if any error happens. // */ // @Override protected void pagedExecuteWorkFlow(String queryId, LogicalWorkflow workflow, // IResultHandler resultHandler, int pageSize) throws ConnectorException{ // throw new UnsupportedException("method pagedExecuteWorkFlow not supported"); // } // // // /* // * (non-Javadoc) // * // * @see com.stratio.crossdata.common.connector.IQueryEngine#stop(java.lang.String) // */ // @Override // public void stop(String queryId) throws UnsupportedException, ExecutionException { // throw new UnsupportedException("method stop not supported"); // // // } // // // // } // Path: src/test/java/com/stratio/connector/deep/ConnectionsHandler.java import com.stratio.connector.deep.engine.query.DeepQueryEngine; import com.stratio.crossdata.common.connector.ConnectorClusterConfig; import com.stratio.crossdata.common.data.ClusterName; import com.stratio.crossdata.common.exceptions.ConnectionException; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.crossdata.common.exceptions.UnsupportedException; package com.stratio.connector.deep; public class ConnectionsHandler { protected final DeepConnector deepConnector; public ConnectionsHandler() throws InitializationException { this.deepConnector = new DeepConnector(); this.deepConnector.init(null); } public void connect(ConnectorClusterConfig configuration) throws ConnectionException { this.deepConnector.connect(null, configuration); } public DeepConnector getDeepContextConnector() { return this.deepConnector; }
public DeepQueryEngine getQueryEngine() throws UnsupportedException {
Stratio/stratio-connector-deep
src/main/java/com/stratio/connector/deep/DeepConfigurationBuilder.java
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // }
import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; import com.stratio.deep.core.context.DeepSparkConfig; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Arrays; import java.util.List;
package com.stratio.connector.deep; /** * This class must build the deep configuration. * Created by jmgomez on 25/02/15. */ public class DeepConfigurationBuilder { /** * Constructor. * @throws InitializationException */ public DeepConfigurationBuilder() throws InitializationException { // Retrieving configuration InputStream input = DeepConnector.class.getClassLoader().getResourceAsStream(CONFIGURATION_FILE_CONSTANT); if (input == null) { String message = "Sorry, unable to find [" + CONFIGURATION_FILE_CONSTANT + "]"; LOGGER.error(message); throw new InitializationException(message); } } /** * Return the HDFS path. * @return the HDFS path. */ public String getHDFSFilePath(){ return connectorConfig.getConfig(ExtractorConstants.HDFS).getString( ExtractorConstants.FS_FILE_PATH); } /** * The log. */ private static transient final Logger LOGGER = LoggerFactory.getLogger(DeepConnector.class); /** * The configuration file name. */ private static final String CONFIGURATION_FILE_CONSTANT = "connector-application.conf"; /** * Connector configuration from the properties file. */ private Config connectorConfig = ConfigFactory.load(CONFIGURATION_FILE_CONSTANT); /** * This method return the implementation class. * @param dataSourceName the datasource. * @return */ public String getImplementationClass(String dataSourceName){
// Path: src/main/java/com/stratio/connector/deep/configuration/DeepConnectorConstants.java // public final class DeepConnectorConstants { // private DeepConnectorConstants(){ // // } // // public static final String HDFS = "hdfs"; // public static final String SPARK_MASTER = "spark.master"; // public static final String SPARK_HOME = "spark.home"; // public static final String SPARK_JARS = "spark.jars"; // public static final String CLUSTER_PREFIX_CONSTANT = "cluster"; // public static final String IMPL_CLASS_SUFIX_CONSTANT = ".implClass"; // public static final String EXTRACTOR_IMPL_CLASS = "extractorImplClass"; // public static final String DEEP_CONNECTOR_JOB_CONSTANT = "DeepConnectorJob"; // // public static final int DEFAULT_RESULT_SIZE = 10000; // public static final String PROPERTY_DEFAULT_LIMIT = "DefaultLimit"; // public static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory"; // public static final String SPARK_DRIVER_MEMORY = "spark.driver.memory"; // public static final String SPARK_TASK_CPUS = "spark.task.cpus"; // public static final String SPARK_DEFAULT_PARALELISM = "spark.default.parallelism"; // public static final String SPARK_CORES_MAX = "spark.cores.max"; // public static final String SPARK_DRIVER_RESULTSIZE = "spark.driver.maxResultSize"; // // // // // } // Path: src/main/java/com/stratio/connector/deep/DeepConfigurationBuilder.java import com.stratio.connector.deep.configuration.DeepConnectorConstants; import com.stratio.crossdata.common.exceptions.InitializationException; import com.stratio.deep.commons.extractor.utils.ExtractorConstants; import com.stratio.deep.core.context.DeepSparkConfig; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Arrays; import java.util.List; package com.stratio.connector.deep; /** * This class must build the deep configuration. * Created by jmgomez on 25/02/15. */ public class DeepConfigurationBuilder { /** * Constructor. * @throws InitializationException */ public DeepConfigurationBuilder() throws InitializationException { // Retrieving configuration InputStream input = DeepConnector.class.getClassLoader().getResourceAsStream(CONFIGURATION_FILE_CONSTANT); if (input == null) { String message = "Sorry, unable to find [" + CONFIGURATION_FILE_CONSTANT + "]"; LOGGER.error(message); throw new InitializationException(message); } } /** * Return the HDFS path. * @return the HDFS path. */ public String getHDFSFilePath(){ return connectorConfig.getConfig(ExtractorConstants.HDFS).getString( ExtractorConstants.FS_FILE_PATH); } /** * The log. */ private static transient final Logger LOGGER = LoggerFactory.getLogger(DeepConnector.class); /** * The configuration file name. */ private static final String CONFIGURATION_FILE_CONSTANT = "connector-application.conf"; /** * Connector configuration from the properties file. */ private Config connectorConfig = ConfigFactory.load(CONFIGURATION_FILE_CONSTANT); /** * This method return the implementation class. * @param dataSourceName the datasource. * @return */ public String getImplementationClass(String dataSourceName){
return connectorConfig.getConfig(DeepConnectorConstants.CLUSTER_PREFIX_CONSTANT)