Skip to content

Commit 313ccae

Browse files
committed
Fix auth failed error
1 parent e0b490d commit 313ccae

File tree

12 files changed

+73
-48
lines changed

12 files changed

+73
-48
lines changed

build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ repositories {
1111
}
1212

1313
group = "be.teletask.onvif"
14-
version = "1.1.14"
14+
version = "1.1.15"
1515

1616
dependencies {
1717
implementation(kotlin("stdlib"))

src/main/java/be/teletask/onvif/DiscoveryManager.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public class DiscoveryManager {
1616
public static final String TAG = DiscoveryManager.class.getSimpleName();
1717

1818
//Attributes
19-
private OnvifDiscovery discovery;
19+
private final OnvifDiscovery discovery;
2020

2121
//Constructors
2222

src/main/java/be/teletask/onvif/DiscoveryThread.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ public class DiscoveryThread extends Thread {
1818
public static final String TAG = DiscoveryThread.class.getSimpleName();
1919

2020
//Attributes
21-
private DatagramSocket server;
22-
private int timeout;
23-
private DiscoveryParser parser;
24-
private DiscoveryCallback callback;
21+
private final DatagramSocket server;
22+
private final int timeout;
23+
private final DiscoveryParser parser;
24+
private final DiscoveryCallback callback;
2525

2626
//Constructors
2727
DiscoveryThread(DatagramSocket server, int timeout, DiscoveryMode mode, DiscoveryCallback callback) {

src/main/java/be/teletask/onvif/OnvifDiscovery.java

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class OnvifDiscovery {
3838
public static final String TAG = OnvifDiscovery.class.getSimpleName();
3939
private static final String MULTICAST_ADDRESS_IPV4 = "239.255.255.250"; // Simple Service Discovery Protocol
4040
private static final String MULTICAST_ADDRESS_IPV6 = "[FF02::C]";
41-
private static int DISCOVERY_TIMEOUT = 10000;
41+
private static final int DISCOVERY_TIMEOUT = 10000;
4242

4343
private static final Random random = new SecureRandom();
4444

@@ -105,24 +105,26 @@ void probe(DiscoveryMode mode, DiscoveryListener discoveryListener) {
105105

106106
private void broadcast(List<InetAddress> addresses) {
107107
//Our list will be accessed by multiple threads, hence ConcurrentSkipListSet
108-
Collection<Device> devices = new ConcurrentSkipListSet<>();
108+
final Collection<Device> devices = new ConcurrentSkipListSet<>();
109109

110110
//Create a new cached thread pool and a monitor service
111-
ExecutorService executorService = Executors.newCachedThreadPool();
112-
ExecutorService monitor = Executors.newSingleThreadExecutor();
113-
CountDownLatch latch = new CountDownLatch(addresses.size());
114-
List<Runnable> runnables = new ArrayList<>();
111+
final ExecutorService executorService = Executors.newCachedThreadPool();
112+
final ExecutorService monitor = Executors.newSingleThreadExecutor();
113+
final CountDownLatch latch = new CountDownLatch(addresses.size());
114+
final List<Runnable> runnables = new ArrayList<>();
115+
116+
OnvifPacket packet = createDiscoveryPacket();
117+
byte[] data = packet.getData();
115118

116119
//Add runnables to the list to be executed in order
117120
for (InetAddress address : addresses) {
121+
if (address.isLoopbackAddress() || !(address instanceof Inet4Address)) continue;
122+
118123
runnables.add(() -> {
119124
try {
120-
OnvifPacket packet = createDiscoveryPacket();
121-
byte[] data = packet.getData();
122-
123125
int port = random.nextInt(20000) + 40000;
124126

125-
DatagramSocket client = new DatagramSocket(port, address);
127+
final DatagramSocket client = new DatagramSocket(port, address);
126128
client.setBroadcast(true);
127129

128130
//Start a new thread to listen for incoming UDP packages
@@ -198,10 +200,10 @@ private OnvifPacket createDiscoveryPacket() {
198200
List<InetAddress> getInterfaceAddresses() {
199201
List<InetAddress> addresses = new ArrayList<>();
200202
try {
201-
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
203+
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
202204

203205
while (interfaces.hasMoreElements()) {
204-
NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
206+
NetworkInterface networkInterface = interfaces.nextElement();
205207

206208
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
207209
continue; // Don't want to broadcast to the loopback interface

src/main/java/be/teletask/onvif/OnvifExecutor.java

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import java.util.Map;
1818
import java.util.concurrent.ConcurrentHashMap;
1919
import java.util.concurrent.TimeUnit;
20+
import java.util.logging.Level;
21+
import java.util.logging.Logger;
2022

2123
/**
2224
* Created by Tomas Verhelst on 03/09/2018.
@@ -26,37 +28,41 @@ public class OnvifExecutor {
2628

2729
//Constants
2830
public static final String TAG = OnvifExecutor.class.getSimpleName();
31+
private static final Logger LOGGER = Logger.getLogger(OnvifExecutor.class.getName());
2932

3033
//Attributes
31-
private final OkHttpClient client;
3234
private final MediaType reqBodyType = MediaType.parse("application/soap+xml; charset=utf-8;");
33-
private final Credentials credentials = new Credentials("", "");
35+
private final ConcurrentHashMap<String, OkHttpClient> clientPool = new ConcurrentHashMap<>();
3436
private OnvifResponseListener onvifResponseListener;
3537

3638
//Constructors
3739

3840
OnvifExecutor(OnvifResponseListener onvifResponseListener) {
3941
this.onvifResponseListener = onvifResponseListener;
42+
}
4043

41-
DigestAuthenticator authenticator = new DigestAuthenticator(credentials);
42-
Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
43-
44-
client = new OkHttpClient.Builder()
45-
.connectTimeout(3, TimeUnit.SECONDS)
46-
.writeTimeout(5, TimeUnit.SECONDS)
47-
.readTimeout(0, TimeUnit.SECONDS) // PullMessages can keep the connection open longer, timeout will be applied per request
48-
.addInterceptor(new AuthenticationCacheInterceptor(authCache))
49-
.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache))
50-
.build();
44+
/**
45+
* Visszaadja vagy létrehozza az OkHttpClient példányt az adott eszközhöz
46+
*/
47+
private OkHttpClient getClientForDevice(OnvifDevice device) {
48+
String deviceKey = device.getHostName() + ":" + device.getUsername();
49+
return clientPool.computeIfAbsent(deviceKey, key -> {
50+
Credentials deviceCredentials = new Credentials(device.getUsername(), device.getPassword());
51+
DigestAuthenticator authenticator = new DigestAuthenticator(deviceCredentials);
52+
Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
53+
54+
return new OkHttpClient.Builder()
55+
.connectTimeout(3, TimeUnit.SECONDS)
56+
.writeTimeout(5, TimeUnit.SECONDS)
57+
.readTimeout(0, TimeUnit.SECONDS) // PullMessages can keep the connection open longer, timeout will be applied per request
58+
.addInterceptor(new AuthenticationCacheInterceptor(authCache))
59+
.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache))
60+
.build();
61+
});
5162
}
5263

5364
//Methods
5465

55-
private synchronized void setCredentials(String username, String password) {
56-
credentials.setUserName(username);
57-
credentials.setPassword(password);
58-
}
59-
6066
<T> void sendRequest(OnvifDevice device, OnvifRequest<T> request) {
6167
sendRequest(device, request, 5);
6268
}
@@ -65,12 +71,9 @@ <T> void sendRequest(OnvifDevice device, OnvifRequest<T> request) {
6571
* Sends a request to the Onvif-compatible device.
6672
*/
6773
<T> void sendRequest(OnvifDevice device, OnvifRequest<T> request, int timeoutSeconds) {
68-
String body;
69-
synchronized (credentials) {
70-
setCredentials(device.getUsername(), device.getPassword());
71-
body = OnvifXMLBuilder.getSoapHeader(credentials, request.getSoapHeader()) + request.getXml() + OnvifXMLBuilder.getEnvelopeEnd();
72-
}
73-
74+
Credentials deviceCredentials = new Credentials(device.getUsername(), device.getPassword());
75+
String body = OnvifXMLBuilder.getSoapHeader(deviceCredentials, request.getSoapHeader()) + request.getXml() + OnvifXMLBuilder.getEnvelopeEnd();
76+
LOGGER.log(Level.INFO, "Onvif Sending Request: {0}", body);
7477
performXmlRequest(device, request, buildOnvifRequest(device, request, RequestBody.create(body, reqBodyType)), timeoutSeconds);
7578
}
7679

@@ -79,6 +82,12 @@ <T> void sendRequest(OnvifDevice device, OnvifRequest<T> request, int timeoutSec
7982
*/
8083
void clear() {
8184
onvifResponseListener = null;
85+
// Kliensek leállítása és erőforrások felszabadítása
86+
for (OkHttpClient client : clientPool.values()) {
87+
client.dispatcher().executorService().shutdown();
88+
client.connectionPool().evictAll();
89+
}
90+
clientPool.clear();
8291
}
8392

8493
//Properties
@@ -94,14 +103,13 @@ public void setOnvifResponseListener(OnvifResponseListener onvifResponseListener
94103
* @param listener Válasz listener (ByteArray)
95104
*/
96105
void downloadSnapshot(OnvifDevice device, String snapshotUri, int timeoutSeconds, OnvifRequest.Listener<byte[]> listener) {
97-
setCredentials(device.getUsername(), device.getPassword());
98-
99106
Request request = new Request.Builder()
100107
.url(snapshotUri)
101108
.get()
102109
.build();
103110

104-
final Call call = client.newCall(request);
111+
OkHttpClient deviceClient = getClientForDevice(device);
112+
final Call call = deviceClient.newCall(request);
105113
call.timeout().timeout(timeoutSeconds, TimeUnit.SECONDS);
106114

107115
try (Response response = call.execute()) {
@@ -127,7 +135,8 @@ void downloadSnapshot(OnvifDevice device, String snapshotUri, int timeoutSeconds
127135
private <T> void performXmlRequest(OnvifDevice device, OnvifRequest<T> request, Request xmlRequest, int timeoutSeconds) {
128136
if (xmlRequest == null) return;
129137

130-
final Call call = client.newCall(xmlRequest);
138+
OkHttpClient deviceClient = getClientForDevice(device);
139+
final Call call = deviceClient.newCall(xmlRequest);
131140
call.timeout().timeout(timeoutSeconds, TimeUnit.SECONDS);
132141

133142
try (Response xmlResponse = call.execute()) {

src/main/java/be/teletask/onvif/OnvifXMLBuilder.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ public static String getSoapHeader(Credentials cred, String extraHeader) {
3535
byte[] bytes = new byte[20];
3636
new Random().nextBytes(bytes);
3737
nonce = Base64.getEncoder().encodeToString(bytes);
38-
created = ZonedDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
38+
39+
// Use UTC time explicitly to avoid timezone issues
40+
created = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
3941

4042
byte[] createdByteArray = created.getBytes(StandardCharsets.UTF_8);
4143
byte[] passwordByteArray = cred.getPassword().getBytes(StandardCharsets.UTF_8);
@@ -46,6 +48,7 @@ public static String getSoapHeader(Credentials cred, String extraHeader) {
4648

4749
md.update(c);
4850
digest = Base64.getEncoder().encodeToString(md.digest());
51+
4952
} catch (NoSuchAlgorithmException e) {
5053
e.printStackTrace();
5154
}

src/main/java/be/teletask/onvif/parsers/GetEventBrokersParser.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,5 @@ public List<String> parse(OnvifResponse response) {
4747

4848

4949

50+
51+

src/main/java/be/teletask/onvif/requests/AddEventBrokerRequest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,5 @@ public OnvifType getType() {
4949

5050

5151

52+
53+

src/main/java/be/teletask/onvif/requests/DeleteEventBrokerRequest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,5 @@ public OnvifType getType() {
4747

4848

4949

50+
51+

src/main/java/be/teletask/onvif/requests/GetEventBrokerRequest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,5 @@ public OnvifType getType() {
4444

4545

4646

47+
48+

0 commit comments

Comments
 (0)