Skip to content

Commit

Permalink
Aligned SDK to latest API version (v2.2)
Browse files Browse the repository at this point in the history
Added support for importing email addresses from a file / input stream /
 byte array
Improved null values handling while serializing JSON data
Fixed an issue with the charset used while serializing input data (#4)
Refactored the way RestRequest builds Http requests
  • Loading branch information
verifalia committed Jun 28, 2020
1 parent f1f5df3 commit 422eebf
Show file tree
Hide file tree
Showing 17 changed files with 810 additions and 138 deletions.
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
![Verifalia API](https://img.shields.io/badge/Verifalia%20API-v2.1-green)
![Verifalia API](https://img.shields.io/badge/Verifalia%20API-v2.2-green)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.verifalia/verifalia-java-sdk/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.verifalia/verifalia-java-sdk)

Verifalia RESTful API - Java SDK and helper library
Expand Down Expand Up @@ -214,6 +214,33 @@ verifalia

Once deleted, a job is gone and there is no way to retrieve its email validation(s).

### How to import email addresses from a file ###

In addition to submitting structured data (see the paragraphs above), it also possible to import the email addresses to
verify [from a file](https://verifalia.com/developers#email-validations-importing-file) provided by the user. Once submitted,
the email verification job follows the same flow as described above.

Verifalia accepts the following file types:
- plain text files (.txt), with one email address per line
- comma-separated values (.csv), tab-separated values (.tsv) and other delimiter-separated values files
- Microsoft Excel spreadsheets (.xls and .xlsx)

Here is how to extract and verify email addresses, for example, from the third column of the first sheet of an Excel workbook,
starting from the second row:

```java
FileValidationRequest request = new FileValidationRequest("my-list.xlsx",
WellKnownMimeTypes.EXCEL_XLSX);

// request.setSheet(0); // 0 is the default value
request.setColumn(2); // zero-based column number
request.setStartingRow(1); // zero-based starting row number

Validation validation = verifalia
.getEmailValidations()
.submit(request);
```

### Iterating over your email validation jobs ###

For management and reporting purposes, you may want to obtain a detailed list of your past email
Expand Down Expand Up @@ -297,8 +324,7 @@ Iterable<DailyUsage> dailyUsages = verifalia
.dateFilter(lastThirtyDays)
.build());

for (DailyUsage dailyUsage : dailyUsages)
{
for (DailyUsage dailyUsage : dailyUsages) {
System.out.printf("%s - credit packs: %d, free daily credits: %d",
dailyUsage.Date,
dailyUsage.CreditPacks,
Expand Down
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<groupId>com.github.verifalia</groupId>
<artifactId>verifalia-java-sdk</artifactId>
<packaging>jar</packaging>
<version>2.0.2</version>
<version>2.1.0</version>
<name>Verifalia SDK for Java</name>
<description>Verifalia provides a simple HTTPS-based API for validating email addresses and checking whether they are deliverable or not. This library allows to easily integrate with Verifalia and verify email addresses in real-time.</description>
<url>https://verifalia.com/</url>
Expand Down Expand Up @@ -40,6 +40,7 @@
<lombok.version>1.18.4</lombok.version>
<apache.commons.version>3.9</apache.commons.version>
<http.client.version>4.5.12</http.client.version>
<http.mime.version>4.5.12</http.mime.version>
<json.lib.version>2.4</json.lib.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
Expand Down Expand Up @@ -78,6 +79,11 @@
<artifactId>httpclient</artifactId>
<version>${http.client.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${http.mime.version}</version>
</dependency>
<!-- JSON Library -->
<dependency>
<groupId>net.sf.json-lib</groupId>
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/verifalia/api/VerifaliaRestClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class VerifaliaRestClient {
/**
* The default API version supported by the SDK.
*/
public static final String DEFAULT_API_VERSION = "v2.1";
public static final String DEFAULT_API_VERSION = "v2.2";

/**
* Cached REST client object.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ public class DurationSerializer extends JsonSerializer<Duration> {

@Override
public void serialize(Duration value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value != null) {
if (value == null) {
jgen.writeNull();
} else {
jgen.writeString(toString(value));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,24 @@

package com.verifalia.api.emailvalidations;

import com.verifalia.api.common.Direction;
import com.verifalia.api.common.iterables.IterableHelper;
import com.verifalia.api.common.ListingCursor;
import com.verifalia.api.common.Utils;
import com.verifalia.api.common.filters.FilterPredicateFragment;
import com.verifalia.api.common.models.ListSegment;
import com.verifalia.api.common.models.ListSegmentMeta;
import com.verifalia.api.common.*;
import com.verifalia.api.common.filters.*;
import com.verifalia.api.common.iterables.*;
import com.verifalia.api.common.models.*;
import com.verifalia.api.emailvalidations.models.*;
import com.verifalia.api.exceptions.InsufficientCreditException;
import com.verifalia.api.exceptions.VerifaliaException;
import com.verifalia.api.exceptions.WaitingInterruptedException;
import com.verifalia.api.rest.HttpRequestMethod;
import com.verifalia.api.rest.RestClient;
import com.verifalia.api.rest.RestRequest;
import com.verifalia.api.rest.RestResponse;
import com.verifalia.api.exceptions.*;
import com.verifalia.api.rest.*;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -202,7 +196,7 @@ public Validation submit(@NonNull final String[] emailAddresses, @NonNull final
* @return A {@link Validation} object representing the submitted email validation job.
* @throws VerifaliaException
*/
public Validation submit(@NonNull final ValidationRequest validationRequest) throws VerifaliaException {
public Validation submit(@NonNull final AbstractValidationRequest validationRequest) throws VerifaliaException {
return submit(validationRequest, null);
}

Expand All @@ -214,20 +208,60 @@ public Validation submit(@NonNull final ValidationRequest validationRequest) thr
* @return A {@link Validation} object representing the submitted email validation job.
* @throws VerifaliaException
*/
public Validation submit(@NonNull final ValidationRequest validationRequest, final WaitingStrategy waitingStrategy) throws VerifaliaException {
// Checks the parameters
public Validation submit(@NonNull final AbstractValidationRequest validationRequest, final WaitingStrategy waitingStrategy) throws VerifaliaException {
// Checks the parameters and build the REST request

if (validationRequest.getEntries() == null) {
throw new IllegalArgumentException("emailAddresses cannot be null");
}
if (validationRequest.getEntries().size() == 0) {
throw new IllegalArgumentException("Can't validate an empty batch (emailAddresses)");
RestRequest request;

if (validationRequest instanceof ValidationRequest) {
ValidationRequest standardValidationRequest = (ValidationRequest) validationRequest;

if (standardValidationRequest.getEntries() == null) {
throw new IllegalArgumentException("emailAddresses cannot be null");
}
if (standardValidationRequest.getEntries().size() == 0) {
throw new IllegalArgumentException("Can't validate an empty batch (emailAddresses)");
}

request = new RestRequest(HttpRequestMethod.POST,
"email-validations",
// Explicitly set the charset as UTF-8 (see https://github.com/verifalia/verifalia-java-sdk/issues/4)
new StringEntity(RestRequest.serializeToJson(validationRequest), "UTF-8"));
}
else if (validationRequest instanceof FileValidationRequest) {
// The actual file content will be checked by the Verifalia API

FileValidationRequest fileValidationRequest = (FileValidationRequest) validationRequest;

// Build the multi-part entity
// TODO: Move the entity building part to an ad-hoc class derived from RestRequest

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

// Build the REST request
RestRequest request = new RestRequest(HttpRequestMethod.POST, "email-validations", validationRequest);
// inputFile part

entityBuilder.addBinaryBody("inputFile",
fileValidationRequest.getInputStream(),
fileValidationRequest.getContentType(),
// HACK: Dummy file name to make the underlying Java multi-part form data serializer happy
"file");

// Settings part

entityBuilder.addTextBody("settings",
RestRequest.serializeToJson(fileValidationRequest),
ContentType.parse("application/json"));

request = new RestRequest(HttpRequestMethod.POST,
"email-validations",
entityBuilder.build());
}
else {
throw new IllegalArgumentException("Unsupported class for the validationRequest parameter.");
}

// Send the request to the Verifalia servers

RestResponse response = restClient.execute(request);

// Handle response based on status code
Expand Down Expand Up @@ -260,6 +294,10 @@ public Validation submit(@NonNull final ValidationRequest validationRequest, fin
throw new InsufficientCreditException(response);
}

case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: {
throw new UnsupportedMediaTypeException(response);
}

default: {
throw new VerifaliaException(response);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Verifalia - Email list cleaning and real-time email verification service
* https://verifalia.com/
* support@verifalia.com
*
* Copyright (c) 2005-2020 Cobisi Research
*
* Cobisi Research
* Via Prima Strada, 35
* 35129, Padova
* Italy - European Union
*
* 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.verifalia.api.emailvalidations.models;

import com.verifalia.api.common.serialization.DurationSerializer;
import com.verifalia.api.emailvalidations.serialization.QualityLevelNameSerializer;
import com.verifalia.api.emailvalidations.serialization.ValidationPrioritySerializer;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.Objects.nonNull;

/**
* Represents the abstract base class for email validation requests to be submitted against the Verifalia API.
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class AbstractValidationRequest {
private static final Integer VALIDATION_INPUT_PRIORITY_MIN_VALUE = 0;
private static final Integer VALIDATION_INPUT_PRIORITY_MAX_VALUE = 255;

/**
* An optional user-defined name for the validation job, for your own reference. The name will be returned on
* subsequent API calls and shown on the Verifalia clients area.
*/
private String name;

/**
* A reference to the expected results quality level for this request. Quality levels determine how Verifalia validates
* email addresses, including whether and how the automatic reprocessing logic occurs (for transient statuses) and the
* verification timeouts settings.
* Use one of {@link QualityLevelName#Standard}, {@link QualityLevelName#High} or {@link QualityLevelName#Extreme}
* values or a custom quality level ID if you have one (custom quality levels are available to premium plans only).
*/
@JsonSerialize(using = QualityLevelNameSerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
private QualityLevelName quality;

/**
* The strategy Verifalia follows while determining which email addresses are duplicates, within a multiple items job.
* Duplicated items (after the first occurrence) will have the {@link ValidationEntryStatus#Duplicate} status.
*/
private DeduplicationMode deduplication;

/**
* The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account
* with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others.
* The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to
* {@link ValidationPriority#Highest} (255 - highest priority), where the midway value
* {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the
* concurrent validation jobs for an account using the same priority.
*/
@JsonSerialize(using = ValidationPrioritySerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
private ValidationPriority priority;

/**
* The maximum data retention period Verifalia observes for this verification job, after which the job will be
* automatically deleted. A verification job can be deleted anytime prior to its retention period through the
* {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method.
*/
@JsonSerialize(using = DurationSerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
private Duration retention;
}
Loading

0 comments on commit 422eebf

Please sign in to comment.