Skip to content

Commit 0257f50

Browse files
authored
Merge pull request #28 from securenative/dev
Support custom path
2 parents c519270 + 3ec8675 commit 0257f50

40 files changed

+264
-224
lines changed

README.md

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,12 @@ To get your *API KEY*, login to your SecureNative account and go to project sett
5656
SecureNative can automatically load your config from *securenative.properties* file or from the file that is specified in your *SECURENATIVE_CONFIG_FILE* env variable:
5757

5858
```java
59+
// Options 1: Use default config file path
5960
SecureNative secureNative = SecureNative.init();
61+
62+
// Options 2: Use specific config file path
63+
Path path = Paths.get("/path/to/securenative.properties");
64+
SecureNative secureNative = SecureNative.init(path);
6065
```
6166
### Option 2: Initialize via API Key
6267

@@ -140,8 +145,8 @@ public void track(HttpServletRequest request, HttpServletResponse response) {
140145
**Example**
141146

142147
```java
143-
@RequestMapping("/track")
144-
public void track(HttpServletRequest request, HttpServletResponse response) {
148+
@RequestMapping("/verify")
149+
public void verify(HttpServletRequest request, HttpServletResponse response) {
145150
SecureNativeContext context = SecureNative.contextBuilder()
146151
.fromHttpServletRequest(request)
147152
.build();
@@ -159,9 +164,9 @@ public void track(HttpServletRequest request, HttpServletResponse response) {
159164
.build();
160165

161166
VerifyResult verifyResult = secureNative.verify(eventOptions);
162-
verifyResult.getRiskLevel() // Low, Medium, High
163-
verifyResult.score() // Risk score: 0 -1 (0 - Very Low, 1 - Very High)
164-
verifyResult.getTriggers() // ["TOR", "New IP", "New City"]
167+
verifyResult.getRiskLevel(); // Low, Medium, High
168+
verifyResult.score(); // Risk score: 0 -1 (0 - Very Low, 1 - Very High)
169+
verifyResult.getTriggers(); // ["TOR", "New IP", "New City"]
165170
}
166171
```
167172

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<groupId>com.securenative.java</groupId>
77
<artifactId>securenative-java</artifactId>
88
<packaging>jar</packaging>
9-
<version>0.4.6</version>
9+
<version>0.4.7</version>
1010
<url>https://github.com/securenative/securenative-java</url>
1111

1212
<name>${project.groupId}:${project.artifactId}:${project.version}</name>

src/main/java/com/securenative/ApiManager.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55

66
public interface ApiManager {
77
void track(EventOptions eventOptions);
8+
89
VerifyResult verify(EventOptions eventOptions);
910
}

src/main/java/com/securenative/ApiManagerImpl.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
import com.securenative.exceptions.SecureNativeSDKException;
88
import com.securenative.models.Event;
99
import com.securenative.models.EventOptions;
10-
import com.securenative.models.VerifyResult;
1110
import com.securenative.models.SDKEvent;
11+
import com.securenative.models.VerifyResult;
1212

1313
public class ApiManagerImpl implements ApiManager {
1414
private final EventManager eventManager;
@@ -32,7 +32,7 @@ public VerifyResult verify(EventOptions eventOptions) {
3232
logger.info("Verify event call");
3333
Event event = new SDKEvent(eventOptions, this.options);
3434
try {
35-
return this.eventManager.sendSync(VerifyResult.class , event, ApiRoute.VERIFY.getApiRoute());
35+
return this.eventManager.sendSync(VerifyResult.class, event, ApiRoute.VERIFY.getApiRoute());
3636
} catch (Exception ex) {
3737
logger.error("Failed to call verify", ex);
3838
return this.options.getFailoverStrategy() == FailoverStrategy.FAIL_OPEN ?
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
package com.securenative;
22

3-
import com.securenative.exceptions.SecureNativeInvalidUriException;
43
import com.securenative.exceptions.SecureNativeParseException;
54
import com.securenative.models.Event;
65

76
import java.io.IOException;
87

98
public interface EventManager {
109
<T> T sendSync(Class<T> clazz, Event event, String url) throws IOException, SecureNativeParseException;
10+
1111
void sendAsync(Event event, String url, Boolean retry);
12+
1213
void startEventsPersist();
14+
1315
void stopEventsPersist();
1416
}

src/main/java/com/securenative/EventOptionsBuilder.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33

44
import com.securenative.context.SecureNativeContext;
5+
import com.securenative.enums.EventTypes;
56
import com.securenative.exceptions.SecureNativeInvalidOptionsException;
67
import com.securenative.models.EventOptions;
7-
import com.securenative.enums.EventTypes;
88
import com.securenative.models.UserTraits;
99

1010
import java.util.Date;
@@ -15,11 +15,11 @@ public class EventOptionsBuilder {
1515
private static final Logger logger = Logger.getLogger(EventOptionsBuilder.class);
1616
private final EventOptions eventOptions;
1717

18-
public static EventOptionsBuilder builder(String eventType){
18+
public static EventOptionsBuilder builder(String eventType) {
1919
return new EventOptionsBuilder(eventType);
2020
}
2121

22-
public static EventOptionsBuilder builder(EventTypes eventType){
22+
public static EventOptionsBuilder builder(EventTypes eventType) {
2323
return new EventOptionsBuilder(eventType.getType());
2424
}
2525

@@ -68,7 +68,7 @@ public EventOptionsBuilder timestamp(Date timestamp) {
6868
}
6969

7070
public EventOptions build() throws SecureNativeInvalidOptionsException {
71-
if(this.eventOptions.getProperties().size() > MAX_PROPERTIES_SIZE){
71+
if (this.eventOptions.getProperties().size() > MAX_PROPERTIES_SIZE) {
7272
throw new SecureNativeInvalidOptionsException(String.format("You can have only up to %d custom properties", MAX_PROPERTIES_SIZE));
7373
}
7474
return this.eventOptions;

src/main/java/com/securenative/Logger.java

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,28 @@ public String toString() {
2424

2525
interface ILogger {
2626
void trace(String var1, Object... var2);
27+
2728
void debug(String var1, Object... var2);
29+
2830
void info(String var1, Object... var2);
31+
2932
void warn(String var1, Object... var2);
33+
3034
void error(String var1, Object... var2);
3135
}
3236

3337
public class Logger implements ILogger {
3438
private static LogLevel _logLevel = LogLevel.ERROR;
3539
private org.slf4j.Logger _logger = null;
3640

37-
private Logger(Class<?> clazz){
41+
private Logger(Class<?> clazz) {
3842
this._logger = LoggerFactory.getLogger(clazz);
3943
}
4044

4145
static void initLogger(String logLevel) {
42-
try{
46+
try {
4347
_logLevel = LogLevel.valueOf(logLevel);
44-
}catch (IllegalArgumentException ex){
48+
} catch (IllegalArgumentException ex) {
4549
_logLevel = LogLevel.ERROR;
4650
}
4751
}
@@ -52,35 +56,35 @@ public static Logger getLogger(Class<?> clazz) {
5256

5357
@Override
5458
public void trace(String var1, Object... var2) {
55-
if(_logLevel == LogLevel.TRACE){
59+
if (_logLevel == LogLevel.TRACE) {
5660
_logger.error(var1, var2);
5761
}
5862
}
5963

6064
@Override
6165
public void debug(String var1, Object... var2) {
62-
if(_logLevel == LogLevel.DEBUG){
66+
if (_logLevel == LogLevel.DEBUG) {
6367
_logger.debug(var1, var2);
6468
}
6569
}
6670

6771
@Override
6872
public void info(String var1, Object... var2) {
69-
if(_logLevel == LogLevel.INFO){
73+
if (_logLevel == LogLevel.INFO) {
7074
_logger.error(var1, var2);
7175
}
7276
}
7377

7478
@Override
7579
public void warn(String var1, Object... var2) {
76-
if(_logLevel == LogLevel.WARN){
80+
if (_logLevel == LogLevel.WARN) {
7781
_logger.warn(var1, var2);
7882
}
7983
}
8084

8185
@Override
8286
public void error(String var1, Object... var2) {
83-
if(_logLevel == LogLevel.ERROR){
87+
if (_logLevel == LogLevel.ERROR) {
8488
_logger.error(var1, var2);
8589
}
8690
}

src/main/java/com/securenative/ResourceStream.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package com.securenative;
2+
23
import java.io.InputStream;
34

45
public interface ResourceStream {

src/main/java/com/securenative/SecureNative.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import javax.servlet.http.HttpServletRequest;
1717
import java.io.IOException;
18+
import java.nio.file.Path;
1819
import java.util.stream.Collectors;
1920

2021
import static com.securenative.utils.SignatureUtils.SIGNATURE_HEADER;
@@ -32,7 +33,7 @@ private SecureNative(SecureNativeOptions options) throws SecureNativeSDKExceptio
3233
this.options = options;
3334

3435
EventManager eventManager = new SecureNativeEventManager(new SecureNativeHTTPClient(options), options);
35-
if(options.getAutoSend()){
36+
if (options.getAutoSend()) {
3637
eventManager.startEventsPersist();
3738
}
3839
this.apiManager = new ApiManagerImpl(eventManager, options);
@@ -51,16 +52,22 @@ public static SecureNative init(String apiKey) throws SecureNativeSDKException,
5152
if (Utils.isNullOrEmpty(apiKey)) {
5253
throw new SecureNativeConfigException("You must pass your SecureNative api key");
5354
}
54-
SecureNativeConfigurationBuilder builder = SecureNativeConfigurationBuilder.defaultConfigBuilder();
55+
SecureNativeConfigurationBuilder builder = SecureNativeConfigurationBuilder.defaultConfigBuilder();
5556
SecureNativeOptions secureNativeOptions = builder.withApiKey(apiKey).build();
5657
return init(secureNativeOptions);
5758
}
5859

60+
5961
public static SecureNative init() throws SecureNativeSDKException, SecureNativeConfigException {
6062
SecureNativeOptions secureNativeOptions = ConfigurationManager.loadConfig();
6163
return init(secureNativeOptions);
6264
}
6365

66+
public static SecureNative init(Path path) throws SecureNativeSDKException, SecureNativeConfigException {
67+
SecureNativeOptions secureNativeOptions = ConfigurationManager.loadConfig(path);
68+
return init(secureNativeOptions);
69+
}
70+
6471
public static SecureNative getInstance() throws SecureNativeSDKIllegalStateException {
6572
if (secureNative == null) {
6673
throw new SecureNativeSDKIllegalStateException();
@@ -72,24 +79,24 @@ public SecureNativeOptions getOptions() {
7279
return options;
7380
}
7481

75-
public static SecureNativeConfigurationBuilder configBuilder(){
82+
public static SecureNativeConfigurationBuilder configBuilder() {
7683
return SecureNativeConfigurationBuilder.defaultConfigBuilder();
7784
}
7885

79-
public static SecureNativeContextBuilder contextBuilder(){
86+
public static SecureNativeContextBuilder contextBuilder() {
8087
return SecureNativeContextBuilder.defaultContextBuilder();
8188
}
8289

8390
public boolean verifyRequestPayload(HttpServletRequest request) throws IOException {
8491
String requestSignature = request.getHeader(SIGNATURE_HEADER);
85-
String body = request.getReader().lines().collect(Collectors.joining());
92+
String body = request.getReader().lines().collect(Collectors.joining());
8693

8794
return SignatureUtils.isValidSignature(requestSignature, body, this.options.getApiKey());
8895
}
8996

9097
@Override
9198
public void track(EventOptions eventOptions) {
92-
this.apiManager.track(eventOptions);
99+
this.apiManager.track(eventOptions);
93100
}
94101

95102
@Override

src/main/java/com/securenative/SecureNativeEventManager.java

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,25 @@
33
import com.fasterxml.jackson.core.JsonProcessingException;
44
import com.fasterxml.jackson.databind.DeserializationFeature;
55
import com.fasterxml.jackson.databind.ObjectMapper;
6+
import com.securenative.config.SecureNativeOptions;
67
import com.securenative.exceptions.SecureNativeHttpException;
7-
import com.securenative.exceptions.SecureNativeInvalidUriException;
88
import com.securenative.exceptions.SecureNativeParseException;
99
import com.securenative.exceptions.SecureNativeSDKException;
1010
import com.securenative.http.HttpClient;
1111
import com.securenative.http.HttpResponse;
1212
import com.securenative.models.Event;
1313
import com.securenative.models.RequestOptions;
14-
import com.securenative.config.SecureNativeOptions;
1514

1615
import java.io.IOException;
17-
import java.util.concurrent.*;
16+
import java.util.concurrent.ConcurrentLinkedQueue;
17+
import java.util.concurrent.Executors;
18+
import java.util.concurrent.ScheduledExecutorService;
19+
import java.util.concurrent.TimeUnit;
1820

1921

2022
public class SecureNativeEventManager implements EventManager {
2123
private static final Logger logger = Logger.getLogger(SecureNativeEventManager.class);
22-
private final int[] coefficients = new int[] { 1, 1, 2, 3, 5, 8, 13 };
24+
private final int[] coefficients = new int[]{1, 1, 2, 3, 5, 8, 13};
2325
private int attempt = 0;
2426
private Boolean sendEnabled = false;
2527
private ScheduledExecutorService scheduler;
@@ -54,7 +56,7 @@ public <T> T sendSync(Class<T> clazz, Event event, String url) throws IOExceptio
5456
String responseBody = response.getBody();
5557
try {
5658
return mapper.readValue(responseBody, clazz);
57-
}catch (Exception ex){
59+
} catch (Exception ex) {
5860
logger.error("Failed to parse response body", ex.getMessage());
5961
throw new SecureNativeParseException(ex.getMessage());
6062
}
@@ -77,10 +79,10 @@ public void sendAsync(Event event, String url, Boolean retry) {
7779

7880
private void sendEvents() throws InterruptedException {
7981
if (!this.events.isEmpty() && this.sendEnabled) {
80-
RequestOptions requestOptions = events.peek();
82+
RequestOptions requestOptions = events.peek();
8183
try {
8284
String body = requestOptions.getBody();
83-
HttpResponse resp = this.httpClient.post(requestOptions.getUrl(), body);
85+
HttpResponse resp = this.httpClient.post(requestOptions.getUrl(), body);
8486
if (resp.getStatusCode() == 401) {
8587
requestOptions.setRetry(false);
8688
}
@@ -93,15 +95,15 @@ private void sendEvents() throws InterruptedException {
9395
} catch (Exception ex) {
9496
logger.error("Failed to send event", ex.getMessage());
9597
if (requestOptions.getRetry()) {
96-
if(attempt++ == coefficients.length){
98+
if (attempt++ == coefficients.length) {
9799
attempt = 0;
98100
}
99101
int backoff = coefficients[attempt] * this.options.getInterval();
100102
logger.debug("BackOff automatic sending by", backoff);
101103
this.sendEnabled = false;
102104
Thread.sleep(backoff);
103105
this.sendEnabled = true;
104-
}else{
106+
} else {
105107
// remove the event from queue, retry: false
106108
events.remove(requestOptions);
107109
}
@@ -119,7 +121,10 @@ public void startEventsPersist() {
119121
this.sendEnabled = true;
120122
this.scheduler = Executors.newSingleThreadScheduledExecutor();
121123
this.scheduler.scheduleWithFixedDelay(() -> {
122-
try { sendEvents(); } catch (InterruptedException ignored) { }
124+
try {
125+
sendEvents();
126+
} catch (InterruptedException ignored) {
127+
}
123128
}, 0, this.options.getInterval(), TimeUnit.MILLISECONDS);
124129
}
125130

@@ -131,7 +136,8 @@ public void stopEventsPersist() {
131136
this.scheduler.shutdown();
132137
// drain event queue
133138
this.scheduler.awaitTermination(this.options.getTimeout(), TimeUnit.MILLISECONDS);
134-
} catch (InterruptedException ignored) { }
139+
} catch (InterruptedException ignored) {
140+
}
135141

136142
logger.debug("Stopped event persistence");
137143
}

0 commit comments

Comments
 (0)