public boolean authenticate(final Socket toBeAuthenticated, final Set<CancelableTask> relatedHolePunchingTasks,
final CancelableTask ownTask, final Object sharedLock) throws IOException {
boolean result = false;
logger.info("Trying to authenticate socket: {}", toBeAuthenticated); //$NON-NLS-1$
final MessageWriter messageWriter = new MessageWriter(toBeAuthenticated.getOutputStream());
final MessageReader messageReader = this.hpUtil.getCustomHolePunchingMessageReader();
final Message receivedMessage = messageReader.readSTUNMessage(toBeAuthenticated.getInputStream());
if ((receivedMessage.getMessageMethod() == STUNMessageMethod.AUTHENTICATE)
&& receivedMessage.hasAttribute(Token.class)) {
final Token receivedToken = receivedMessage.getAttribute(Token.class);
if (receivedToken.getToken().equals(this.authentikationToken)) {
final Message tokenAckMessage = receivedMessage.buildSuccessResponse();
synchronized (sharedLock) {
messageWriter.writeMessage(tokenAckMessage);
final Message receveidAckMessage = messageReader
.readSTUNMessage(toBeAuthenticated.getInputStream());
if (this.hpUtil.isAuthenticationAcknowledgmentMessage(receveidAckMessage)) {
logger.debug("Authentication successfull, stopping hole punching threads"); //$NON-NLS-1$
this.hpUtil.stopCancableTasksExceptOwnTask(relatedHolePunchingTasks, ownTask);
result = true;