Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
ru.sms_activate.SMSActivateApi Maven / Gradle / Ivy
package ru.sms_activate;
import com.google.gson.reflect.TypeToken;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ru.sms_activate.client_enums.SMSActivateClientRentStatus;
import ru.sms_activate.client_enums.SMSActivateClientStatus;
import ru.sms_activate.client_enums.SMSActivateLanguage;
import ru.sms_activate.error.SMSActivateBannedException;
import ru.sms_activate.error.SMSActivateUnknownException;
import ru.sms_activate.error.base.SMSActivateBaseException;
import ru.sms_activate.error.base.SMSActivateBaseTypeError;
import ru.sms_activate.error.wrong_parameter.SMSActivateWrongParameter;
import ru.sms_activate.error.wrong_parameter.SMSActivateWrongParameterException;
import ru.sms_activate.listener.SMSActivateExceptionListener;
import ru.sms_activate.listener.SMSActivateWebClientListener;
import ru.sms_activate.response.SMSActivateCountries;
import ru.sms_activate.response.api_activation.*;
import ru.sms_activate.response.api_activation.enums.SMSActivateGetStatusActivation;
import ru.sms_activate.response.api_activation.enums.SMSActivateServerStatus;
import ru.sms_activate.response.api_activation.enums.SMSActivateStatusNumber;
import ru.sms_activate.response.api_activation.extra.SMSActivateAvailableService;
import ru.sms_activate.response.api_activation.extra.SMSActivateCountryInfo;
import ru.sms_activate.response.api_activation.extra.SMSActivatePriceInfo;
import ru.sms_activate.response.api_activation.extra.SMSActivateServiceInfo;
import ru.sms_activate.response.api_rent.SMSActivateGetRentListResponse;
import ru.sms_activate.response.api_rent.SMSActivateGetRentServices;
import ru.sms_activate.response.api_rent.SMSActivateGetRentServicesAndCountriesResponse;
import ru.sms_activate.response.api_rent.SMSActivateGetRentStatusResponse;
import ru.sms_activate.response.api_rent.enums.SMSActivateRentStatus;
import ru.sms_activate.response.api_rent.extra.SMSActivateRentActivation;
import ru.sms_activate.response.api_rent.extra.SMSActivateSMS;
import ru.sms_activate.response.extra.SMSActivateCountry;
import ru.sms_activate.response.qiwi.SMSActivateGetQiwiRequisitesResponse;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* The class is a high-level API for interacting with the SMS-Activate API.
* API capabilities allow you to work with the service through your software.
* Before starting work, you must have an API key and a referral link to use all the API capabilities.
* Use the methods that are implemented in this class.
*
* All methods and constructor in SMSActivateApi throw SMSActivateWrongParameterException
* Before request set referral identifier
*
* @see SMSActivateWrongParameterException
* @see SMSActivateBaseException
* @see SMSActivateWrongParameter
* @see SMSActivateBaseTypeError
*/
public class SMSActivateApi {
/**
* The minimal rent time.
*/
public static final int MINIMAL_RENT_TIME = 4;
/**
* Regular expression for numbers.
*/
private static final Pattern patternDigit = Pattern.compile("\\d+(?:[\\.,]\\d+)?");
/**
* Max size of count activations in one request.
*/
private static final int MAX_BATCH_SIZE = 10;
/**
* Special validator for server responses.
*/
protected final SMSActivateValidator validator = new SMSActivateValidator();
/**
* Api key from site.
*/
private String apiKey;
/**
* Referral identifier.
*/
private String ref = null;
/**
* Listener on data from server.
*/
protected SMSActivateWebClientListener smsActivateWebClientListener;
public SMSActivateApi() {
this("");
}
/**
* Constructor API sms-activate with API key.
*
* @param apiKey API key (not be null).
*/
public SMSActivateApi(@NotNull String apiKey) {
this.apiKey = apiKey;
}
/**
* Sets the listener on request to server.
*
* @param smsActivateWebClientListener listener on request to server.
*/
public void setSmsActivateWebClientListener(@NotNull SMSActivateWebClientListener smsActivateWebClientListener) {
this.smsActivateWebClientListener = smsActivateWebClientListener;
}
/**
* Sets the listener on error.
*
* @param smsActivateExceptionListener listener on error.
*/
public void setSmsActivateExceptionListener(@NotNull SMSActivateExceptionListener smsActivateExceptionListener) {
this.validator.setSmsActivateExceptionListener(smsActivateExceptionListener);
}
/**
* Sets the apiKey.
*
* @param apiKey api key sms-activate.
*/
public void setApiKey(@NotNull String apiKey) {
this.apiKey = apiKey;
}
/**
* Returns the API key.
*
* @return apiKey API key (not be null).
*/
@NotNull
public String getApiKey() {
return apiKey;
}
/**
* If you are a partner of sms-activate set the referral identifier. For example ref=softgorregtelegram.
* The referral identifier are given by support.
*
* @param ref referral identifier.
*/
public void setRef(@NotNull String ref) {
this.ref = ref;
}
/**
* Returns the referral link.
*
* @return referral link.
*/
@Nullable
public String getRef() {
return ref;
}
/**
* Returns the current account balance in rubles.
*
* @return current account balance in rubles.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public BigDecimal getBalance() throws SMSActivateBaseException {
return getBalanceByAction(SMSActivateAction.GET_BALANCE);
}
/**
* Returns the current account balance and cashBack in rubles.
*
* @return current account balance and cashBack in rubles.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetBalanceAndCashBackResponse getBalanceAndCashBack() throws SMSActivateBaseException {
BigDecimal balance = getBalance();
BigDecimal balanceAndCashBack = getBalanceByAction(SMSActivateAction.GET_BALANCE_AND_CASHBACK);
return new SMSActivateGetBalanceAndCashBackResponse(balance, balanceAndCashBack.subtract(balance));
}
/**
* Returns the available services from setting site.
*
* @return the available services.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetNumbersStatusResponse getNumbersStatusByDefaultSettingFromSite() throws SMSActivateBaseException {
return getNumbersStatus(null, null);
}
/**
* Returns the available services by country and operator.
*
* @param countryId id country.
* @param operatorSet set names operators mobile network.
* @return available services by county and operator (not be null).
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect.
*
*/
@NotNull
public SMSActivateGetNumbersStatusResponse getNumbersStatus(@Nullable Integer countryId, @Nullable Set operatorSet)
throws SMSActivateBaseException {
if (countryId != null && countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
String operator = null;
if (operatorSet != null) {
operatorSet.removeIf(String::isEmpty);
if (!operatorSet.isEmpty()) {
operator = String.join(",", operatorSet);
}
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_NUMBERS_STATUS);
smsActivateURLBuilder.append(SMSActivateURLKey.OPERATOR, operator);
if (countryId != null) {
smsActivateURLBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId));
}
String serviceJsonResponse = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
Map serviceMap = jsonParser.tryParseJson(serviceJsonResponse, new TypeToken>() {
}.getType(), validator);
Map serviceInfoMap = new HashMap<>();
for (Map.Entry entry : serviceMap.entrySet()) {
String serviceName = entry.getKey();
String[] parts = serviceName.split("_");
serviceInfoMap.put(serviceName, new SMSActivateServiceInfo(
parts[0],
entry.getValue(),
parts[1].equals("1")
));
}
return new SMSActivateGetNumbersStatusResponse(serviceInfoMap);
}
/**
* Returns the activation by service, countryId.
*
* @param countryId id country.
* @param service service name for activation.
* @return activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateActivation getNumber(int countryId, @NotNull String service) throws SMSActivateBaseException {
return getNumber(countryId, service, false);
}
/**
* Returns the activation by service, countryId.
*
* @param countryId id country.
* @param service service name for activation.
* @param forward true if need number phone with redirection else false.
* @return activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateActivation getNumber(int countryId, @NotNull String service, boolean forward) throws SMSActivateBaseException {
return getNumber(countryId, service, forward, null, null);
}
/**
* Returns the activation by service, countryId, phoneException, operator, forward
*
* @param countryId id country.
* @param service service name for activation.
* @param operatorSet set mobile operators if operatorSet is null then .
* @param phoneExceptionSet set excepted id numbers prefix if phoneExceptionSet is null then.
* @param forward is it necessary to request a number with forwarding.
* @return activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_PHONE_EXCEPTION - if one or more numbers prefix is incorrect.
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateActivation getNumber(
int countryId,
@NotNull String service,
boolean forward,
@Nullable Set operatorSet,
@Nullable Set phoneExceptionSet
) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
String phoneException = null;
String operator = null;
if (phoneExceptionSet != null) {
phoneExceptionSet.removeIf(String::isEmpty);
if (!phoneExceptionSet.isEmpty()) {
phoneException = String.join(",", phoneExceptionSet);
}
}
if (operatorSet != null) {
operatorSet.removeIf(String::isEmpty);
if (!operatorSet.isEmpty()) {
operator = String.join(",", operatorSet);
}
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_NUMBER);
smsActivateURLBuilder.append(SMSActivateURLKey.REF, ref)
.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId))
.append(SMSActivateURLKey.SERVICE, service)
.append(SMSActivateURLKey.FORWARD, forward ? "1" : "0")
.append(SMSActivateURLKey.OPERATOR, operator)
.append(SMSActivateURLKey.PHONE_EXCEPTION, phoneException);
String responseFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
validator.throwExceptionWithBan(responseFromServer);
if (!responseFromServer.startsWith(SMSActivateMagicConstant.ACCESS)) {
throw validator.getBaseExceptionByErrorNameOrUnknown(responseFromServer, null);
}
try {
String[] parts = responseFromServer.split(":");
int id = Integer.parseInt(parts[1]);
long number = Long.parseLong(parts[2]);
return new SMSActivateActivation(id, number, service);
} catch (NumberFormatException e) {
throw validator.getBaseExceptionByErrorNameOrUnknown(responseFromServer, "Error formatting to number.");
}
}
/**
* Returns the specified object id by countryId, multiService.
* Separator for multiService is commas.
*
* @param countryId id country.
* @param multiServiceSet services for ordering (not be null).
* @return SMSActivateGetMultiServiceNumberResponse object.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect;
* NOT_AVAILABLE - if country not supported multi-service.
*
*/
@NotNull
public SMSActivateGetMultiServiceNumberResponse getMultiServiceNumber(int countryId, @NotNull Set multiServiceSet)
throws SMSActivateBaseException {
return getMultiServiceNumber(countryId, multiServiceSet, null, null);
}
/**
* Returns the specified object with activations id by countryId, multiService.
* Separator for multiService, multiForward and operator is commas.
*
* @param countryId id country.
* @param serviceMap map service where key is service name, value is forward.
* @return specified object with activations.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect;
* NOT_AVAILABLE - if country not supported multi-service.
*
*/
@NotNull
public SMSActivateGetMultiServiceNumberResponse getMultiServiceNumber(int countryId, @NotNull Map serviceMap) throws SMSActivateBaseException {
return getMultiServiceNumber(countryId, serviceMap, null);
}
/**
* Returns the specified object with activations id by countryId, multiService.
* Separator for multiService, multiForward and operator is commas.
*
* @param countryId id country.
* @param serviceMap map service where key is service name, value is forward.
* @param operatorSet mobile operator.
* @return specified object with activations.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect;
* NOT_AVAILABLE - if country not supported multi-service.
*
*/
@NotNull
public SMSActivateGetMultiServiceNumberResponse getMultiServiceNumber(int countryId, @NotNull Map serviceMap, @Nullable Set operatorSet) throws SMSActivateBaseException {
return getMultiServiceNumber(countryId, serviceMap.keySet(), operatorSet, new ArrayList<>(serviceMap.values()));
}
/**
* Returns the specified object with activations id by countryId, multiService.
* Separator for multiService, multiForward and operator is commas.
*
* @param countryId id country.
* @param multiServiceSet services for ordering (not be null).
* @param operatorSet mobile operator.
* @param multiForwardList is it necessary to request a number with forwarding.
* @return specified object with activations.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* @throws SMSActivateBannedException if your account has been banned.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if operator or countryId is incorrect;
* BAD_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect;
* NOT_AVAILABLE - if country not supported multi-service.
*
*/
@NotNull
private SMSActivateGetMultiServiceNumberResponse getMultiServiceNumber(
int countryId,
@NotNull Set multiServiceSet,
@Nullable Set operatorSet,
@Nullable List multiForwardList
) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
multiServiceSet.removeIf(String::isEmpty);
String strMultiService = String.join(",", multiServiceSet);
String strOperators = null;
String strMultiForward = null;
if (multiForwardList != null) {
strMultiForward = multiForwardList.stream()
.filter(forward -> !Objects.isNull(forward))
.map(forward -> forward ? "1" : "0")
.collect(Collectors.joining(","));
}
if (operatorSet != null) {
operatorSet.removeIf(String::isEmpty);
strOperators = String.join(",", operatorSet);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_MULTI_SERVICE_NUMBER);
smsActivateURLBuilder.append(SMSActivateURLKey.REF, String.valueOf(ref))
.append(SMSActivateURLKey.MULTI_SERVICE, strMultiService)
.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId))
.append(SMSActivateURLKey.MULTI_FORWARD, strMultiForward)
.append(SMSActivateURLKey.OPERATOR, strOperators);
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
validator.throwExceptionWithBan(jsonFromServer);
List smsActivateActivationList = jsonParser.tryParseJson(jsonFromServer, new TypeToken>() {
}.getType(), validator);
return new SMSActivateGetMultiServiceNumberResponse(smsActivateActivationList);
}
/**
* Sets the status activation.
* Get number using getNumber method after that the following actions are available:
* CANCEL - Cancel activation (if the number did not suit you)
* MESSAGE_WAS_SENT - Report that SMS has been sent (optional)
*
* To activate with status READY:
* CANCEL - Cancel activation
*
* Immediately after receiving the code:
* REQUEST_ONE_MORE_CODE - Request another SMS
* FINISH - Confirm SMS code and complete activation
*
* To activate with status RETRY_GET:
* FINISH - Confirm SMS code and complete activation
*
* @param activationId id to set activation status (not be null).
* @param status value to establish (not be null).
* @return access activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_STATUS - if service is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateSetStatusResponse setStatus(int activationId, @NotNull SMSActivateClientStatus status)
throws SMSActivateBaseException {
return setStatusWithForwardPhone(activationId, status, null);
}
/**
* Sets the status activation.
* Get number using getNumber method after that the following actions are available:
* CANCEL - Cancel activation (if the number did not suit you)
* MESSAGE_WAS_SENT - Report that SMS has been sent (optional)
*
* To activate with status READY:
* CANCEL - Cancel activation
*
* Immediately after receiving the code:
* REQUEST_ONE_MORE_CODE - Request another SMS
* FINISH - Confirm SMS code and complete activation
*
* To activate with status RETRY_GET:
* FINISH - Confirm SMS code and complete activation
*
* @param activation activation to set activation status (not be null).
* @param status value to establish (not be null).
* @return access activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_STATUS - if service is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateSetStatusResponse setStatus(@NotNull SMSActivateActivation activation, @NotNull SMSActivateClientStatus status)
throws SMSActivateBaseException {
return setStatus(activation.getId(), status);
}
/**
* Sets the status activation.
* Get number using getNumber method after that the following actions are available:
* CANCEL - Cancel activation (if the number did not suit you)
* SEND_READY_NUMBER - Report that SMS has been sent (optional)
*
* To activate with status READY:
* CANCEL - Cancel activation
*
* Immediately after receiving the code:
* REQUEST_ONE_MORE_CODE - Request another SMS
* FINISH - Confirm SMS code and complete activation
*
* To activate with status RETRY_GET:
* FINISH - Confirm SMS code and complete activation
*
* @param activationId id to set activation status (not be null).
* @param status value to establish (not be null).
* @param forwardPhone number phone for forward.
* @return access activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_STATUS - if service is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateSetStatusResponse setStatusWithForwardPhone(
int activationId,
@NotNull SMSActivateClientStatus status,
@Nullable Long forwardPhone
) throws SMSActivateBaseException {
if (forwardPhone != null && forwardPhone <= 0) {
throw new SMSActivateWrongParameterException(
"Phone number for forwarding must be positive.",
"Телефон для переадресации должен быть положительный."
);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.SET_STATUS);
smsActivateURLBuilder.append(SMSActivateURLKey.STATUS, String.valueOf(status.getId()))
.append(SMSActivateURLKey.ID, String.valueOf(activationId));
if (forwardPhone != null) {
smsActivateURLBuilder.append(SMSActivateURLKey.FORWARD, String.valueOf(forwardPhone));
}
String statusFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateServerStatus smsActivateServerStatus = SMSActivateServerStatus.getStatusByName(statusFromServer);
if (smsActivateServerStatus != SMSActivateServerStatus.UNKNOWN) {
return new SMSActivateSetStatusResponse(smsActivateServerStatus);
}
throw validator.getBaseExceptionByErrorNameOrUnknown(statusFromServer, null);
}
/**
* Returns the state by id activation.
*
* @param activationId id activation to get activation state.
* @return state activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateGetStatusResponse getStatus(int activationId) throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_STATUS);
smsActivateURLBuilder.append(SMSActivateURLKey.ID, String.valueOf(activationId));
String code = null;
String statusFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
if (statusFromServer.contains(":")) {
String[] parts = statusFromServer.split(":");
statusFromServer = parts[0];
code = parts[1];
}
SMSActivateGetStatusActivation status = SMSActivateGetStatusActivation.getStatusByName(statusFromServer);
if (status != SMSActivateGetStatusActivation.UNKNOWN) {
return new SMSActivateGetStatusResponse(status, code);
}
throw validator.getBaseExceptionByErrorNameOrUnknown(statusFromServer, null);
}
/**
* Returns the state by activation.
*
* @param activation activation to get state.
* @return state activation.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateGetStatusResponse getStatus(@NotNull SMSActivateActivation activation) throws SMSActivateBaseException {
return getStatus(activation.getId());
}
/**
* Returns the specified object from server with text sms.
*
* @param activationId id activation.
* @return full text sms with status:
*
* if SMS arrived, then the answer will be with the FULL_SMS status
* if expected then WAIT_CODE
* if canceled then CANCEL
*
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateGetFullSmsResponse getFullSms(int activationId) throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_FULL_SMS);
smsActivateURLBuilder.append(SMSActivateURLKey.ID, String.valueOf(activationId));
String smsFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateStatusNumber smsActivateStatusNumber = SMSActivateStatusNumber.getStatusByName(smsFromServer);
if (smsActivateStatusNumber != SMSActivateStatusNumber.UNKNOWN) {
String message = "";
if (smsActivateStatusNumber == SMSActivateStatusNumber.FULL_SMS) {
message = smsFromServer.split(":", 2)[1];
}
return new SMSActivateGetFullSmsResponse(smsActivateStatusNumber, message);
}
throw validator.getBaseExceptionByErrorNameOrUnknown(smsFromServer, null);
}
/**
* Returns the specified object from server with text sms.
*
* @param activation activation to get fullSMS.
* @return full text sms with status:
*
* if SMS arrived, then the answer will be with the FULL_SMS status
* if expected then WAIT_CODE
* if canceled then CANCEL
*
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ACTIVATION - if activation is not exist.
*
*/
@NotNull
public SMSActivateGetFullSmsResponse getFullSms(@NotNull SMSActivateActivation activation) throws SMSActivateBaseException {
return getFullSms(activation.getId());
}
/**
* Returns the all actual prices in all countries and all services.
*
* @return price list country.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetPricesResponse getAllPrices() throws SMSActivateBaseException {
return getPricesByCountryIdAndServiceShortName(null, null);
}
/**
* Returns the all actual price services by country id.
*
* @param countryId id country.
* @return all actual price services by country id.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateGetPricesResponse getPricesAllServicesByCountryId(int countryId) throws SMSActivateBaseException {
return getPricesByCountryIdAndServiceShortName(countryId, null);
}
/**
* Returns the all actual price services by country id.
*
* @param serviceShortName short name service.
* @return all actual price services by country id.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateGetPricesResponse getPricesAllCountryByServiceShortName(@NotNull String serviceShortName)
throws SMSActivateBaseException {
return getPricesByCountryIdAndServiceShortName(null, serviceShortName);
}
/**
* Returns the actual rent prices by country and service short name.
*
* @param countryId id number (default 0).
* @param serviceShortName service for needed price list (default null).
* {@code null, null -> all service and all country}
* {@code countryId, null -> all service in country}
* {@code null, serviceShortName -> all country by service}
* @return price list country.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_OPERATOR - if country id is incorrect;
* WRONG_SERVICE - if service is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateGetPricesResponse getPricesByCountryIdAndServiceShortName(@Nullable Integer countryId, @Nullable String serviceShortName)
throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_PRICES);
if (serviceShortName != null) {
if (serviceShortName.length() != 2) {
throw new SMSActivateWrongParameterException("Wrong service short name.", "Некорректное короткое имя сервиса.");
}
smsActivateURLBuilder.append(SMSActivateURLKey.SERVICE, serviceShortName);
}
if (countryId != null) {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
smsActivateURLBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId));
}
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
Map> smsActivateGetPriceMap = jsonParser.tryParseJson(jsonFromServer,
new TypeToken>>() {
}.getType(), validator);
return new SMSActivateGetPricesResponse(smsActivateGetPriceMap);
}
/**
* Returns the country with information.
*
* @return country with information.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetCountriesResponse getCountries() throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_COUNTRIES);
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
Map countryInformationMap = jsonParser.tryParseJson(jsonFromServer, new TypeToken>() {
}.getType(), validator);
return new SMSActivateGetCountriesResponse(countryInformationMap);
}
/**
* Returns the qiwi response with data on wallet.
*
* @return qiwi response with data on wallet with status:
*
* SUCCESS - all is OK;
* FALSE - acceptance of qiwi payments is not possible.
*
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetQiwiRequisitesResponse getQiwiRequisites() throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_QIWI_REQUISITES);
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
return jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
}
/**
* Returns the activation for additional service by forwarding.
*
* @param parentActivation activation to get additional service.
* @param service service short name.
* @return id activation for additional service by forwarding
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_BALANCE - if your balance is less than the price.
*
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_ADDITIONAL_SERVICE - if additional service is incorrect;
* WRONG_ACTIVATION_ID - if id parent is incorrect;
* WRONG_SECURITY - if trying to transfer an activation ID without forwarding, or a completed / inactive activation;
* REPEAT_ADDITIONAL_SERVICE - if ordered again service that has already been purchased;
*
*/
@NotNull
public SMSActivateActivation getAdditionalService(@NotNull SMSActivateActivation parentActivation, @NotNull String service) throws SMSActivateBaseException {
return getAdditionalService(parentActivation.getId(), service);
}
/**
* Returns the activation for additional service by forwarding.
*
* @param parentActivationId id activation.
* @param service service short name.
* @return id activation for additional service by forwarding
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_BALANCE - if your balance is less than the price.
*
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_ADDITIONAL_SERVICE - if additional service is incorrect;
* WRONG_ACTIVATION_ID - if id parent is incorrect;
* WRONG_SECURITY - if trying to transfer an activation ID without forwarding, or a completed / inactive activation;
* REPEAT_ADDITIONAL_SERVICE - if ordered again service that has already been purchased;
*
*/
@NotNull
public SMSActivateActivation getAdditionalService(int parentActivationId, @NotNull String service) throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_ADDITIONAL_SERVICE);
smsActivateURLBuilder.append(SMSActivateURLKey.ID, String.valueOf(parentActivationId))
.append(SMSActivateURLKey.SERVICE, service);
String responseFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
if (!responseFromServer.startsWith(SMSActivateMagicConstant.ADDITIONAL)) {
throw validator.getBaseExceptionByErrorNameOrUnknown(responseFromServer, null);
}
try {
String[] parts = responseFromServer.split(":");
int childId = Integer.parseInt(parts[1]);
long number = Long.parseLong(parts[2]);
return new SMSActivateActivation(childId, number, service);
} catch (NumberFormatException e) {
throw validator.getBaseExceptionByErrorNameOrUnknown(responseFromServer, "Error formatting to number.");
}
}
/**
* Returns the rent object with countries supported rent and accessed services by country.
*
* @param countryId id country (default 0).
* @param operatorSet mobile operators.
* @param hours rent time in hours (default {@value MINIMAL_RENT_TIME}).
* @return the rent object with countries supported rent and accessed services by country.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter error types in this method:
*
* BAD_KEY - if your api-key is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateGetRentServicesAndCountriesResponse getRentServicesAndCountries(int countryId, @Nullable Set operatorSet, int hours)
throws SMSActivateBaseException {
if (hours < MINIMAL_RENT_TIME) {
throw new SMSActivateWrongParameterException(
"Time rent can't be negative or equals " + MINIMAL_RENT_TIME,
"Время аренды не может быть меньше или равно " + MINIMAL_RENT_TIME
);
}
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
String operator = null;
if (operatorSet != null) {
operatorSet.removeIf(String::isEmpty);
if (!operatorSet.isEmpty()) {
operator = String.join(",", operatorSet);
}
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_RENT_SERVICES_AND_COUNTRIES);
smsActivateURLBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId))
.append(SMSActivateURLKey.OPERATOR, operator)
.append(SMSActivateURLKey.RENT_TIME, String.valueOf(hours));
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
return jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
}
/**
* Returns the object rent on {@value MINIMAL_RENT_TIME} by countryId and service short name.
*
* @param countryId id country.
* @param service service to which you need to get a number.
* @return object rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_SERVICE - if service is incorrect;
* ACCOUNT_INACTIVE - if no free numbers.
*
*/
@NotNull
public SMSActivateRentActivation getRentNumber(int countryId, @NotNull String service) throws SMSActivateBaseException {
return getRentNumber(countryId, service, MINIMAL_RENT_TIME);
}
/**
* Returns the object rent on {@value MINIMAL_RENT_TIME} by countryId and service short name.
*
* @param countryId id country.
* @param service service to which you need to get a number.
* @param hours rent time in hours.
* @return object rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_SERVICE - if service is incorrect;
* ACCOUNT_INACTIVE - if no free numbers.
*
*/
@NotNull
public SMSActivateRentActivation getRentNumber(int countryId, @NotNull String service, int hours) throws SMSActivateBaseException {
return getRentNumber(countryId, service, null, hours, null);
}
/**
* Returns the object rent on time.
*
* @param countryId id country (default 0 - Russia).
* @param service service to which you need to get a number.
* @param operator mobile operator.
* @param hours rent time in hours (default MINIMAL_RENT_TIME hour).
* @param urlWebhook url for webhook.
* @return object rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if currently no numbers;
* NO_BALANCE - if your balance is less than the price;
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* BAD_SERVICE - if service is incorrect;
* ACCOUNT_INACTIVE - if no free numbers;
* WRONG_OPERATOR - if operator is incorrect;
* WRONG_COUNTRY_ID - if country id is incorrect.
*
*/
@NotNull
public SMSActivateRentActivation getRentNumber(
int countryId,
@NotNull String service,
@Nullable String operator,
int hours,
@Nullable String urlWebhook
) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
if (hours < MINIMAL_RENT_TIME) {
throw new SMSActivateWrongParameterException(
String.format("The rental time cannot be less than %d.", MINIMAL_RENT_TIME),
String.format("Время аренды не может быть меньше чем %d.", MINIMAL_RENT_TIME)
);
}
if (operator != null && operator.isEmpty()) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_OPERATOR);
}
if (urlWebhook != null && urlWebhook.isEmpty()) {
throw new SMSActivateWrongParameterException(
"Parameter url-webhook can't be empty.",
"Параметер url-webhook не может быть пустым."
);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_RENT_NUMBER);
smsActivateURLBuilder.append(SMSActivateURLKey.RENT_TIME, String.valueOf(hours))
.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId))
.append(SMSActivateURLKey.OPERATOR, operator)
.append(SMSActivateURLKey.URL, urlWebhook)
.append(SMSActivateURLKey.SERVICE, service);
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
if (validator.checkOnNotContainsSuccessStatus(jsonFromServer)) {
SMSActivateErrorResponse errorResponse = jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
throw validator.getBaseExceptionByErrorNameOrUnknown(errorResponse.getMessage(), null);
}
SMSActivateGetRentNumberResponse smsActivateGetRentNumberResponse = jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
return smsActivateGetRentNumberResponse.getSMSmsActivateGetRentNumber();
}
/**
* Returns the list sms.
*
* @param rentId id received in response when ordering a number.
* @return list sms.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ID_RENT - if is not input.
* STATUS_WAIT_CODE - if not sms.
* STATUS_CANCEL - if rent is canceled.
* STATUS_FINISH - if rent is finished.
*
*/
@NotNull
public SMSActivateGetRentStatusResponse getRentStatus(int rentId) throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_RENT_STATUS);
smsActivateURLBuilder.append(SMSActivateURLKey.ID, String.valueOf(rentId));
String jsonResponseFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
if (validator.checkOnNotContainsSuccessStatus(jsonResponseFromServer)) {
SMSActivateErrorResponse errorResponse = jsonParser.tryParseJson(jsonResponseFromServer, new TypeToken() {
}.getType(), validator);
throw validator.getBaseExceptionByErrorNameOrUnknown(errorResponse.getMessage(), null);
}
return jsonParser.tryParseJson(jsonResponseFromServer, new TypeToken() {
}.getType(), validator);
}
/**
* Returns the list sms.
*
* @param rentActivation to get the list sms.
* @return list sms.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ID_RENT - if is not input.
* STATUS_WAIT_CODE - if not sms.
* STATUS_CANCEL - if rent is canceled.
* STATUS_FINISH - if rent is finished.
*
*/
@NotNull
public SMSActivateGetRentStatusResponse getRentStatus(@NotNull SMSActivateRentActivation rentActivation) throws SMSActivateBaseException {
return getRentStatus(rentActivation.getId());
}
/**
* Sets the status on rent.
*
* @param rentId id activation for set status rent.
* @param status status rent.
* @return response status from server.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ID_RENT - if is not input.
* INCORRECT_STATUS - if status is incorrect.
* CANT_CANCEL - if it is impossible to cancel the rent (more than 20 min.).
* ALREADY_FINISH - if rent is finished.
* ALREADY_CANCEL - if rent is canceled.
* INVALID_PHONE - if id is incorrect.
*
*/
@NotNull
public SMSActivateRentStatus setRentStatus(int rentId, @NotNull SMSActivateClientRentStatus status)
throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.SET_RENT_STATUS);
smsActivateURLBuilder.append(SMSActivateURLKey.ID, String.valueOf(rentId))
.append(SMSActivateURLKey.STATUS, String.valueOf(status.getId()));
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
if (validator.checkOnNotContainsSuccessStatus(jsonFromServer)) {
SMSActivateErrorResponse response = jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
throw validator.getBaseExceptionByErrorNameOrUnknown(response.getMessage(), null);
}
return SMSActivateRentStatus.SUCCESS;
}
/**
* Sets the status on rent.
*
* @param rentActivation rent to set status.
* @param status status rent.
* @return response status from server.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
* NO_ID_RENT - if is not input.
* INCORRECT_STATUS - if status is incorrect.
* CANT_CANCEL - if it is impossible to cancel the rent (more than 20 min.).
* ALREADY_FINISH - if rent is finished.
* ALREADY_CANCEL - if rent is canceled.
* INVALID_PHONE - if id is incorrect.
*
*/
@NotNull
public SMSActivateRentStatus setRentStatus(@NotNull SMSActivateRentActivation rentActivation, @NotNull SMSActivateClientRentStatus status)
throws SMSActivateBaseException {
return setRentStatus(rentActivation.getId(), status);
}
/**
* Returns the current rents.
*
* @return current rents.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
* Types errors:
* Base type error in this method:
*
* NO_NUMBERS - if no rented phone numbers numbers.
*
* Wrong parameter type error:
*
* BAD_KEY - if your api-key is incorrect;
*
*/
@NotNull
public SMSActivateGetRentListResponse getRentList() throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_RENT_LIST);
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
if (validator.checkOnNotContainsSuccessStatus(jsonFromServer)) {
SMSActivateErrorResponse smsActivateErrorResponse = jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
throw validator.getBaseExceptionByErrorNameOrUnknown(smsActivateErrorResponse.getMessage(), null);
}
return jsonParser.tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
}
/**
* Wait the sms on activation by minutes.
*
* @param activationId activation id to get sms.
* @param maxWaitMinutes minutes to wait.
* @return code from sms.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@Nullable
public String waitSms(int activationId, int maxWaitMinutes) throws SMSActivateBaseException {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, maxWaitMinutes);
SMSActivateGetStatusResponse statusResponse = getStatus(activationId);
while (System.currentTimeMillis() < calendar.getTime().getTime()) {
if (
statusResponse.getSMSActivateGetStatus() == SMSActivateGetStatusActivation.OK &&
!statusResponse.getCodeFromSMS().equalsIgnoreCase(SMSActivateMagicConstant.NO_CODE)
) {
return statusResponse.getCodeFromSMS();
}
try {
Thread.sleep(5 * 1000);
} catch (Exception ignored) {
}
statusResponse = getStatus(activationId);
}
return statusResponse.getCodeFromSMS();
}
/**
* Wait the sms on activation by minutes.
*
* @param activation activation to get sms.
* @param maxWaitMinutes minutes to wait.
* @return code from sms.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@Nullable
public String waitSms(@NotNull SMSActivateActivation activation, int maxWaitMinutes) throws SMSActivateBaseException {
return waitSms(activation.getId(), maxWaitMinutes);
}
/**
* Returns a list of sms that came for rent after a while.
*
* @param rentActivation rent for rent for which you need to return the list of sms.
* @param maxWaitMinutes how many minutes to wait.
* @return list of sms that came for rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public List waitSmsForRent(@NotNull SMSActivateRentActivation rentActivation, int maxWaitMinutes) throws SMSActivateBaseException {
return this.waitSmsForRent(rentActivation.getId(), maxWaitMinutes);
}
/**
* Returns a list of sms that came for rent after a while.
*
* @param rentId rent for rent for which you need to return the list of sms.
* @param maxWaitMinutes how many minutes to wait.
* @return list of sms that came for rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public List waitSmsForRent(int rentId, int maxWaitMinutes) throws SMSActivateBaseException {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, maxWaitMinutes);
int countSMS = 0;
List smsActivateSMS = new ArrayList<>();
try {
SMSActivateGetRentStatusResponse rentStatus = this.getRentStatus(rentId);
countSMS = rentStatus.getCountSms();
smsActivateSMS = rentStatus.getSmsActivateSMSList();
} catch (SMSActivateBaseException e) {
if (e.getTypeError() != SMSActivateBaseTypeError.WAIT_CODE) {
throw e;
}
}
while (System.currentTimeMillis() < calendar.getTime().getTime()) {
try {
SMSActivateGetRentStatusResponse rentStatus = this.getRentStatus(rentId);
if (rentStatus.getCountSms() != countSMS) {
return rentStatus.getSmsActivateSMSList();
}
} catch (SMSActivateBaseException e) {
if (e.getTypeError() != SMSActivateBaseTypeError.WAIT_CODE) {
throw e;
}
}
try {
Thread.sleep(5 * 1000);
} catch (Exception ignored) {
}
}
return smsActivateSMS;
}
/**
* Returns the list of current activations.
*
* @return list of current activations.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetCurrentActivations getCurrentActivations() throws SMSActivateBaseException {
return getCurrentActivations(0, 10);
}
/**
* Returns the list of current activations.
*
* @param start serial number of the first requested activation (default 0).
* @param length count activations in one query (default ({@value MAX_BATCH_SIZE})).
* Maximum number of activations in one request - {@value MAX_BATCH_SIZE}
* @return list of current activations.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetCurrentActivations getCurrentActivations(int start, int length) throws SMSActivateBaseException {
if (start < 0) {
throw new SMSActivateWrongParameterException(
"The serial number of the first activation requested must be positive.",
"Серийный номер первой запрошенной активации должен быть положительным."
);
}
if (length > MAX_BATCH_SIZE) {
throw new SMSActivateWrongParameterException(
"The number of received activations in the request must be no more than 10.",
"Количество получаемых активаций в запросе должно быть неболее 10."
);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, SMSActivateAction.GET_CURRENT_ACTIVATIONS);
smsActivateURLBuilder.append(SMSActivateURLKey.START, String.valueOf(start))
.append(SMSActivateURLKey.LENGTH, String.valueOf(length));
String jsonFromServer = new SMSActivateWebClient(smsActivateWebClientListener)
.getOrThrowCommonException(smsActivateURLBuilder, validator);
return new SMSActivateJsonParser().tryParseJson(jsonFromServer, new TypeToken() {
}.getType(), validator);
}
/**
* Returns the list available services with info.
*
* @return list available services with info.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetAvailableServices getAvailableServices() throws SMSActivateBaseException {
return getAvailableServicesByCountryId(0);
}
/**
* Returns the list available services with info by country id.
* @param countryId country id (default 0).
* @return list available services with info by country id.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetAvailableServices getAvailableServicesByCountryId(int countryId) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(
SMSActivateMagicConstant.SPECIAL_API_ACTIVATION_URL,
SMSActivateURLKey.ACT,
SMSActivateAction.GET_AVAILABLE_SERVICES_BY_COUNTRY
);
smsActivateURLBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId));
SMSActivateWebClient smsActivateWebClient = new SMSActivateWebClient(smsActivateWebClientListener);
String jsonFromServer = smsActivateWebClient.getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
TypeToken> typeToken = new TypeToken>() {
};
return new SMSActivateGetAvailableServices(jsonParser.tryParseJson(jsonFromServer, typeToken.getType(), validator));
}
/**
* Returns the current services with cost on site.
*
* @return current services with cost on site.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetNumbersStatusAndMediumSmsTime getNumbersStatusAndMediumSmsTime() throws SMSActivateBaseException {
return getNumbersStatusAndMediumSmsTimeByCountryId(0);
}
/**
* Returns the current services with cost on site by countryId.
*
* @param countryId country id (default 0).
* @return current services with cost on site by countryId.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetNumbersStatusAndMediumSmsTime getNumbersStatusAndMediumSmsTimeByCountryId(int countryId) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(SMSActivateMagicConstant.SPECIAL_API_ACTIVATION_URL, SMSActivateURLKey.ACT, SMSActivateAction.GET_NUMBERS_STATUS_AND_MEDIUM_SMS_TIME);
smsActivateURLBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId));
SMSActivateWebClient webClient = new SMSActivateWebClient(smsActivateWebClientListener);
String jsonFromServer = webClient.getOrThrowCommonException(smsActivateURLBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
TypeToken> typeToken = new TypeToken>() {
};
return new SMSActivateGetNumbersStatusAndMediumSmsTime(jsonParser.tryParseJson(jsonFromServer, typeToken.getType(), validator));
}
/**
* Returns the rent services and countries supported rent without apiKey.
*
* @return services and countries.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetRentServices getRentServices() throws SMSActivateBaseException {
return getRentServicesByCountryId(0);
}
/**
* Returns the rent services and countries supported rent by countryId without apiKey.
*
* @param countryId country id.
* @return services and countries supported rent by countryId.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetRentServices getRentServicesByCountryId(int countryId) throws SMSActivateBaseException {
return getRentServicesByCountryIdAndRentOperator(countryId, null);
}
/**
* Returns the rent services and countries supported rent by countryId and rent operator without apiKey
*
* @param countryId country id.
* @param rentOperator rent operator.
* @return services and countries supported rent by countryId and rent operator.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateGetRentServices getRentServicesByCountryIdAndRentOperator(int countryId, @Nullable String rentOperator) throws SMSActivateBaseException {
if (countryId < 0) {
throw new SMSActivateWrongParameterException(SMSActivateWrongParameter.WRONG_COUNTRY_ID);
}
SMSActivateURLBuilder urlBuilder = new SMSActivateURLBuilder(
SMSActivateMagicConstant.SPECIAL_API_RENT_URL,
SMSActivateURLKey.ACTION,
SMSActivateAction.GET_RENT_SERVICES
);
urlBuilder.append(SMSActivateURLKey.COUNTRY, String.valueOf(countryId))
.append(SMSActivateURLKey.OPERATOR_RENT_FORWARD, rentOperator);
SMSActivateWebClient webClient = new SMSActivateWebClient(smsActivateWebClientListener);
String jsonFromServer = webClient.getOrThrowCommonException(urlBuilder, validator);
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
Type type = new TypeToken() {
}.getType();
return jsonParser.tryParseJson(jsonFromServer, type, validator);
}
/**
* Returns the list of countries supported rent.
*
* @param language language for request.
* @return list of countries supported rent.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateCountries getRentCountries(@NotNull SMSActivateLanguage language) throws SMSActivateBaseException {
return getByUrlAndLanguage(
SMSActivateMagicConstant.SPECIAL_API_RENT_URL,
SMSActivateAction.GET_RENT_COUNTRIES,
language
);
}
/**
* Returns the list of countries supported rent.
*
* @param language language for request.
* @return list of countries.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
public SMSActivateCountries getAllCountriesByLanguage(@NotNull SMSActivateLanguage language) throws SMSActivateBaseException {
return getByUrlAndLanguage(
SMSActivateMagicConstant.SPECIAL_API_RENT_URL,
SMSActivateAction.GET_ALL_COUNTRIES,
language
);
}
/**
* Returns the list of countries.
*
* @param url target url.
* @param action type of query.
* @param language response language.
* @return list of countries.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
* @throws SMSActivateUnknownException if error type not documented.
*/
@NotNull
private SMSActivateCountries getByUrlAndLanguage(
@NotNull String url,
@NotNull SMSActivateAction action,
@NotNull SMSActivateLanguage language
) throws SMSActivateBaseException {
SMSActivateURLBuilder urlBuilder = new SMSActivateURLBuilder(url, SMSActivateURLKey.ACTION, action);
urlBuilder.append(SMSActivateURLKey.LANGUAGE, language.getShortName());
SMSActivateWebClient webClient = new SMSActivateWebClient(smsActivateWebClientListener);
String jsonFromServer = webClient.getOrThrowCommonException(urlBuilder, validator);
Type typeOf = new TypeToken>() {
}.getType();
SMSActivateJsonParser jsonParser = new SMSActivateJsonParser();
return new SMSActivateCountries(jsonParser.tryParseJson(jsonFromServer, typeOf, validator));
}
/**
* Returns the current account balance by specific action.
*
* @param smsActivateAction name specific action to get balance.
* @return current account balance.
* @throws SMSActivateWrongParameterException if one of parameters is incorrect.
*/
@NotNull
private BigDecimal getBalanceByAction(@NotNull SMSActivateAction smsActivateAction) throws SMSActivateBaseException {
SMSActivateURLBuilder smsActivateURLBuilder = new SMSActivateURLBuilder(apiKey, smsActivateAction);
String balance = new SMSActivateWebClient(smsActivateWebClientListener).getOrThrowCommonException(smsActivateURLBuilder, validator);
Matcher matcher = patternDigit.matcher(balance);
if (!matcher.find()) {
throw new SMSActivateBaseException("Error: " + balance, "Ошибка: " + balance);
}
return new BigDecimal(matcher.group());
}
}