Compare commits

...

2 Commits

58 changed files with 920 additions and 811 deletions

View File

@ -245,7 +245,7 @@ public class StackProperties
String[] parts = str.split(regex); String[] parts = str.split(regex);
// Remove mal-formatted entries. // Remove mal-formatted entries.
List<String> res = new ArrayList<String>(); List<String> res = new ArrayList<>();
for (String s : parts) for (String s : parts)
if (s != null && s.trim().length() != 0) if (s != null && s.trim().length() != 0)
res.add(s); res.add(s);

View File

@ -74,14 +74,14 @@ public abstract class IceControlAttribute
// the attributeValue array // the attributeValue array
// Reading in the network byte order (Big-Endian) // Reading in the network byte order (Big-Endian)
tieBreaker = ((attributeValue[offset++] & 0xffl) << 56) tieBreaker = ((attributeValue[offset++] & 0xffL) << 56)
| ((attributeValue[offset++] & 0xffl) << 48) | ((attributeValue[offset++] & 0xffL) << 48)
| ((attributeValue[offset++] & 0xffl) << 40) | ((attributeValue[offset++] & 0xffL) << 40)
| ((attributeValue[offset++] & 0xffl) << 32) | ((attributeValue[offset++] & 0xffL) << 32)
| ((attributeValue[offset++] & 0xffl) << 24) | ((attributeValue[offset++] & 0xffL) << 24)
| ((attributeValue[offset++] & 0xffl) << 16) | ((attributeValue[offset++] & 0xffL) << 16)
| ((attributeValue[offset++] & 0xffl) << 8) | ((attributeValue[offset++] & 0xffL) << 8)
| (attributeValue[offset++] & 0xffl); | (attributeValue[offset] & 0xffL);
} }
/** /**

View File

@ -144,7 +144,7 @@ public class LifetimeAttribute
throw new StunException("length invalid"); throw new StunException("length invalid");
} }
lifetime = ((attributeValue[offset + 0] << 24) & 0xff000000) + lifetime = ((attributeValue[offset] << 24) & 0xff000000) +
((attributeValue[offset + 1] << 16) & 0x00ff0000) + ((attributeValue[offset + 1] << 16) & 0x00ff0000) +
((attributeValue[offset + 2] << 8) & 0x0000ff00) + ((attributeValue[offset + 2] << 8) & 0x0000ff00) +
(attributeValue[offset + 3] & 0x000000ff); (attributeValue[offset + 3] & 0x000000ff);

View File

@ -131,7 +131,7 @@ public class ReservationTokenAttribute
byte[] copy = new byte[reservationToken.length]; byte[] copy = new byte[reservationToken.length];
System.arraycopy(reservationToken, 0, copy, 0, reservationToken.length); System.arraycopy(reservationToken, 0, copy, 0, reservationToken.length);
return reservationToken; return copy;
} }
/** /**
@ -196,8 +196,8 @@ public class ReservationTokenAttribute
for(int i = 0; i < b; i++) for(int i = 0; i < b; i++)
{ {
token.reservationToken[i] = (byte)((left >> (i * 8)) & 0xFFl); token.reservationToken[i] = (byte)((left >> (i * 8)) & 0xFFL);
token.reservationToken[i + b] = (byte)((right >> (i * 8)) & 0xFFl); token.reservationToken[i + b] = (byte)((right >> (i * 8)) & 0xFFL);
} }
//calculate hashcode for Hashtable storage. //calculate hashcode for Hashtable storage.

View File

@ -121,7 +121,7 @@ public class SoftwareAttribute
byte[] copy = new byte[software.length]; byte[] copy = new byte[software.length];
System.arraycopy(software, 0, copy, 0, software.length); System.arraycopy(software, 0, copy, 0, software.length);
return software; return copy;
} }
/** /**

View File

@ -52,7 +52,7 @@ public class UnknownAttributesAttribute extends Attribute
/** /**
* A list of attribute types that were not understood by the server. * A list of attribute types that were not understood by the server.
*/ */
private ArrayList<Character> unknownAttributes = new ArrayList<Character>(); private ArrayList<Character> unknownAttributes = new ArrayList<>();
/** /**
* Constructor. * Constructor.
@ -100,7 +100,7 @@ public class UnknownAttributesAttribute extends Attribute
//some attributes may be repeated for padding //some attributes may be repeated for padding
//(packet length should be divisable by 4) //(packet length should be divisable by 4)
if(!contains(attributeID)) if(!contains(attributeID))
unknownAttributes.add(new Character(attributeID)); unknownAttributes.add(attributeID);
} }
/** /**
@ -110,7 +110,7 @@ public class UnknownAttributesAttribute extends Attribute
*/ */
public boolean contains(char attributeID) public boolean contains(char attributeID)
{ {
return unknownAttributes.contains(new Character(attributeID)); return unknownAttributes.contains(attributeID);
} }
/** /**
@ -140,7 +140,7 @@ public class UnknownAttributesAttribute extends Attribute
*/ */
public char getAttribute(int index ) public char getAttribute(int index )
{ {
return (unknownAttributes.get(index)).charValue(); return unknownAttributes.get(index);
} }
/** /**
@ -164,7 +164,7 @@ public class UnknownAttributesAttribute extends Attribute
Iterator<Character> attributes = getAttributes(); Iterator<Character> attributes = getAttributes();
while (attributes.hasNext()) while (attributes.hasNext())
{ {
char att = attributes.next().charValue(); char att = attributes.next();
binValue[offset++] = (byte)(att >> 8); binValue[offset++] = (byte)(att >> 8);
binValue[offset++] = (byte)(att & 0x00FF); binValue[offset++] = (byte)(att & 0x00FF);
} }

View File

@ -19,15 +19,11 @@ package org.ice4j.ice;
import java.beans.*; import java.beans.*;
import java.io.*; import java.io.*;
import java.math.*;
import java.net.*;
import java.security.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.harvest.*; import org.ice4j.ice.harvest.*;
import org.ice4j.ice.harvest.TrickleCallback;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -52,6 +48,7 @@ import org.ice4j.stack.*;
* @author Boris Grozev * @author Boris Grozev
*/ */
public class Agent public class Agent
extends BaseAgent
{ {
/** /**
* The maximum number of retransmissions of a STUN Binding request without * The maximum number of retransmissions of a STUN Binding request without
@ -103,28 +100,6 @@ public class Agent
public static final String PROPERTY_ICE_PROCESSING_STATE public static final String PROPERTY_ICE_PROCESSING_STATE
= "IceProcessingState"; = "IceProcessingState";
/**
* The LinkedHashMap used to store the media streams
* This map preserves the insertion order of the media streams.
*/
private final Map<String, IceMediaStream> mediaStreams
= new LinkedHashMap<String, IceMediaStream>();
/**
* The candidate harvester that we use to gather candidate on the local
* machine.
*/
private final HostCandidateHarvester hostCandidateHarvester
= new HostCandidateHarvester();
/**
* A list of additional <tt>CandidateHarvester</tt>s which will be used to
* harvest candidates synchronously, and previously to harvesting by
* {@link #harvesters}.
*/
private final List<CandidateHarvester> hostHarvesters
= new LinkedList<CandidateHarvester>();
/** /**
* The set of harvesters (i.e. STUN, TURN, and others) that the agent should * The set of harvesters (i.e. STUN, TURN, and others) that the agent should
* use when gathering candidates for components. * use when gathering candidates for components.
@ -137,14 +112,6 @@ public class Agent
*/ */
// private final HarvestStatistics harvestStats = new HarvestStatistics(); // private final HarvestStatistics harvestStats = new HarvestStatistics();
/**
* We use the <tt>FoundationsRegistry</tt> to keep track of the foundations
* we assign within a session (i.e. the entire life time of an
* <tt>Agent</tt>)
*/
private final FoundationsRegistry foundationsRegistry
= new FoundationsRegistry();
/** /**
* Our internal nominator implementing several nomination strategies. * Our internal nominator implementing several nomination strategies.
*/ */
@ -166,23 +133,13 @@ public class Agent
* the necessary triggered checks. * the necessary triggered checks.
*/ */
private final List<CandidatePair> preDiscoveredPairsQueue private final List<CandidatePair> preDiscoveredPairsQueue
= new LinkedList<CandidatePair>(); = new LinkedList<>();
/** /**
* The lock that we use while starting connectivity establishment. * The lock that we use while starting connectivity establishment.
*/ */
private final Object startLock = new Object(); private final Object startLock = new Object();
/**
* The user fragment that we should use for the ice-ufrag attribute.
*/
private final String ufrag;
/**
* The password that we should use for the ice-pwd attribute.
*/
private final String password;
/** /**
* The tie-breaker number is used in connectivity checks to detect and * The tie-breaker number is used in connectivity checks to detect and
* repair the case where both agents believe to have the controlling or the * repair the case where both agents believe to have the controlling or the
@ -190,21 +147,11 @@ public class Agent
*/ */
private long tieBreaker; private long tieBreaker;
/**
* Determines whether this is the controlling agent in a an ICE interaction.
*/
private boolean isControlling = true;
/** /**
* The entity that will be taking care of outgoing connectivity checks. * The entity that will be taking care of outgoing connectivity checks.
*/ */
private final ConnectivityCheckClient connCheckClient; private final ConnectivityCheckClient connCheckClient;
/**
* The entity that will be taking care of incoming connectivity checks.
*/
private final ConnectivityCheckServer connCheckServer;
/** /**
* Indicates the state of ICE processing in this <tt>Agent</tt>. An * Indicates the state of ICE processing in this <tt>Agent</tt>. An
* <tt>Agent</tt> is in the Waiting state until it has both sent and * <tt>Agent</tt> is in the Waiting state until it has both sent and
@ -228,13 +175,7 @@ public class Agent
* Agent} and following its changes of state. * Agent} and following its changes of state.
*/ */
private final List<PropertyChangeListener> stateListeners private final List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>(); = new LinkedList<>();
/**
* The <tt>StunStack</tt> used by this <tt>Agent</tt>.
*/
private StunStack stunStack;
/** /**
* The thread that we use for moving from COMPLETED into a TERMINATED state. * The thread that we use for moving from COMPLETED into a TERMINATED state.
*/ */
@ -283,42 +224,20 @@ public class Agent
*/ */
private boolean performConsentFreshness = false; private boolean performConsentFreshness = false;
/**
* The flag which specifies whether {@link #hostCandidateHarvester} should
* be used or not.
*/
private Boolean useHostHarvester = null;
/** /**
* Creates an empty <tt>Agent</tt> with no streams, and no address. * Creates an empty <tt>Agent</tt> with no streams, and no address.
*/ */
public Agent() public Agent()
{ {
SecureRandom random = new SecureRandom();
connCheckServer = new ConnectivityCheckServer(this);
connCheckClient = new ConnectivityCheckClient(this); connCheckClient = new ConnectivityCheckClient(this);
//add the FINGERPRINT attribute to all messages.
System.setProperty(StackProperties.ALWAYS_SIGN, "true");
//add the software attribute to all messages
if (StackProperties.getString(StackProperties.SOFTWARE) == null)
System.setProperty(StackProperties.SOFTWARE, "ice4j.org");
ufrag
= ensureIceAttributeLength(
new BigInteger(24, random).toString(32)
+ BigInteger.valueOf(
System.currentTimeMillis()).toString(32),
/* min */ 4, /* max */ 256);
password
= ensureIceAttributeLength(
new BigInteger(128, random).toString(32),
/* min */ 22, /* max */ 256);
tieBreaker = Math.abs(random.nextLong()); tieBreaker = Math.abs(random.nextLong());
nominator = new DefaultNominator(this); nominator = new DefaultNominator(this);
// The default value of controlling was true before the class BaseAgent
// was split out of the class Agent. BaseAgent defaults to false for
// controlling since it is unable to perform connectivity checks.
setControlling(true);
} }
/** /**
@ -335,95 +254,27 @@ public class Agent
* Creates a new media stream and stores it. * Creates a new media stream and stores it.
* *
* @param mediaStreamName the name of the media stream * @param mediaStreamName the name of the media stream
*
* @return the newly created and stored <tt>IceMediaStream</tt> * @return the newly created and stored <tt>IceMediaStream</tt>
*/ */
@Override
public IceMediaStream createMediaStream(String mediaStreamName) public IceMediaStream createMediaStream(String mediaStreamName)
{ {
logger.fine("Create media stream for " + mediaStreamName); IceMediaStream mediaStream = super.createMediaStream(mediaStreamName);
IceMediaStream mediaStream
= new IceMediaStream(Agent.this, mediaStreamName);
mediaStreams.put(mediaStreamName, mediaStream); if (mediaStream != null)
{
// Since we add a new stream, we must wait to add the component and the // Since we add a new stream, we must wait to add the component and
// remote candidates before starting to "RUN" this Agent. // the remote candidates before starting to "RUN" this Agent.
// This is useful if this Agent is already in COMPLETED state // This is useful if this Agent is already in COMPLETED state
// (isStarted() == true) due to a previous successful ICE procedure: // (isStarted() == true) due to a previous successful ICE procedure:
// this way incoming connectivity checks are registered in the // this way incoming connectivity checks are registered in the
// preDiscoveredPairsQueue until this Agent is in RUNNING state. // preDiscoveredPairsQueue until this Agent is in RUNNING state.
this.setState(IceProcessingState.WAITING); setState(IceProcessingState.WAITING);
}
return mediaStream; return mediaStream;
} }
/**
* Creates a new {@link Component} for the specified <tt>stream</tt> and
* allocates potentially all local candidates that should belong to it.
*
* @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to.
* @param transport the transport protocol used by the component
* @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwing an exception.
*
* @return the newly created {@link Component} and with a list containing
* all and only local candidates.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
* maxPort</tt>, or if <tt>transport</tt> is not currently supported.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
* @throws BindException if we couldn't find a free port between
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries.
*/
public Component createComponent( IceMediaStream stream,
Transport transport,
int preferredPort,
int minPort,
int maxPort)
throws IllegalArgumentException,
IOException,
BindException
{
if(transport != Transport.UDP)
{
throw new IllegalArgumentException(
"This implementation does not currently support transport: "
+ transport);
}
Component component = stream.createComponent();
gatherCandidates(component, preferredPort, minPort, maxPort);
for(Candidate<?> candidate : component.getLocalCandidates())
{
logger.info("\t" + candidate.getTransportAddress() + " (" +
candidate.getType() + ")");
}
/*
* Lyubomir: After we've gathered the LocalCandidate for a Component and
* before we've made them available to the caller, we have to make sure
* that the ConnectivityCheckServer is started. If there's been a
* previous connectivity establishment which has completed, it has
* stopped the ConnectivityCheckServer. If the ConnectivityCheckServer is
* not started after we've made the gathered LocalCandidates available
* to the caller, the caller may send them and a connectivity check may
* arrive from the remote Agent.
*/
connCheckServer.start();
return component;
}
/** /**
* Uses all <tt>CandidateHarvester</tt>s currently registered with this * Uses all <tt>CandidateHarvester</tt>s currently registered with this
* <tt>Agent</tt> to obtain whatever addresses they can discover. * <tt>Agent</tt> to obtain whatever addresses they can discover.
@ -447,56 +298,21 @@ public class Agent
* @throws IOException if an error occurs while the underlying resolver lib * @throws IOException if an error occurs while the underlying resolver lib
* is gathering candidates and we end up without even a single one. * is gathering candidates and we end up without even a single one.
*/ */
private void gatherCandidates( Component component, @Override
int preferredPort, protected void gatherCandidates(
int minPort, Component component,
int maxPort) int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException, throws IllegalArgumentException,
IOException IOException
{ {
logger.info("Gather candidates for component " + super.gatherCandidates(component, preferredPort, minPort, maxPort);
component.toShortString());
if (useHostHarvester()) // in case we are not trickling, apply other harvesters here
if (!isTrickling())
{ {
hostCandidateHarvester.harvest( harvestingStarted = true; // raise a flag to warn on a second call.
component,
preferredPort, minPort, maxPort, Transport.UDP);
}
else
{
if (hostHarvesters.isEmpty())
logger.warning("No host harvesters available!");
}
for (CandidateHarvester harvester : hostHarvesters)
{
harvester.harvest(component);
}
if (component.getLocalCandidateCount() == 0)
logger.warning("Failed to gather any host candidates!");
//in case we are not trickling, apply other harvesters here
if(!isTrickling())
{
harvestingStarted = true; //raise a flag to warn on a second call.
harvesters.harvest(component); harvesters.harvest(component);
} }
logger.fine("Candidate count in first harvest: " +
component.getLocalCandidateCount());
// Emil: Because of trickle, we now assign foundations, compute
// priorities, and eliminate redundancies while adding candidates on a
// component. This means that we no longer need to do it here, where we
// did before.
//computeFoundations(component);
//component.prioritizeCandidates();
//component.eliminateRedundantCandidates();
//select the candidate to put in the media line.
component.selectDefaultCandidate();
} }
/** /**
@ -525,7 +341,7 @@ public class Agent
} }
//create a list of components and start harvesting //create a list of components and start harvesting
List<Component> components = new LinkedList<Component>(); List<Component> components = new LinkedList<>();
for (IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{ {
@ -571,14 +387,12 @@ public class Agent
"Trigger checks for pairs that were received before " "Trigger checks for pairs that were received before "
+ "running state"); + "running state");
Iterator<CandidatePair> it = preDiscoveredPairsQueue.iterator(); for (CandidatePair cp : preDiscoveredPairsQueue)
while(it.hasNext())
{ {
triggerCheck(it.next()); triggerCheck(cp);
} }
this.preDiscoveredPairsQueue.clear(); preDiscoveredPairsQueue.clear();
} }
connCheckClient.startChecks(); connCheckClient.startChecks();
@ -748,7 +562,11 @@ public class Agent
*/ */
private boolean setState(IceProcessingState newState) private boolean setState(IceProcessingState newState)
{ {
if (newState == null)
throw new NullPointerException("newState");
IceProcessingState oldState; IceProcessingState oldState;
synchronized (stateSyncRoot) synchronized (stateSyncRoot)
{ {
oldState = state; oldState = state;
@ -757,8 +575,8 @@ public class Agent
if (!oldState.equals(newState)) if (!oldState.equals(newState))
{ {
logger.info("ICE state changed from " + oldState + " to " logger.info(
+ newState); "ICE state changed from " + oldState + " to " + newState);
fireStateChange(oldState, newState); fireStateChange(oldState, newState);
return true; return true;
@ -823,7 +641,7 @@ public class Agent
public void addCandidateHarvester(CandidateHarvester harvester) public void addCandidateHarvester(CandidateHarvester harvester)
{ {
if (harvester.isHostHarvester()) if (harvester.isHostHarvester())
hostHarvesters.add(harvester); addHostHarvester(harvester);
else else
harvesters.add(harvester); harvesters.add(harvester);
} }
@ -838,30 +656,6 @@ public class Agent
return harvesters; return harvesters;
} }
/**
* Returns that user name that should be advertised in session descriptions
* containing ICE data from this agent.
*
* @return that user name that should be advertised in session descriptions
* containing ICE data from this agent.
*/
public String getLocalUfrag()
{
return ufrag;
}
/**
* Returns that password that should be advertised in session descriptions
* containing ICE data from this agent.
*
* @return that password that should be advertised in session descriptions
* containing ICE data from this agent.
*/
public String getLocalPassword()
{
return password;
}
/** /**
* Returns the user name that this <tt>Agent</tt> should use in connectivity * Returns the user name that this <tt>Agent</tt> should use in connectivity
* checks for outgoing Binding Requests. According to RFC 5245, a Binding * checks for outgoing Binding Requests. According to RFC 5245, a Binding
@ -1000,83 +794,6 @@ public class Agent
return null; return null;
} }
/**
* Returns the {@link FoundationsRegistry} this agent is using to assign
* candidate foundations. We use the <tt>FoundationsRegistry</tt> to keep
* track of the foundations we assign within a session (i.e. the entire life
* time of an <tt>Agent</tt>)
*/
public final FoundationsRegistry getFoundationsRegistry()
{
return foundationsRegistry;
}
/**
* Returns the <tt>IceMediaStream</tt> with the specified <tt>name</tt> or
* <tt>null</tt> if no such stream has been registered with this
* <tt>Agent</tt> yet.
*
* @param name the name of the stream that we'd like to obtain a reference
* to.
*
* @return the <tt>IceMediaStream</tt> with the specified <tt>name</tt> or
* <tt>null</tt> if no such stream has been registered with this
* <tt>Agent</tt> yet.
*/
public IceMediaStream getStream(String name)
{
synchronized(mediaStreams)
{
return mediaStreams.get(name);
}
}
/**
* Returns a <tt>List</tt> containing the names of all currently registered
* media streams.
*
* @return a <tt>List</tt> containing the names of all currently registered
* media streams.
*/
public List<String> getStreamNames()
{
synchronized(mediaStreams)
{
return new LinkedList<String>(mediaStreams.keySet());
}
}
/**
* Returns a <tt>List</tt> containing all <tt>IceMediaStream</tt>s currently
* registered with this agent.
*
* @return a <tt>List</tt> containing all <tt>IceMediaStream</tt>s currently
* registered with this agent.
*/
public List<IceMediaStream> getStreams()
{
synchronized(mediaStreams)
{
return new LinkedList<IceMediaStream>(mediaStreams.values());
}
}
/**
* Returns the number of <tt>IceMediaStream</tt>s currently registered with
* this agent.
*
* @return the number of <tt>IceMediaStream</tt>s currently registered with
* this agent.
*
*/
public int getStreamCount()
{
synchronized(mediaStreams)
{
return mediaStreams.size();
}
}
/** /**
* Gets the <tt>IceMediaStream</tt>s registered with this <tt>Agent</tt> for * Gets the <tt>IceMediaStream</tt>s registered with this <tt>Agent</tt> for
* which connectivity establishment is pending. For example, after a set of * which connectivity establishment is pending. For example, after a set of
@ -1114,29 +831,6 @@ public class Agent
return streams; return streams;
} }
/**
* Gets the <tt>StunStack</tt> used by this <tt>Agent</tt>.
*
* @return the <tt>StunStack</tt> used by this <tt>Agent</tt>
*/
public synchronized StunStack getStunStack()
{
if (stunStack == null)
stunStack = new StunStack();
return stunStack;
}
/**
* Sets the <tt>StunStack</tt> used by this <tt>Agent</tt>.
*
* @param stunStack the stunStack to be used by this Agent.
*
*/
public void setStunStack(StunStack stunStack)
{
this.stunStack = stunStack;
}
/** /**
* Returns the number of {@link CheckList}s that are currently active. * Returns the number of {@link CheckList}s that are currently active.
* *
@ -1195,14 +889,12 @@ public class Agent
} }
/** /**
* Specifies whether this agent has the controlling role in an ICE exchange. * {@inheritDoc}
*
* @param isControlling <tt>true</tt> if this is to be the controlling
* <tt>Agent</tt> and <tt>false</tt> otherwise.
*/ */
public void setControlling(boolean isControlling) @Override
public void setControlling(boolean controlling)
{ {
this.isControlling = isControlling; super.setControlling(controlling);
//in case we have already initialized our check lists we'd need to //in case we have already initialized our check lists we'd need to
//recompute pair priorities. //recompute pair priorities.
@ -1215,96 +907,6 @@ public class Agent
} }
} }
/**
* Removes <tt>stream</tt> and all its child <tt>Component</tt>s and
* <tt>Candidate</tt>s from the this agent and releases all resources that
* they had allocated (like sockets for example)
*
* @param stream the <tt>Component</tt> we'd like to remove and free.
*/
public void removeStream(IceMediaStream stream)
{
synchronized (mediaStreams)
{
mediaStreams.remove(stream.getName());
}
/*
* XXX The invocation of IceMediaStream#free() on stream has been moved
* out of the synchronized block in order to reduce the chances of a
* deadlock. There was no obvious reason why it should stay in the
* synchronized block at the time of the modification.
*/
stream.free();
}
/**
* Determines whether this agent has the controlling role in an ICE
* exchange.
*
* @return <tt>true</tt> if this is to be the controlling <tt>Agent</tt>
* and <tt>false</tt> otherwise.
*/
public boolean isControlling()
{
return isControlling;
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't.
*
* @param localAddress the {@link TransportAddress} we are looking for.
*
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't.
*/
public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{
for(IceMediaStream stream : mediaStreams.values())
{
LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if(cnd != null)
return cnd;
}
return null;
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't.
*
* @param localAddress the {@link TransportAddress} we are looking for.
* @param ufrag local ufrag
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't.
*/
public LocalCandidate findLocalCandidate(
TransportAddress localAddress,
String ufrag)
{
for(IceMediaStream stream : mediaStreams.values())
{
for(Component c : stream.getComponents())
{
for(LocalCandidate cnd : c.getLocalCandidates())
{
if(cnd != null
&& cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag))
{
return cnd;
}
}
}
}
return null;
}
/** /**
* Returns the remote <tt>Candidate</tt> with the specified * Returns the remote <tt>Candidate</tt> with the specified
* <tt>remoteAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>remoteAddress</tt> if it belongs to any of this {@link Agent}'s
@ -1437,22 +1039,25 @@ public class Agent
Component parentComponent = localCandidate.getParentComponent(); Component parentComponent = localCandidate.getParentComponent();
RemoteCandidate remoteCandidate = null; RemoteCandidate remoteCandidate = null;
remoteCandidate = new RemoteCandidate( remoteCandidate
remoteAddress, = new RemoteCandidate(
parentComponent, remoteAddress,
CandidateType.PEER_REFLEXIVE_CANDIDATE, parentComponent,
foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(), CandidateType.PEER_REFLEXIVE_CANDIDATE,
priority, getFoundationsRegistry()
// We can not know the related candidate of a remote peer .obtainFoundationForPeerReflexiveCandidate(),
// reflexive candidate. We must set it to "null". priority,
null, // We can not know the related candidate of a remote peer
ufrag); // reflexive candidate. We must set it to "null".
null,
ufrag);
CandidatePair triggeredPair CandidatePair triggeredPair
= new CandidatePair(localCandidate, remoteCandidate); = new CandidatePair(localCandidate, remoteCandidate);
logger.fine("set use-candidate " + useCandidate + " for pair " + logger.fine(
triggeredPair.toShortString()); "set use-candidate " + useCandidate + " for pair "
+ triggeredPair.toShortString());
if(useCandidate) if(useCandidate)
{ {
triggeredPair.setUseCandidateReceived(); triggeredPair.setUseCandidateReceived();
@ -1466,8 +1071,10 @@ public class Agent
//so it's now safe to go and see whether this is a new PR cand. //so it's now safe to go and see whether this is a new PR cand.
if(triggeredPair.getParentComponent().getSelectedPair() == null) if(triggeredPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Received check from " + logger.info(
triggeredPair.toShortString() + " triggered a check"); "Received check from "
+ triggeredPair.toShortString()
+ " triggered a check");
} }
triggerCheck(triggeredPair); triggerCheck(triggeredPair);
} }
@ -1824,26 +1431,6 @@ public class Agent
} }
} }
/**
* Returns the number of host {@link Candidate}s in this {@link Agent}.
*
* @return the number of host {@link Candidate}s in this {@link Agent}.
*/
protected int countHostCandidates()
{
int num = 0;
synchronized (mediaStreams)
{
Collection<IceMediaStream> streamsCol = mediaStreams.values();
for( IceMediaStream stream : streamsCol)
num += stream.countHostCandidates();
}
return num;
}
/** /**
* Lets the application specify a custom value for the <tt>Ta</tt> timer * Lets the application specify a custom value for the <tt>Ta</tt> timer
* so that we don't calculate one. * so that we don't calculate one.
@ -2080,57 +1667,6 @@ public class Agent
setState(terminationState); setState(terminationState);
} }
/**
* Adds or removes ICE characters (i.e. ALPHA, DIGIT, +, or /) to or from a
* specific <tt>String</tt> in order to produce a <tt>String</tt> with a
* length within a specific range.
*
* @param s the <tt>String</tt> to add or remove characters to or from in
* case its length is less than <tt>min</tt> or greater than <tt>max</tt>
* @param min the minimum length in (ICE) characters of the returned
* <tt>String</tt>
* @param max the maximum length in (ICE) characters of the returned
* <tt>String</tt>
* @return <tt>s</tt> if its length is greater than or equal to
* <tt>min</tt> and less than or equal to <tt>max</tt>; a new
* <tt>String</tt> which is equal to <tt>s</tt> with prepended ICE
* characters if the length of <tt>s</tt> is less than <tt>min</tt>; a new
* <tt>String</tt> which is composed of the first <tt>max</tt> characters of
* <tt>s</tt> if the length of <tt>s</tt> is greater than <tt>max</tt>
* @throws IllegalArgumentException if <tt>min</tt> is negative or
* <tt>max</tt> is less than <tt>min</tt>
* @throws NullPointerException if <tt>s</tt> is equal to <tt>null</tt>
*/
private String ensureIceAttributeLength(String s, int min, int max)
{
if (s == null)
throw new NullPointerException("s");
if (min < 0)
throw new IllegalArgumentException("min " + min);
if (max < min)
throw new IllegalArgumentException("max " + max);
int length = s.length();
int numberOfIceCharsToAdd = min - length;
if (numberOfIceCharsToAdd > 0)
{
StringBuilder sb = new StringBuilder(min);
for (; numberOfIceCharsToAdd > 0; --numberOfIceCharsToAdd)
{
sb.append('0');
}
sb.append(s);
s = sb.toString();
}
else if (max < length)
{
s = s.substring(0, max);
}
return s;
}
/** /**
* Called by the garbage collector when garbage collection determines that * Called by the garbage collector when garbage collection determines that
* there are no more references to this instance. Calls {@link #free()} on * there are no more references to this instance. Calls {@link #free()} on
@ -2379,7 +1915,6 @@ public class Agent
this.trickle = trickle; this.trickle = trickle;
} }
/** /**
* Returns the harvesting time (in ms) for the harvester given in parameter. * Returns the harvesting time (in ms) for the harvester given in parameter.
* *
@ -2405,7 +1940,6 @@ public class Agent
} }
} }
} }
return 0; return 0;
} }
@ -2437,7 +1971,6 @@ public class Agent
} }
} }
} }
return 0; return 0;
} }
@ -2455,7 +1988,6 @@ public class Agent
harvestDuration harvestDuration
+= harvester.getHarvestStatistics().getHarvestDuration(); += harvester.getHarvestStatistics().getHarvestDuration();
} }
return harvestDuration; return harvestDuration;
} }
@ -2475,7 +2007,6 @@ public class Agent
{ {
harvestCount += harvester.getHarvestStatistics().getHarvestCount(); harvestCount += harvester.getHarvestStatistics().getHarvestCount();
} }
return harvestCount; return harvestCount;
} }
@ -2502,32 +2033,4 @@ public class Agent
{ {
this.performConsentFreshness = performConsentFreshness; this.performConsentFreshness = performConsentFreshness;
} }
/**
* Checks whether the dynamic host harvester should be used or not.
* @return <tt>true</tt> if the dynamic host harvester should be used and
* <tt>false</tt> otherwise.
*/
public boolean useHostHarvester()
{
if (useHostHarvester == null)
{
useHostHarvester
= StackProperties.getBoolean(
StackProperties.USE_DYNAMIC_HOST_HARVESTER,
true);
}
return useHostHarvester;
}
/**
* Sets the flag which indicates whether the dynamic host harvester will
* be used or not by this <tt>Agent</tt>.
* @param useHostHarvester the value to set.
*/
public void setUseHostHarvester(boolean useHostHarvester)
{
this.useHostHarvester = useHostHarvester;
}
} }

View File

@ -0,0 +1,655 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.ice;
import java.io.*;
import java.math.*;
import java.net.*;
import java.security.*;
import java.util.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.stack.*;
/**
* Implements a (common) base of full and lite ICE agents (within the ice4j
* library).
*
* @author Lyubomir Marinov
*/
public class BaseAgent
{
/**
* The <tt>Logger</tt> used by the <tt>BaseAgent</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(BaseAgent.class.getName());
/**
* Adds or removes ICE characters (i.e. ALPHA, DIGIT, +, or /) to or from a
* specific <tt>String</tt> in order to produce a <tt>String</tt> with a
* length within a specific range.
*
* @param s the <tt>String</tt> to add or remove characters to or from in
* case its length is less than <tt>min</tt> or greater than <tt>max</tt>
* @param min the minimum length in (ICE) characters of the returned
* <tt>String</tt>
* @param max the maximum length in (ICE) characters of the returned
* <tt>String</tt>
* @return <tt>s</tt> if its length is greater than or equal to
* <tt>min</tt> and less than or equal to <tt>max</tt>; a new
* <tt>String</tt> which is equal to <tt>s</tt> with prepended ICE
* characters if the length of <tt>s</tt> is less than <tt>min</tt>; a new
* <tt>String</tt> which is composed of the first <tt>max</tt> characters of
* <tt>s</tt> if the length of <tt>s</tt> is greater than <tt>max</tt>
* @throws IllegalArgumentException if <tt>min</tt> is negative or
* <tt>max</tt> is less than <tt>min</tt>
* @throws NullPointerException if <tt>s</tt> is equal to <tt>null</tt>
*/
private static String ensureIceAttributeLength(String s, int min, int max)
{
if (s == null)
throw new NullPointerException("s");
if (min < 0)
throw new IllegalArgumentException("min " + min);
if (max < min)
throw new IllegalArgumentException("max " + max);
int length = s.length();
int numberOfIceCharsToAdd = min - length;
if (numberOfIceCharsToAdd > 0)
{
StringBuilder sb = new StringBuilder(min);
for (; numberOfIceCharsToAdd > 0; --numberOfIceCharsToAdd)
{
sb.append('0');
}
sb.append(s);
s = sb.toString();
}
else if (max < length)
{
s = s.substring(0, max);
}
return s;
}
/**
* The entity that will be taking care of incoming connectivity checks.
*/
private final ConnectivityCheckServer connCheckServer;
/**
* Determines whether this is the controlling agent in a an ICE interaction.
* The default value of {@code BaseAgent} is {@code false} since it is
* unable to perform connectivity checks.
*/
private boolean controlling = false;
/**
* We use the <tt>FoundationsRegistry</tt> to keep track of the foundations
* we assign within a session (i.e. the entire life time of a
* <tt>BaseAgent</tt>.)
*/
private final FoundationsRegistry foundationsRegistry
= new FoundationsRegistry();
/**
* The candidate harvester that we use to gather candidate on the local
* machine.
*/
private final HostCandidateHarvester hostHarvester
= new HostCandidateHarvester();
/**
* A list of additional <tt>CandidateHarvester</tt>s which will be used to
* harvest candidates synchronously, and previously to harvesting by
* non-host <tt>CandidateHarvester</tt>s (if implemented by extenders).
*/
private final List<CandidateHarvester> hostHarvesters = new LinkedList<>();
/**
* The <tt>LinkedHashMap</tt> used to store the <tt>IceMediaStream</tt>s.
* Preserves the insertion order.
*/
private final Map<String, IceMediaStream> mediaStreams
= new LinkedHashMap<>();
/**
* The password that we should use for the ice-pwd attribute.
*/
private final String password;
protected final SecureRandom random = new SecureRandom();
/**
* The <tt>StunStack</tt> used by this <tt>BaseAgent</tt>.
*/
private StunStack stunStack;
/**
* The user fragment that we should use for the ice-ufrag attribute.
*/
private final String ufrag;
/**
* The flag which specifies whether {@link #hostHarvester} is (to be) used.
*/
private Boolean useHostHarvester;
/**
* Creates an empty <tt>BaseAgent</tt> with no streams, and no address.
*/
public BaseAgent()
{
connCheckServer = new ConnectivityCheckServer(this);
//add the FINGERPRINT attribute to all messages.
System.setProperty(StackProperties.ALWAYS_SIGN, "true");
//add the software attribute to all messages
if (StackProperties.getString(StackProperties.SOFTWARE) == null)
System.setProperty(StackProperties.SOFTWARE, "ice4j.org");
ufrag
= ensureIceAttributeLength(
new BigInteger(24, random).toString(32)
+ BigInteger
.valueOf(System.currentTimeMillis())
.toString(32),
/* min */ 4, /* max */ 256);
password
= ensureIceAttributeLength(
new BigInteger(128, random).toString(32),
/* min */ 22, /* max */ 256);
}
/**
* Adds <tt>harvester</tt> to the list of host harvesters that this agent
* will use when gathering <tt>Candidate</tt>s.
*
* @param harvester a <tt>CandidateHarvester</tt> that this agent should use
* when gathering candidates.
*/
protected void addHostHarvester(CandidateHarvester harvester)
{
if (harvester.isHostHarvester())
hostHarvesters.add(harvester);
else
throw new IllegalArgumentException("harvester.isHostHarvester");
}
/**
* Returns the number of host {@link Candidate}s in this {@code BaseAgent}.
*
* @return the number of host {@link Candidate}s in this {@code BaseAgent}.
*/
protected int countHostCandidates()
{
int num = 0;
synchronized (mediaStreams)
{
Collection<IceMediaStream> streamsCol = mediaStreams.values();
for( IceMediaStream stream : streamsCol)
num += stream.countHostCandidates();
}
return num;
}
/**
* Creates a new {@link Component} for the specified <tt>stream</tt> and
* allocates potentially all local candidates that should belong to it.
*
* @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to.
* @param transport the transport protocol used by the component
* @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwing an exception.
*
* @return the newly created {@link Component} and with a list containing
* all and only local candidates.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
* maxPort</tt>, or if <tt>transport</tt> is not currently supported.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
* @throws BindException if we couldn't find a free port between
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries.
*/
public Component createComponent(
IceMediaStream stream,
Transport transport,
int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException,
IOException,
BindException
{
if(transport != Transport.UDP)
{
throw new IllegalArgumentException(
"This implementation does not currently support transport: "
+ transport);
}
Component component = stream.createComponent();
gatherCandidatesAndSelectDefaultCandidate(
component,
preferredPort, minPort, maxPort);
for(Candidate<?> candidate : component.getLocalCandidates())
{
logger.info(
"\t" + candidate.getTransportAddress() + " ("
+ candidate.getType() + ")");
}
/*
* Lyubomir: After we've gathered the LocalCandidate for a Component and
* before we've made them available to the caller, we have to make sure
* that the ConnectivityCheckServer is started. If there's been a
* previous connectivity establishment which has completed, it has
* stopped the ConnectivityCheckServer. If the ConnectivityCheckServer is
* not started after we've made the gathered LocalCandidates available
* to the caller, the caller may send them and a connectivity check may
* arrive from the remote Agent.
*/
connCheckServer.start();
return component;
}
/**
* Creates a new media stream and stores it.
*
* @param mediaStreamName the name of the media stream
* @return the newly created and stored <tt>IceMediaStream</tt>
*/
public IceMediaStream createMediaStream(String mediaStreamName)
{
logger.fine("Create media stream for " + mediaStreamName);
IceMediaStream mediaStream = new IceMediaStream(this, mediaStreamName);
mediaStreams.put(mediaStreamName, mediaStream);
return mediaStream;
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@code BaseAgent}'s
* streams or <tt>null</tt> if it doesn't.
*
* @param localAddress the {@link TransportAddress} we are looking for.
*
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@code BaseAgent}'s
* streams or <tt>null</tt> if it doesn't.
*/
public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{
for(IceMediaStream stream : mediaStreams.values())
{
LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if(cnd != null)
return cnd;
}
return null;
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@code BaseAgent}'s
* streams or <tt>null</tt> if it doesn't.
*
* @param localAddress the {@link TransportAddress} we are looking for.
* @param ufrag local ufrag
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@code BaseAgent}'s
* streams or <tt>null</tt> if it doesn't.
*/
public LocalCandidate findLocalCandidate(
TransportAddress localAddress,
String ufrag)
{
for(IceMediaStream stream : mediaStreams.values())
{
for(Component c : stream.getComponents())
{
for(LocalCandidate cnd : c.getLocalCandidates())
{
if(cnd != null
&& cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag))
{
return cnd;
}
}
}
}
return null;
}
/**
* Uses all <tt>CandidateHarvester</tt>s currently registered with this
* <tt>Agent</tt> to obtain whatever addresses they can discover.
* <p>
* Not that the method would only use existing harvesters so make sure
* you've registered all harvesters that you would want to use before
* calling it.
* </p>
* @param component the <tt>Component</tt> that we'd like to gather
* candidates for.
* @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwing an exception.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort &gt;
* maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver lib
* is gathering candidates and we end up without even a single one.
*/
protected void gatherCandidates(
Component component,
int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException,
IOException
{
logger.info(
"Gather candidates for component " + component.toShortString());
if (useHostHarvester())
{
hostHarvester.harvest(
component,
preferredPort, minPort, maxPort,
Transport.UDP);
}
else if (hostHarvesters.isEmpty())
{
logger.warning("No host harvesters available!");
}
for (CandidateHarvester harvester : hostHarvesters)
{
harvester.harvest(component);
}
if (component.getLocalCandidateCount() == 0)
logger.warning("Failed to gather any host candidates!");
}
/**
* Uses all <tt>CandidateHarvester</tt>s currently registered with this
* <tt>Agent</tt> to obtain whatever addresses they can discover.
* <p>
* Not that the method would only use existing harvesters so make sure
* you've registered all harvesters that you would want to use before
* calling it.
* </p>
* @param component the <tt>Component</tt> that we'd like to gather
* candidates for.
* @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwing an exception.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort &gt;
* maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver lib
* is gathering candidates and we end up without even a single one.
*/
private void gatherCandidatesAndSelectDefaultCandidate(
Component component,
int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException,
IOException
{
gatherCandidates(component, preferredPort, minPort, maxPort);
logger.fine(
"Candidate count in first harvest: "
+ component.getLocalCandidateCount());
//select the candidate to put in the media line.
component.selectDefaultCandidate();
}
/**
* Returns the {@link FoundationsRegistry} this agent is using to assign
* candidate foundations. We use the <tt>FoundationsRegistry</tt> to keep
* track of the foundations we assign within a session (i.e. the entire life
* time of a <tt>BaseAgent</tt>.)
*/
public final FoundationsRegistry getFoundationsRegistry()
{
return foundationsRegistry;
}
/**
* Returns that password that should be advertised in session descriptions
* containing ICE data from this agent.
*
* @return that password that should be advertised in session descriptions
* containing ICE data from this agent.
*/
public String getLocalPassword()
{
return password;
}
/**
* Returns that user name that should be advertised in session descriptions
* containing ICE data from this agent.
*
* @return that user name that should be advertised in session descriptions
* containing ICE data from this agent.
*/
public String getLocalUfrag()
{
return ufrag;
}
/**
* Returns the <tt>IceMediaStream</tt> with the specified <tt>name</tt> or
* <tt>null</tt> if no such stream has been registered with this
* <tt>BaseAgent</tt> yet.
*
* @param name the name of the stream that we'd like to obtain a reference
* to.
*
* @return the <tt>IceMediaStream</tt> with the specified <tt>name</tt> or
* <tt>null</tt> if no such stream has been registered with this
* <tt>BaseAgent</tt> yet.
*/
public IceMediaStream getStream(String name)
{
synchronized(mediaStreams)
{
return mediaStreams.get(name);
}
}
/**
* Returns the number of <tt>IceMediaStream</tt>s currently registered with
* this agent.
*
* @return the number of <tt>IceMediaStream</tt>s currently registered with
* this agent.
*
*/
public int getStreamCount()
{
synchronized(mediaStreams)
{
return mediaStreams.size();
}
}
/**
* Returns a <tt>List</tt> containing the names of all currently registered
* media streams.
*
* @return a <tt>List</tt> containing the names of all currently registered
* media streams.
*/
public List<String> getStreamNames()
{
synchronized(mediaStreams)
{
return new LinkedList<>(mediaStreams.keySet());
}
}
/**
* Returns a <tt>List</tt> containing all <tt>IceMediaStream</tt>s currently
* registered with this agent.
*
* @return a <tt>List</tt> containing all <tt>IceMediaStream</tt>s currently
* registered with this agent.
*/
public List<IceMediaStream> getStreams()
{
synchronized(mediaStreams)
{
return new LinkedList<>(mediaStreams.values());
}
}
/**
* Gets the <tt>StunStack</tt> used by this <tt>BaseAgent</tt>.
*
* @return the <tt>StunStack</tt> used by this <tt>BaseAgent</tt>
*/
public synchronized StunStack getStunStack()
{
if (stunStack == null)
stunStack = new StunStack();
return stunStack;
}
/**
* Determines whether this agent has the controlling role in an ICE
* exchange.
*
* @return <tt>true</tt> if this is to be the controlling <tt>BaseAgent</tt>
* and <tt>false</tt> otherwise.
*/
public boolean isControlling()
{
return controlling;
}
/**
* Removes <tt>stream</tt> and all its child <tt>Component</tt>s and
* <tt>Candidate</tt>s from the this agent and releases all resources that
* they had allocated (like sockets for example)
*
* @param stream the <tt>Component</tt> we'd like to remove and free.
*/
public void removeStream(IceMediaStream stream)
{
synchronized (mediaStreams)
{
mediaStreams.remove(stream.getName());
}
/*
* XXX The invocation of IceMediaStream#free() on stream has been moved
* out of the synchronized block in order to reduce the chances of a
* deadlock. There was no obvious reason why it should stay in the
* synchronized block at the time of the modification.
*/
stream.free();
}
/**
* Specifies whether this agent has the controlling role in an ICE exchange.
*
* @param controlling <tt>true</tt> if this is to be the controlling
* <tt>BaseAgent</tt> and <tt>false</tt> otherwise.
*/
public void setControlling(boolean controlling)
{
this.controlling = controlling;
}
/**
* Sets the <tt>StunStack</tt> to be used by this <tt>BaseAgent</tt>.
*
* @param stunStack the <tt>StunStack</tt> to be used by this
* <tt>BaseAgent</tt>.
*/
public void setStunStack(StunStack stunStack)
{
this.stunStack = stunStack;
}
/**
* Sets the flag which indicates whether the dynamic host harvester (i.e.
* {@link #hostHarvester}) is (to be) used by this <tt>BaseAgent</tt>.
*
* @param useHostHarvester {@code true} to use the dynamic host harvester;
* otherwise, {@code false}.
*/
public void setUseHostHarvester(boolean useHostHarvester)
{
this.useHostHarvester = useHostHarvester;
}
/**
* Determines whether the dynamic host harvester (i.e.
* {@link #hostHarvester}) is (to be) used.
*
* @return <tt>true</tt> if the dynamic host harvester is (to be) used;
* <tt>false</tt>, otherwise.
*/
public boolean useHostHarvester()
{
if (useHostHarvester == null)
{
useHostHarvester
= StackProperties.getBoolean(
StackProperties.USE_DYNAMIC_HOST_HARVESTER,
true);
}
return useHostHarvester;
}
}

View File

@ -56,8 +56,7 @@ public class CheckList
* A pair would get into a triggered check queue as soon as we receive * A pair would get into a triggered check queue as soon as we receive
* a check on its local candidate. * a check on its local candidate.
*/ */
private final List<CandidatePair> triggeredCheckQueue private final List<CandidatePair> triggeredCheckQueue = new LinkedList<>();
= new LinkedList<CandidatePair>();
/** /**
* A reference to the {@link IceMediaStream} that we belong to. * A reference to the {@link IceMediaStream} that we belong to.
@ -69,14 +68,14 @@ public class CheckList
* Agent} and following its changes of state. * Agent} and following its changes of state.
*/ */
private final List<PropertyChangeListener> stateListeners private final List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>(); = new LinkedList<>();
/** /**
* Contains {@link PropertyChangeListener}s registered with this {@link * Contains {@link PropertyChangeListener}s registered with this {@link
* Agent} and following its changes of state. * Agent} and following its changes of state.
*/ */
private final List<PropertyChangeListener> checkListeners private final List<PropertyChangeListener> checkListeners
= new LinkedList<PropertyChangeListener>(); = new LinkedList<>();
/** /**
* The name of the {@link PropertyChangeEvent} that we use to deliver * The name of the {@link PropertyChangeEvent} that we use to deliver
@ -297,8 +296,7 @@ public class CheckList
*/ */
protected synchronized void computeInitialCheckListPairStates() protected synchronized void computeInitialCheckListPairStates()
{ {
Map<String, CandidatePair> pairsToWait Map<String, CandidatePair> pairsToWait = new Hashtable<>();
= new Hashtable<String, CandidatePair>();
//first, determine the pairs that we'd need to put in the waiting state. //first, determine the pairs that we'd need to put in the waiting state.
for(CandidatePair pair : this) for(CandidatePair pair : this)
@ -508,8 +506,7 @@ public class CheckList
synchronized(stateListeners) synchronized(stateListeners)
{ {
listenersCopy listenersCopy = new LinkedList<>(stateListeners);
= new LinkedList<PropertyChangeListener>(stateListeners);
} }
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(
@ -564,8 +561,7 @@ public class CheckList
synchronized(checkListeners) synchronized(checkListeners)
{ {
listenersCopy listenersCopy = new LinkedList<>(checkListeners);
= new LinkedList<PropertyChangeListener>(checkListeners);
} }
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(

View File

@ -73,21 +73,19 @@ public class Component
/** /**
* The list locally gathered candidates for this media stream. * The list locally gathered candidates for this media stream.
*/ */
private final List<LocalCandidate> localCandidates private final List<LocalCandidate> localCandidates = new LinkedList<>();
= new LinkedList<LocalCandidate>();
/** /**
* The list of candidates that the peer agent sent for this stream. * The list of candidates that the peer agent sent for this stream.
*/ */
private final List<RemoteCandidate> remoteCandidates private final List<RemoteCandidate> remoteCandidates = new LinkedList<>();
= new LinkedList<RemoteCandidate>();
/** /**
* The list of candidates that the peer agent sent for this stream after * The list of candidates that the peer agent sent for this stream after
* connectivity establishment. * connectivity establishment.
*/ */
private final List<RemoteCandidate> remoteUpdateCandidates = private final List<RemoteCandidate> remoteUpdateCandidates
new LinkedList<RemoteCandidate>(); = new LinkedList<>();
/** /**
* A <tt>Comparator</tt> that we use for sorting <tt>Candidate</tt>s by * A <tt>Comparator</tt> that we use for sorting <tt>Candidate</tt>s by
@ -143,7 +141,7 @@ public class Component
*/ */
public boolean addLocalCandidate(LocalCandidate candidate) public boolean addLocalCandidate(LocalCandidate candidate)
{ {
Agent agent = getParentStream().getParentAgent(); BaseAgent agent = getParentStream().getParentAgent();
//assign foundation. //assign foundation.
agent.getFoundationsRegistry().assignFoundation(candidate); agent.getFoundationsRegistry().assignFoundation(candidate);
@ -185,7 +183,7 @@ public class Component
{ {
synchronized(localCandidates) synchronized(localCandidates)
{ {
return new ArrayList<LocalCandidate>(localCandidates); return new ArrayList<>(localCandidates);
} }
} }
@ -257,8 +255,7 @@ public class Component
logger.info("Update remote candidate for " + toShortString() + ": " + logger.info("Update remote candidate for " + toShortString() + ": " +
candidate.getTransportAddress()); candidate.getTransportAddress());
List<RemoteCandidate> existingCandidates List<RemoteCandidate> existingCandidates = new LinkedList<>();
= new LinkedList<RemoteCandidate>();
synchronized (remoteCandidates) synchronized (remoteCandidates)
{ {
existingCandidates.addAll(remoteCandidates); existingCandidates.addAll(remoteCandidates);
@ -300,8 +297,7 @@ public class Component
if(remoteUpdateCandidates.size() == 0) if(remoteUpdateCandidates.size() == 0)
return; return;
newRemoteCandidates newRemoteCandidates = new LinkedList<>(remoteUpdateCandidates);
= new LinkedList<RemoteCandidate>(remoteUpdateCandidates);
List<LocalCandidate> localCnds = getLocalCandidates(); List<LocalCandidate> localCnds = getLocalCandidates();
@ -315,7 +311,7 @@ public class Component
} }
} }
checkList = new Vector<CandidatePair>(); checkList = new Vector<>();
for(LocalCandidate localCnd : localCnds) for(LocalCandidate localCnd : localCnds)
{ {
@ -391,7 +387,7 @@ public class Component
{ {
synchronized(remoteCandidates) synchronized(remoteCandidates)
{ {
return new ArrayList<RemoteCandidate>(remoteCandidates); return new ArrayList<>(remoteCandidates);
} }
} }
@ -459,15 +455,17 @@ public class Component
StringBuffer buff StringBuffer buff
= new StringBuffer("Component id=").append(getComponentID()); = new StringBuffer("Component id=").append(getComponentID());
buff.append(" parent stream=" + getParentStream().getName()); buff.append(" parent stream=").append(getParentStream().getName());
//local candidates //local candidates
int localCandidatesCount = getLocalCandidateCount(); int localCandidatesCount = getLocalCandidateCount();
if(localCandidatesCount > 0) if(localCandidatesCount > 0)
{ {
buff.append("\n" + localCandidatesCount + " Local candidates:"); buff.append("\n")
buff.append("\ndefault candidate: " + getDefaultCandidate()); .append(localCandidatesCount)
.append(" Local candidates:");
buff.append("\ndefault candidate: ").append(getDefaultCandidate());
synchronized(localCandidates) synchronized(localCandidates)
{ {
@ -487,14 +485,16 @@ public class Component
if(remoteCandidatesCount > 0) if(remoteCandidatesCount > 0)
{ {
buff.append("\n" + remoteCandidatesCount + " Remote candidates:"); buff.append("\n")
buff.append("\ndefault remote candidate: " .append(remoteCandidatesCount)
+ getDefaultRemoteCandidate()); .append(" Remote candidates:");
buff.append("\ndefault remote candidate: ")
.append(getDefaultRemoteCandidate());
synchronized(remoteCandidates) synchronized(remoteCandidates)
{ {
for (RemoteCandidate cand : remoteCandidates) for (RemoteCandidate cand : remoteCandidates)
{ {
buff.append("\n" + cand.toString()); buff.append("\n").append(cand);
} }
} }
} }
@ -701,12 +701,8 @@ public class Component
{ {
synchronized(localCandidates) synchronized(localCandidates)
{ {
Iterator<LocalCandidate> localCandsIter = localCandidates.iterator(); for (LocalCandidate cand : localCandidates)
while (localCandsIter.hasNext())
{ {
LocalCandidate cand = localCandsIter.next();
if ((defaultCandidate == null) if ((defaultCandidate == null)
|| (defaultCandidate.getDefaultPreference() || (defaultCandidate.getDefaultPreference()
< cand.getDefaultPreference())) < cand.getDefaultPreference()))

View File

@ -57,13 +57,13 @@ class ConnectivityCheckClient
/** /**
* The {@link PaceMaker}s that are currently running checks in this client. * The {@link PaceMaker}s that are currently running checks in this client.
*/ */
private final List<PaceMaker> paceMakers = new LinkedList<PaceMaker>(); private final List<PaceMaker> paceMakers = new LinkedList<>();
/** /**
* Timer that is used to let some seconds before a CheckList is considered * Timer that is used to let some seconds before a CheckList is considered
* as FAILED. * as FAILED.
*/ */
private Map<String, Timer> timers = new HashMap<String, Timer>(); private Map<String, Timer> timers = new HashMap<>();
/** /**
* A flag that determines whether we have received a STUN response or not. * A flag that determines whether we have received a STUN response or not.
@ -611,7 +611,7 @@ class ConnectivityCheckClient
synchronized(this) synchronized(this)
{ {
Vector<CandidatePair> parentCheckList Vector<CandidatePair> parentCheckList
= new Vector<CandidatePair>(parentStream.getCheckList()); = new Vector<>(parentStream.getCheckList());
for(CandidatePair pair : parentCheckList) for(CandidatePair pair : parentCheckList)
if ((pair.getState() == CandidatePairState.FROZEN) if ((pair.getState() == CandidatePairState.FROZEN)

View File

@ -63,7 +63,7 @@ class ConnectivityCheckServer
/** /**
* The agent that created us. * The agent that created us.
*/ */
private final Agent parentAgent; private final BaseAgent parentAgent;
/** /**
* The indicator which determines whether this * The indicator which determines whether this
@ -88,7 +88,7 @@ class ConnectivityCheckServer
* *
* @param parentAgent the <tt>Agent</tt> that is creating this instance. * @param parentAgent the <tt>Agent</tt> that is creating this instance.
*/ */
public ConnectivityCheckServer(Agent parentAgent) public ConnectivityCheckServer(BaseAgent parentAgent)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
@ -139,7 +139,7 @@ class ConnectivityCheckServer
//ignore incoming requests that are not meant for the local user. //ignore incoming requests that are not meant for the local user.
//normally the stack will get rid of faulty user names but we could //normally the stack will get rid of faulty user names but we could
//still see messages not meant for this server if both peers or running //still see messages not meant for this server if both peers are running
//on this same instance of the stack. //on this same instance of the stack.
UsernameAttribute uname = (UsernameAttribute)request UsernameAttribute uname = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME); .getAttribute(Attribute.USERNAME);

View File

@ -50,8 +50,7 @@ public class DefaultNominator
* Map that will remember association between validated relayed candidate * Map that will remember association between validated relayed candidate
* and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy. * and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy.
*/ */
private final Map<String, TimerTask> validatedCandidates private final Map<String, TimerTask> validatedCandidates = new HashMap<>();
= new HashMap<String, TimerTask>();
/** /**
* Creates a new instance of this nominator using <tt>parentAgent</tt> as * Creates a new instance of this nominator using <tt>parentAgent</tt> as

View File

@ -44,7 +44,7 @@ public class FoundationsRegistry
* Contains mappings between a type+baseIP+server+transport * Contains mappings between a type+baseIP+server+transport
* <tt>String</tt>s and the foundation that has been assigned to them. * <tt>String</tt>s and the foundation that has been assigned to them.
*/ */
private Map<String, String> foundations = new Hashtable<String, String>(); private Map<String, String> foundations = new Hashtable<>();
/** /**
* Assigns to <tt>candidate</tt> the foundation that corresponds to its * Assigns to <tt>candidate</tt> the foundation that corresponds to its

View File

@ -63,6 +63,19 @@ public class IceMediaStream
*/ */
public static final String PROPERTY_PAIR_VALIDATED = "PairValidated"; public static final String PROPERTY_PAIR_VALIDATED = "PairValidated";
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(BaseAgent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
/** /**
* The name of this media stream. The name is equal to the value specified * The name of this media stream. The name is equal to the value specified
* in the SDP description. * in the SDP description.
@ -75,8 +88,7 @@ public class IceMediaStream
* address; a media stream may require multiple components, each of which * address; a media stream may require multiple components, each of which
* has to work for the media stream as a whole to work. * has to work for the media stream as a whole to work.
*/ */
private final Map<Integer, Component> components private final Map<Integer, Component> components = new LinkedHashMap<>();
= new LinkedHashMap<Integer, Component>();
/** /**
* An ordered set of candidate pairs for a media stream that have been * An ordered set of candidate pairs for a media stream that have been
@ -84,8 +96,7 @@ public class IceMediaStream
* start of ICE processing, and fills as checks are performed, resulting in * start of ICE processing, and fills as checks are performed, resulting in
* valid candidate pairs. * valid candidate pairs.
*/ */
private final TreeSet<CandidatePair> validList private final TreeSet<CandidatePair> validList = new TreeSet<>();
= new TreeSet<CandidatePair>();
/** /**
* The id that was last assigned to a component. The next id that we give * The id that was last assigned to a component. The next id that we give
@ -103,14 +114,14 @@ public class IceMediaStream
/** /**
* The agent that this media stream belongs to. * The agent that this media stream belongs to.
*/ */
private final Agent parentAgent; private final BaseAgent parentAgent;
/** /**
* Contains {@link PropertyChangeListener}s registered with this {@link * Contains {@link PropertyChangeListener}s registered with this {@link
* Agent} and following the various events it may be generating. * Agent} and following the various events it may be generating.
*/ */
private final List<PropertyChangeListener> streamListeners private final List<PropertyChangeListener> streamListeners
= new LinkedList<PropertyChangeListener>(); = new LinkedList<>();
/** /**
* The maximum number of candidate pairs that we should have in our check * The maximum number of candidate pairs that we should have in our check
@ -140,7 +151,7 @@ public class IceMediaStream
* @param parentAgent the agent that is handling the session that this * @param parentAgent the agent that is handling the session that this
* media stream is a part of * media stream is a part of
*/ */
protected IceMediaStream(Agent parentAgent, String name) protected IceMediaStream(BaseAgent parentAgent, String name)
{ {
this.name = name; this.name = name;
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
@ -163,9 +174,7 @@ public class IceMediaStream
synchronized (components) synchronized (components)
{ {
component = new Component(++lastComponentID, this); component = new Component(++lastComponentID, this);
components.put( components.put(component.getComponentID(), component);
Integer.valueOf(component.getComponentID()),
component);
} }
return component; return component;
@ -231,7 +240,7 @@ public class IceMediaStream
{ {
synchronized(components) synchronized(components)
{ {
return new ArrayList<Component>(components.values()); return new ArrayList<>(components.values());
} }
} }
@ -261,7 +270,7 @@ public class IceMediaStream
{ {
synchronized(components) synchronized(components)
{ {
return new ArrayList<Integer>(components.keySet()); return new ArrayList<>(components.keySet());
} }
} }
@ -282,7 +291,7 @@ public class IceMediaStream
* *
* @return a reference to the <tt>Agent</tt> that this stream belongs to. * @return a reference to the <tt>Agent</tt> that this stream belongs to.
*/ */
public Agent getParentAgent() public BaseAgent getParentAgent()
{ {
return parentAgent; return parentAgent;
} }
@ -436,8 +445,7 @@ public class IceMediaStream
{ {
//a list that we only use for storing pairs that we've already gone //a list that we only use for storing pairs that we've already gone
//through. The list is destroyed at the end of this method. //through. The list is destroyed at the end of this method.
List<CandidatePair> tmpCheckList List<CandidatePair> tmpCheckList = new ArrayList<>(checkList.size());
= new ArrayList<CandidatePair>(checkList.size());
Iterator<CandidatePair> ckListIter = checkList.iterator(); Iterator<CandidatePair> ckListIter = checkList.iterator();
@ -903,18 +911,4 @@ public class IceMediaStream
{ {
return remotePassword; return remotePassword;
} }
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(Agent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
} }

View File

@ -707,8 +707,7 @@ public class NetworkUtils
{ {
Method method = iface.getClass().getMethod("isLoopback"); Method method = iface.getClass().getMethod("isLoopback");
return ((Boolean)method.invoke(iface, new Object[]{})) return (Boolean) method.invoke(iface);
.booleanValue();
} }
catch(Throwable t) catch(Throwable t)
{ {
@ -739,7 +738,7 @@ public class NetworkUtils
{ {
Method method = iface.getClass().getMethod("isUp"); Method method = iface.getClass().getMethod("isUp");
return ((Boolean)method.invoke(iface)).booleanValue(); return (Boolean) method.invoke(iface);
} }
catch(Throwable t) catch(Throwable t)
{ {
@ -769,7 +768,7 @@ public class NetworkUtils
{ {
Method method = iface.getClass().getMethod("isVirtual"); Method method = iface.getClass().getMethod("isVirtual");
return ((Boolean)method.invoke(iface)).booleanValue(); return (Boolean) method.invoke(iface);
} }
catch(Throwable t) catch(Throwable t)
{ {

View File

@ -131,10 +131,9 @@ public class RemoteCandidate
{ {
Component parentCmp = getParentComponent(); Component parentCmp = getParentComponent();
if (parentCmp == null) return
return false; (parentCmp != null)
&& equals(parentCmp.getDefaultRemoteCandidate());
return equals(parentCmp.getDefaultRemoteCandidate());
} }
/** /**

View File

@ -38,8 +38,7 @@ public class TcpHostCandidate
/** /**
* List of <tt>accept</tt>ed sockets for this <tt>TcpHostCandidate</tt>. * List of <tt>accept</tt>ed sockets for this <tt>TcpHostCandidate</tt>.
*/ */
private final List<IceSocketWrapper> sockets private final List<IceSocketWrapper> sockets = new LinkedList<>();
= new LinkedList<IceSocketWrapper>();
/** /**
* Initializes a new <tt>TcpHostCandidate</tt>. * Initializes a new <tt>TcpHostCandidate</tt>.

View File

@ -44,7 +44,7 @@ public class CandidateHarvesterSet
* <tt>Set</tt>. * <tt>Set</tt>.
*/ */
private final Collection<CandidateHarvesterSetElement> elements private final Collection<CandidateHarvesterSetElement> elements
= new LinkedList<CandidateHarvesterSetElement>(); = new LinkedList<>();
/** /**
* A pool of thread used for gathering process. * A pool of thread used for gathering process.
@ -95,7 +95,7 @@ public class CandidateHarvesterSet
*/ */
public void harvest(Component component) public void harvest(Component component)
{ {
harvest(Arrays.asList(new Component[]{component}), null); harvest(Arrays.asList(component), null);
} }
@ -145,8 +145,7 @@ public class CandidateHarvesterSet
* Start asynchronously executing the * Start asynchronously executing the
* CandidateHarvester#harvest(Component) method of the harvesters. * CandidateHarvester#harvest(Component) method of the harvesters.
*/ */
Map<CandidateHarvesterSetTask, Future<?>> tasks Map<CandidateHarvesterSetTask, Future<?>> tasks = new HashMap<>();
= new HashMap<CandidateHarvesterSetTask, Future<?>>();
while (true) while (true)
{ {
@ -171,7 +170,7 @@ public class CandidateHarvesterSet
synchronized (components) synchronized (components)
{ {
componentsCopy = new ArrayList<Component>(components); componentsCopy = new ArrayList<>(components);
} }
// Asynchronously start gathering candidates using the harvester. // Asynchronously start gathering candidates using the harvester.
@ -194,7 +193,7 @@ public class CandidateHarvesterSet
= taskIter.next(); = taskIter.next();
Future<?> future = task.getValue(); Future<?> future = task.getValue();
while (true) do
{ {
try try
{ {
@ -232,9 +231,9 @@ public class CandidateHarvesterSet
} }
catch (InterruptedException ie) catch (InterruptedException ie)
{ {
continue;
} }
} }
while (true);
taskIter.remove(); taskIter.remove();
} }
} }

View File

@ -194,7 +194,7 @@ public class HostCandidateHarvester
} }
if (allowedAddresses == null) if (allowedAddresses == null)
allowedAddresses = new ArrayList<InetAddress>(); allowedAddresses = new ArrayList<>();
allowedAddresses.add(address); allowedAddresses.add(address);
} }
@ -220,7 +220,7 @@ public class HostCandidateHarvester
} }
if (blockedAddresses == null) if (blockedAddresses == null)
blockedAddresses = new ArrayList<InetAddress>(); blockedAddresses = new ArrayList<>();
blockedAddresses.add(address); blockedAddresses.add(address);
} }

View File

@ -84,7 +84,7 @@ public class MappingCandidateHarvester
* Report the LocalCandidates gathered by this CandidateHarvester so * Report the LocalCandidates gathered by this CandidateHarvester so
* that the harvest is sure to be considered successful. * that the harvest is sure to be considered successful.
*/ */
Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>(); Collection<LocalCandidate> candidates = new HashSet<>();
for (Candidate<?> cand : component.getLocalCandidates()) for (Candidate<?> cand : component.getLocalCandidates())
{ {

View File

@ -84,10 +84,9 @@ public class SinglePortUdpHarvester
public static List<SinglePortUdpHarvester> public static List<SinglePortUdpHarvester>
createHarvesters(int port) createHarvesters(int port)
{ {
List<SinglePortUdpHarvester> harvesters List<SinglePortUdpHarvester> harvesters = new LinkedList<>();
= new LinkedList<SinglePortUdpHarvester>();
List<TransportAddress> addresses = new LinkedList<TransportAddress>(); List<TransportAddress> addresses = new LinkedList<>();
boolean isIPv6Disabled = StackProperties.getBoolean( boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6, StackProperties.DISABLE_IPv6,
false); false);
@ -157,7 +156,7 @@ public class SinglePortUdpHarvester
* other threads remove entries when candidates are freed. * other threads remove entries when candidates are freed.
*/ */
private final Map<SocketAddress, MySocket> sockets private final Map<SocketAddress, MySocket> sockets
= new ConcurrentHashMap<SocketAddress, MySocket>(); = new ConcurrentHashMap<>();
/** /**
* The map which keeps all currently active <tt>Candidate</tt>s created by * The map which keeps all currently active <tt>Candidate</tt>s created by
@ -165,14 +164,14 @@ public class SinglePortUdpHarvester
* the components for which the candidates are harvested. * the components for which the candidates are harvested.
*/ */
private final Map<String, MyCandidate> candidates private final Map<String, MyCandidate> candidates
= new ConcurrentHashMap<String, MyCandidate>(); = new ConcurrentHashMap<>();
/** /**
* A pool of <tt>Buffer</tt> instances used to avoid creating of new java * A pool of <tt>Buffer</tt> instances used to avoid creating of new java
* objects. * objects.
*/ */
private final ArrayBlockingQueue<Buffer> pool private final ArrayBlockingQueue<Buffer> pool
= new ArrayBlockingQueue<Buffer>(POOL_SIZE); = new ArrayBlockingQueue<>(POOL_SIZE);
/** /**
* The local address that this harvester is bound to. * The local address that this harvester is bound to.
@ -234,7 +233,7 @@ public class SinglePortUdpHarvester
MySocket destinationSocket; MySocket destinationSocket;
InetSocketAddress remoteAddress; InetSocketAddress remoteAddress;
while (true) do
{ {
// TODO: implement stopping the thread with a switch? // TODO: implement stopping the thread with a switch?
@ -302,21 +301,19 @@ public class SinglePortUdpHarvester
catch (SocketException se) catch (SocketException se)
{ {
logger.info("Could not create a socket: " + se); logger.info("Could not create a socket: " + se);
continue;
} }
catch (IOException ioe) catch (IOException ioe)
{ {
logger.info("Failed to handle new socket: " + ioe); logger.info("Failed to handle new socket: " + ioe);
continue;
} }
} }
else else
{ {
// A STUN Binding Request with an unknown USERNAME. Drop it. // A STUN Binding Request with an unknown USERNAME. Drop it.
continue;
} }
} }
} }
while (true);
// TODO we are all done, clean up. // TODO we are all done, clean up.
} }
@ -417,7 +414,7 @@ public class SinglePortUdpHarvester
public Collection<LocalCandidate> harvest(Component component) public Collection<LocalCandidate> harvest(Component component)
{ {
IceMediaStream stream = component.getParentStream(); IceMediaStream stream = component.getParentStream();
Agent agent = stream.getParentAgent(); BaseAgent agent = stream.getParentAgent();
String ufrag = agent.getLocalUfrag(); String ufrag = agent.getLocalUfrag();
if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1) if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1)
@ -430,7 +427,7 @@ public class SinglePortUdpHarvester
*/ */
logger.info( logger.info(
"More than one Component for an Agent, cannot harvest."); "More than one Component for an Agent, cannot harvest.");
return new LinkedList<LocalCandidate>(); return new LinkedList<>();
} }
MyCandidate candidate = new MyCandidate(component, ufrag); MyCandidate candidate = new MyCandidate(component, ufrag);
@ -469,7 +466,7 @@ public class SinglePortUdpHarvester
* The FIFO which acts as a buffer for this socket. * The FIFO which acts as a buffer for this socket.
*/ */
private final ArrayBlockingQueue<Buffer> queue private final ArrayBlockingQueue<Buffer> queue
= new ArrayBlockingQueue<Buffer>(QUEUE_SIZE); = new ArrayBlockingQueue<>(QUEUE_SIZE);
/** /**
* The remote address that is associated with this socket. * The remote address that is associated with this socket.
@ -692,7 +689,7 @@ public class SinglePortUdpHarvester
* a corresponding socket in {@link #sockets}. * a corresponding socket in {@link #sockets}.
*/ */
private final Map<SocketAddress, IceSocketWrapper> candidateSockets private final Map<SocketAddress, IceSocketWrapper> candidateSockets
= new HashMap<SocketAddress, IceSocketWrapper>(); = new HashMap<>();
/** /**
* The collection of <tt>DatagramSocket</tt>s added to this candidate. * The collection of <tt>DatagramSocket</tt>s added to this candidate.
@ -702,7 +699,7 @@ public class SinglePortUdpHarvester
* the STUN stack or the user of ice4j. * the STUN stack or the user of ice4j.
*/ */
private final Map<SocketAddress, DatagramSocket> sockets private final Map<SocketAddress, DatagramSocket> sockets
= new HashMap<SocketAddress, DatagramSocket>(); = new HashMap<>();
/** /**
* Initializes a new <tt>MyCandidate</tt> instance with the given * Initializes a new <tt>MyCandidate</tt> instance with the given

View File

@ -68,8 +68,7 @@ public class StunCandidateHarvest
* The list of <tt>Candidate</tt>s harvested for {@link #hostCandidate} by * The list of <tt>Candidate</tt>s harvested for {@link #hostCandidate} by
* this harvest. * this harvest.
*/ */
private final List<LocalCandidate> candidates private final List<LocalCandidate> candidates = new LinkedList<>();
= new LinkedList<LocalCandidate>();
/** /**
* The indicator which determines whether this <tt>StunCandidateHarvest</tt> * The indicator which determines whether this <tt>StunCandidateHarvest</tt>
@ -104,8 +103,7 @@ public class StunCandidateHarvest
* to which a STUN <tt>Response</tt> responds available though it is known * to which a STUN <tt>Response</tt> responds available though it is known
* in <tt>StunClientTransaction</tt>. * in <tt>StunClientTransaction</tt>.
*/ */
private final Map<TransactionID, Request> requests private final Map<TransactionID, Request> requests = new HashMap<>();
= new HashMap<TransactionID, Request>();
/** /**
* The interval in milliseconds at which a new STUN keep-alive message is to * The interval in milliseconds at which a new STUN keep-alive message is to
@ -1448,7 +1446,7 @@ public class StunCandidateHarvest
*/ */
public SendKeepAliveMessageThread(StunCandidateHarvest harvest) public SendKeepAliveMessageThread(StunCandidateHarvest harvest)
{ {
this.harvest = new WeakReference<StunCandidateHarvest>(harvest); this.harvest = new WeakReference<>(harvest);
} }
@Override @Override

View File

@ -51,7 +51,7 @@ public class StunCandidateHarvester
* completed i.e. have harvested <tt>Candidate</tt>s. * completed i.e. have harvested <tt>Candidate</tt>s.
*/ */
private final List<StunCandidateHarvest> completedHarvests private final List<StunCandidateHarvest> completedHarvests
= new LinkedList<StunCandidateHarvest>(); = new LinkedList<>();
/** /**
* The username used by this <tt>StunCandidateHarvester</tt> for the * The username used by this <tt>StunCandidateHarvester</tt> for the
@ -65,7 +65,7 @@ public class StunCandidateHarvester
* not completed yet so {@link #harvest(Component)} has to wait for them. * not completed yet so {@link #harvest(Component)} has to wait for them.
*/ */
private final List<StunCandidateHarvest> startedHarvests private final List<StunCandidateHarvest> startedHarvests
= new LinkedList<StunCandidateHarvest>(); = new LinkedList<>();
/** /**
* The address of the STUN server that we will be sending our requests to. * The address of the STUN server that we will be sending our requests to.
@ -255,7 +255,7 @@ public class StunCandidateHarvester
* Report the LocalCandidates gathered by this CandidateHarvester so * Report the LocalCandidates gathered by this CandidateHarvester so
* that the harvest is sure to be considered successful. * that the harvest is sure to be considered successful.
*/ */
Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>(); Collection<LocalCandidate> candidates = new HashSet<>();
synchronized (completedHarvests) synchronized (completedHarvests)
{ {

View File

@ -83,7 +83,7 @@ public class TcpHarvester
List<NetworkInterface> interfaces) List<NetworkInterface> interfaces)
throws IOException throws IOException
{ {
List<TransportAddress> addresses = new LinkedList<TransportAddress>(); List<TransportAddress> addresses = new LinkedList<>();
for (NetworkInterface iface : interfaces) for (NetworkInterface iface : interfaces)
{ {
@ -126,34 +126,32 @@ public class TcpHarvester
* <tt>Component</tt>s from being freed. * <tt>Component</tt>s from being freed.
*/ */
private final Map<String, WeakReference<Component>> components private final Map<String, WeakReference<Component>> components
= new HashMap<String, WeakReference<Component>>(); = new HashMap<>();
/** /**
* The list of transport addresses which we have found to be listening on, * The list of transport addresses which we have found to be listening on,
* and which we will advertise as candidates in * and which we will advertise as candidates in
* {@link #harvest(org.ice4j.ice.Component)} * {@link #harvest(org.ice4j.ice.Component)}
*/ */
private final List<TransportAddress> localAddresses private final List<TransportAddress> localAddresses = new LinkedList<>();
= new LinkedList<TransportAddress>();
/** /**
* Maps a public address to a local address. * Maps a public address to a local address.
*/ */
private final Map<InetAddress, InetAddress> mappedAddresses private final Map<InetAddress, InetAddress> mappedAddresses
= new HashMap<InetAddress, InetAddress>(); = new HashMap<>();
/** /**
* Sets of additional ports, for which server reflexive candidates will be * Sets of additional ports, for which server reflexive candidates will be
* added. * added.
*/ */
private final Set<Integer> mappedPorts = new HashSet<Integer>(); private final Set<Integer> mappedPorts = new HashSet<>();
/** /**
* Channels pending to be added to the list that {@link #readThread} reads * Channels pending to be added to the list that {@link #readThread} reads
* from. * from.
*/ */
private final List<SocketChannel> newChannels private final List<SocketChannel> newChannels = new LinkedList<>();
= new LinkedList<SocketChannel>();
/** /**
* A counter used to decide when to purge {@link #components}. * A counter used to decide when to purge {@link #components}.
@ -175,7 +173,7 @@ public class TcpHarvester
* on. * on.
*/ */
private final List<ServerSocketChannel> serverSocketChannels private final List<ServerSocketChannel> serverSocketChannels
= new LinkedList<ServerSocketChannel>(); = new LinkedList<>();
/** /**
* Whether or not to use ssltcp. * Whether or not to use ssltcp.
@ -421,8 +419,7 @@ public class TcpHarvester
*/ */
private List<LocalCandidate> createLocalCandidates(Component component) private List<LocalCandidate> createLocalCandidates(Component component)
{ {
List<TcpHostCandidate> hostCandidates List<TcpHostCandidate> hostCandidates = new LinkedList<>();
= new LinkedList<TcpHostCandidate>();
// Add the host candidates for the addresses we really listen on // Add the host candidates for the addresses we really listen on
for (TransportAddress transportAddress : localAddresses) for (TransportAddress transportAddress : localAddresses)
@ -438,8 +435,7 @@ public class TcpHarvester
} }
// Add srflx candidates for any mapped addresses // Add srflx candidates for any mapped addresses
List<LocalCandidate> mappedCandidates List<LocalCandidate> mappedCandidates = new LinkedList<>();
= new LinkedList<LocalCandidate>();
for (Map.Entry<InetAddress, InetAddress> mapping for (Map.Entry<InetAddress, InetAddress> mapping
: mappedAddresses.entrySet()) : mappedAddresses.entrySet())
@ -473,8 +469,7 @@ public class TcpHarvester
} }
// Add srflx candidates for mapped ports // Add srflx candidates for mapped ports
List<LocalCandidate> portMappedCandidates List<LocalCandidate> portMappedCandidates = new LinkedList<>();
= new LinkedList<LocalCandidate>();
for (TcpHostCandidate base : hostCandidates) for (TcpHostCandidate base : hostCandidates)
{ {
@ -524,8 +519,7 @@ public class TcpHarvester
} }
} }
LinkedList<LocalCandidate> allCandidates LinkedList<LocalCandidate> allCandidates = new LinkedList<>();
= new LinkedList<LocalCandidate>();
allCandidates.addAll(hostCandidates); allCandidates.addAll(hostCandidates);
allCandidates.addAll(mappedCandidates); allCandidates.addAll(mappedCandidates);
@ -577,7 +571,7 @@ public class TcpHarvester
public Collection<LocalCandidate> harvest(Component component) public Collection<LocalCandidate> harvest(Component component)
{ {
IceMediaStream stream = component.getParentStream(); IceMediaStream stream = component.getParentStream();
Agent agent = stream.getParentAgent(); BaseAgent agent = stream.getParentAgent();
if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1) if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1)
{ {
@ -589,7 +583,7 @@ public class TcpHarvester
*/ */
logger.info( logger.info(
"More than one Component for an Agent, cannot harvest."); "More than one Component for an Agent, cannot harvest.");
return new LinkedList<LocalCandidate>(); return Collections.EMPTY_LIST;
} }
List<LocalCandidate> candidates = createLocalCandidates(component); List<LocalCandidate> candidates = createLocalCandidates(component);
@ -599,8 +593,9 @@ public class TcpHarvester
synchronized (components) synchronized (components)
{ {
components.put(agent.getLocalUfrag(), components.put(
new WeakReference<Component>(component)); agent.getLocalUfrag(),
new WeakReference<>(component));
purgeComponents(); purgeComponents();
} }
@ -807,8 +802,7 @@ public class TcpHarvester
} }
IOException exception = null; IOException exception = null;
List<SocketChannel> channelsToAdd List<SocketChannel> channelsToAdd = new LinkedList<>();
= new LinkedList<SocketChannel>();
// Allow to go on, so we can quit if closed. // Allow to go on, so we can quit if closed.
long selectTimeout = 3000; long selectTimeout = 3000;
@ -1086,8 +1080,8 @@ public class TcpHarvester
} }
/** /**
* Adds the channels from {@link #newChannels} to {@link #channels} and * Registers the channels from {@link #newChannels} with
* registers them in {@link #readSelector}. * {@link #readSelector}.
*/ */
private void checkForNewChannels() private void checkForNewChannels()
{ {
@ -1114,8 +1108,9 @@ public class TcpHarvester
} }
/** /**
* Checks {@link #channels} for channels which have been added over * Checks {@link #readSelector} for channels which have been added over
* {@link #READ_TIMEOUT} milliseconds ago and closes them. * {@link MuxServerSocketChannelFactory#SOCKET_CHANNEL_READ_TIMEOUT}
* milliseconds ago and closes them.
*/ */
private void cleanup() private void cleanup()
{ {

View File

@ -323,9 +323,7 @@ public class TurnCandidateHarvest
EvenPortAttribute evenPortAttribute EvenPortAttribute evenPortAttribute
= (EvenPortAttribute) request.getAttribute(Attribute.EVEN_PORT); = (EvenPortAttribute) request.getAttribute(Attribute.EVEN_PORT);
boolean rFlag boolean rFlag
= (evenPortAttribute == null) = (evenPortAttribute != null) && evenPortAttribute.isRFlag();
? false
: evenPortAttribute.isRFlag();
return return
MessageFactory.createAllocateRequest( MessageFactory.createAllocateRequest(

View File

@ -87,7 +87,7 @@ public class UPNPHarvester
*/ */
public synchronized Collection<LocalCandidate> harvest(Component component) public synchronized Collection<LocalCandidate> harvest(Component component)
{ {
Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>(); Collection<LocalCandidate> candidates = new HashSet<>();
int retries = 0; int retries = 0;
logger.fine("Begin UPnP harvesting"); logger.fine("Begin UPnP harvesting");
@ -213,9 +213,9 @@ public class UPNPHarvester
String externalIP, int port, Component cmp, GatewayDevice device) String externalIP, int port, Component cmp, GatewayDevice device)
throws Exception throws Exception
{ {
List<LocalCandidate> ret = new ArrayList<LocalCandidate>(); List<LocalCandidate> ret = new ArrayList<>();
TransportAddress addr = new TransportAddress(externalIP, port, TransportAddress addr
Transport.UDP); = new TransportAddress(externalIP, port, Transport.UDP);
HostCandidate base = new HostCandidate(socket, cmp); HostCandidate base = new HostCandidate(socket, cmp);

View File

@ -273,8 +273,8 @@ public class IceSdpUtils
//m lines //m lines
List<IceMediaStream> streams = agent.getStreams(); List<IceMediaStream> streams = agent.getStreams();
Vector<MediaDescription> mDescs = new Vector<MediaDescription>( Vector<MediaDescription> mDescs
agent.getStreamCount()); = new Vector<>(agent.getStreamCount());
for(IceMediaStream stream : streams) for(IceMediaStream stream : streams)
{ {
MediaDescription mLine = sdpFactory.createMediaDescription( MediaDescription mLine = sdpFactory.createMediaDescription(
@ -320,15 +320,14 @@ public class IceSdpUtils
if(localCandidates == null || localCandidates.size() == 0) if(localCandidates == null || localCandidates.size() == 0)
{ {
trickleUpdate = new ArrayList<Attribute>(1); trickleUpdate = new ArrayList<>(1);
trickleUpdate.add( trickleUpdate.add(
sdpFactory.createAttribute(END_OF_CANDIDATES, null)); sdpFactory.createAttribute(END_OF_CANDIDATES, null));
return trickleUpdate; return trickleUpdate;
} }
trickleUpdate trickleUpdate = new ArrayList<>(localCandidates.size() + 1);
= new ArrayList<Attribute>(localCandidates.size() + 1);
String streamName = null; String streamName = null;

View File

@ -342,7 +342,7 @@ public abstract class Message
*/ */
//not sure this is the best solution but I'm trying to keep entry order //not sure this is the best solution but I'm trying to keep entry order
protected LinkedHashMap<Character, Attribute> attributes protected LinkedHashMap<Character, Attribute> attributes
= new LinkedHashMap<Character, Attribute>(); = new LinkedHashMap<>();
/** /**
* Attribute presentity is a thing of RFC 3489 and no longer exists in * Attribute presentity is a thing of RFC 3489 and no longer exists in
@ -619,7 +619,7 @@ public abstract class Message
{ {
synchronized(attributes) synchronized(attributes)
{ {
return new LinkedList<Attribute>(attributes.values()); return new LinkedList<>(attributes.values());
} }
} }
@ -941,8 +941,7 @@ public abstract class Message
offset += RFC3489_TRANSACTION_ID_LENGTH; offset += RFC3489_TRANSACTION_ID_LENGTH;
} }
Vector<Map.Entry<Character, Attribute>> v = Vector<Map.Entry<Character, Attribute>> v = new Vector<>();
new Vector<Map.Entry<Character, Attribute>>();
Iterator<Map.Entry<Character, Attribute>> iter = null; Iterator<Map.Entry<Character, Attribute>> iter = null;
char dataLengthForContentDependentAttribute = 0; char dataLengthForContentDependentAttribute = 0;

View File

@ -36,4 +36,4 @@ enum EnShutdown
* There was a forceful shutdown * There was a forceful shutdown
*/ */
SD_FORCEFUL SD_FORCEFUL
}; }

View File

@ -48,4 +48,4 @@ public enum Option
* Timeout in ms for write operations(0 - no timeout) * Timeout in ms for write operations(0 - no timeout)
*/ */
OPT_WRITE_TIMEOUT OPT_WRITE_TIMEOUT
}; }

View File

@ -174,7 +174,7 @@ public class PseudoTCPBase
* control flags. If segment contains any data it is stored in the receive * control flags. If segment contains any data it is stored in the receive
* buffer. * buffer.
*/ */
List<RSegment> m_rlist = new ArrayList<RSegment>(); List<RSegment> m_rlist = new ArrayList<>();
/** /**
* Last receive timestamp * Last receive timestamp
*/ */
@ -203,7 +203,7 @@ public class PseudoTCPBase
/** /**
* Outgoing segments list * Outgoing segments list
*/ */
List<SSegment> m_slist = new ArrayList<SSegment>(); List<SSegment> m_slist = new ArrayList<>();
/** /**
* Last send timestamp * Last send timestamp
*/ */
@ -429,7 +429,7 @@ public class PseudoTCPBase
// Check if it's time to retransmit a segment // Check if it's time to retransmit a segment
if (m_rto_base > 0 && (timeDiff(m_rto_base + m_rx_rto, now) <= 0)) if (m_rto_base > 0 && (timeDiff(m_rto_base + m_rx_rto, now) <= 0))
{ {
assert m_slist.isEmpty() == false; assert !m_slist.isEmpty();
// retransmit segments // retransmit segments
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
@ -1399,7 +1399,7 @@ public class PseudoTCPBase
Iterator<RSegment> iter = m_rlist.iterator(); Iterator<RSegment> iter = m_rlist.iterator();
List<RSegment> toBeRemoved = new ArrayList<RSegment>(); List<RSegment> toBeRemoved = new ArrayList<>();
while (iter.hasNext()) while (iter.hasNext())
{ {
RSegment it = iter.next(); RSegment it = iter.next();
@ -1903,7 +1903,7 @@ public class PseudoTCPBase
*/ */
boolean parseOptions(byte[] data, int offset, int len) boolean parseOptions(byte[] data, int offset, int len)
{ {
List<Short> options_specified = new ArrayList<Short>(); List<Short> options_specified = new ArrayList<>();
// See http://www.freesoft.org/CIE/Course/Section4/8.htm for // See http://www.freesoft.org/CIE/Course/Section4/8.htm for
// parsing the options list. // parsing the options list.

View File

@ -270,7 +270,7 @@ class PseudoTcpSocketImpl
throw new UnsupportedOperationException("Not supported yet."); throw new UnsupportedOperationException("Not supported yet.");
} }
private Map<Integer, Object> options = new HashMap<Integer,Object>(); private Map<Integer, Object> options = new HashMap<>();
public void setOption(int optID, Object value) public void setOption(int optID, Object value)
throws SocketException throws SocketException
{ {
@ -353,7 +353,7 @@ class PseudoTcpSocketImpl
synchronized (state_notify) synchronized (state_notify)
{ {
while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED
&& (noTimeout ? true : (elapsed < timeout)) ) && (noTimeout || (elapsed < timeout)) )
{ {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
state_notify.wait(timeout); state_notify.wait(timeout);

View File

@ -45,4 +45,4 @@ public enum PseudoTcpState
* TODO: closing procedure * TODO: closing procedure
*/ */
TCP_CLOSED// = 4; TCP_CLOSED// = 4;
}; }

View File

@ -24,5 +24,5 @@ package org.ice4j.pseudotcp;
*/ */
enum SendFlags enum SendFlags
{ {
sfNone, sfImmediateAck, sfDelayedAck; sfNone, sfImmediateAck, sfDelayedAck
} }

View File

@ -35,4 +35,4 @@ public enum WriteResult
* Write failed * Write failed
*/ */
WR_FAIL WR_FAIL
}; }

View File

@ -41,8 +41,7 @@ public class CredentialsManager
* The list of <tt>CredentialsAuthority</tt>s registered with this manager * The list of <tt>CredentialsAuthority</tt>s registered with this manager
* as being able to provide credentials. * as being able to provide credentials.
*/ */
private final List<CredentialsAuthority> authorities = private final List<CredentialsAuthority> authorities = new LinkedList<>();
new LinkedList<CredentialsAuthority>();
/** /**
* The list of <tt>CredentialsAuthority</tt>s registered with this manager * The list of <tt>CredentialsAuthority</tt>s registered with this manager

View File

@ -58,8 +58,7 @@ public class GoogleRelayedCandidateDelegate
* {@link #receive(DatagramPacket)} method. They have been received from the * {@link #receive(DatagramPacket)} method. They have been received from the
* TURN server in the form of Data indications. * TURN server in the form of Data indications.
*/ */
private final List<DatagramPacket> packetsToReceive = private final List<DatagramPacket> packetsToReceive = new LinkedList<>();
new LinkedList<DatagramPacket>();
/** /**
* The <tt>DatagramSocket</tt>s which have been sent through this * The <tt>DatagramSocket</tt>s which have been sent through this
@ -67,8 +66,7 @@ public class GoogleRelayedCandidateDelegate
* and which are to be relayed through its associated TURN server in the * and which are to be relayed through its associated TURN server in the
* form of Send indications. * form of Send indications.
*/ */
private final List<DatagramPacket> packetsToSend = private final List<DatagramPacket> packetsToSend = new LinkedList<>();
new LinkedList<DatagramPacket>();
/** /**
* The <tt>Thread</tt> which is to send the {@link #packetsToSend} to the * The <tt>Thread</tt> which is to send the {@link #packetsToSend} to the
@ -315,7 +313,7 @@ public class GoogleRelayedCandidateDelegate
{ {
synchronized (packetsToReceive) synchronized (packetsToReceive)
{ {
while (true) do
{ {
/* /*
* According to the javadoc of DatagramSocket#close(), any * According to the javadoc of DatagramSocket#close(), any
@ -337,7 +335,6 @@ public class GoogleRelayedCandidateDelegate
catch (InterruptedException iex) catch (InterruptedException iex)
{ {
} }
continue;
} }
else else
{ {
@ -348,6 +345,7 @@ public class GoogleRelayedCandidateDelegate
break; break;
} }
} }
while (true);
} }
} }

View File

@ -62,7 +62,7 @@ public class IceTcpServerSocketWrapper
/** /**
* List of TCP client sockets. * List of TCP client sockets.
*/ */
private final List<Socket> sockets = new ArrayList<Socket>(); private final List<Socket> sockets = new ArrayList<>();
/** /**
* Initializes a new <tt>IceTcpServerSocketWrapper</tt>. * Initializes a new <tt>IceTcpServerSocketWrapper</tt>.

View File

@ -570,7 +570,7 @@ abstract class MultiplexingXXXSocketSupport
if (socketFilter.accept(p)) if (socketFilter.accept(p))
{ {
if (toMove == null) if (toMove == null)
toMove = new LinkedList<DatagramPacket>(); toMove = new LinkedList<>();
toMove.add(p); toMove.add(p);
// XXX In the method receive, we allow multiple filters // XXX In the method receive, we allow multiple filters

View File

@ -112,7 +112,7 @@ public class RelayedCandidateDatagramSocket
* <tt>RelayedCandidateDatagramSocket</tt>s relays data send to it to * <tt>RelayedCandidateDatagramSocket</tt>s relays data send to it to
* peer <tt>TransportAddress</tt>es. * peer <tt>TransportAddress</tt>es.
*/ */
private final List<Channel> channels = new LinkedList<Channel>(); private final List<Channel> channels = new LinkedList<>();
/** /**
* The indicator which determines whether this instance has started * The indicator which determines whether this instance has started
@ -143,8 +143,7 @@ public class RelayedCandidateDatagramSocket
* {@link #receive(DatagramPacket)} method. They have been received from the * {@link #receive(DatagramPacket)} method. They have been received from the
* TURN server in the form of Data indications. * TURN server in the form of Data indications.
*/ */
private final List<DatagramPacket> packetsToReceive private final List<DatagramPacket> packetsToReceive = new LinkedList<>();
= new LinkedList<DatagramPacket>();
/** /**
* The <tt>DatagramSocket</tt>s which have been sent through this * The <tt>DatagramSocket</tt>s which have been sent through this
@ -152,8 +151,7 @@ public class RelayedCandidateDatagramSocket
* and which are to be relayed through its associated TURN server in the * and which are to be relayed through its associated TURN server in the
* form of Send indications. * form of Send indications.
*/ */
private final List<DatagramPacket> packetsToSend private final List<DatagramPacket> packetsToSend = new LinkedList<>();
= new LinkedList<DatagramPacket>();
/** /**
* The <tt>Thread</tt> which receives <tt>DatagramPacket</tt>s from * The <tt>Thread</tt> which receives <tt>DatagramPacket</tt>s from
@ -704,7 +702,7 @@ public class RelayedCandidateDatagramSocket
{ {
synchronized (packetsToReceive) synchronized (packetsToReceive)
{ {
while (true) do
{ {
/* /*
* According to the javadoc of DatagramSocket#close(), any * According to the javadoc of DatagramSocket#close(), any
@ -728,7 +726,6 @@ public class RelayedCandidateDatagramSocket
catch (InterruptedException iex) catch (InterruptedException iex)
{ {
} }
continue;
} }
else else
{ {
@ -739,6 +736,7 @@ public class RelayedCandidateDatagramSocket
break; break;
} }
} }
while (true);
} }
} }

View File

@ -65,7 +65,7 @@ public class RtcpDemuxPacketFilter
byte[] data = p.getData(); byte[] data = p.getData();
int off = p.getOffset(); int off = p.getOffset();
if (((data[off + 0] & 0xc0) >> 6) == 2) //RTP/RTCP version field if (((data[off] & 0xc0) >> 6) == 2) //RTP/RTCP version field
{ {
int pt = data[off + 1] & 0xff; int pt = data[off + 1] & 0xff;

View File

@ -39,7 +39,7 @@ public class EventDispatcher
* <tt>EventDispatcher</tt>. * <tt>EventDispatcher</tt>.
*/ */
private final List<MessageTypeEventHandler<?>> messageListeners private final List<MessageTypeEventHandler<?>> messageListeners
= new Vector<MessageTypeEventHandler<?>>(); = new Vector<>();
/** /**
* The <tt>Map</tt> of <tt>EventDispatcher</tt>s which keep the * The <tt>Map</tt> of <tt>EventDispatcher</tt>s which keep the
@ -48,7 +48,7 @@ public class EventDispatcher
* <tt>TransportAddress<tt>es. * <tt>TransportAddress<tt>es.
*/ */
private final Map<TransportAddress, EventDispatcher> children private final Map<TransportAddress, EventDispatcher> children
= new Hashtable<TransportAddress, EventDispatcher>(); = new Hashtable<>();
/** /**
* Initializes a new <tt>EventDispatcher</tt> instance. * Initializes a new <tt>EventDispatcher</tt> instance.

View File

@ -38,7 +38,7 @@ class MessageQueue
// not sure whether Vector is the best choice here since we explicitly // not sure whether Vector is the best choice here since we explicitly
//sync all methods ... review later //sync all methods ... review later
private Vector<RawMessage> queue = new Vector<RawMessage>(); private final Vector<RawMessage> queue = new Vector<>();
//keep a copy of the fifo size and make it accessible for concurrent //keep a copy of the fifo size and make it accessible for concurrent
// queries. // queries.

View File

@ -59,7 +59,7 @@ class NetAccessManager
*/ */
private final Map<TransportAddress, Map<TransportAddress, Connector>> private final Map<TransportAddress, Map<TransportAddress, Connector>>
udpConnectors udpConnectors
= new HashMap<TransportAddress, Map<TransportAddress, Connector>>(); = new HashMap<>();
/** /**
* All <tt>Connectors</tt> currently in use with TCP. The table maps a local * All <tt>Connectors</tt> currently in use with TCP. The table maps a local
@ -74,7 +74,7 @@ class NetAccessManager
*/ */
private final Map<TransportAddress, Map<TransportAddress, Connector>> private final Map<TransportAddress, Map<TransportAddress, Connector>>
tcpConnectors tcpConnectors
= new HashMap<TransportAddress, Map<TransportAddress, Connector>>(); = new HashMap<>();
/** /**
* A synchronized FIFO where incoming messages are stocked for processing. * A synchronized FIFO where incoming messages are stocked for processing.
@ -84,8 +84,7 @@ class NetAccessManager
/** /**
* A thread pool of message processors. * A thread pool of message processors.
*/ */
private Vector<MessageProcessor> messageProcessors private final Vector<MessageProcessor> messageProcessors = new Vector<>();
= new Vector<MessageProcessor>();
/** /**
* The instance that should be notified when an incoming message has been * The instance that should be notified when an incoming message has been
@ -332,8 +331,7 @@ class NetAccessManager
if (connectorsForLocalAddress == null) if (connectorsForLocalAddress == null)
{ {
connectorsForLocalAddress connectorsForLocalAddress = new HashMap<>();
= new HashMap<TransportAddress, Connector>();
connectorsMap.put(localAddress, connectorsForLocalAddress); connectorsMap.put(localAddress, connectorsForLocalAddress);
} }

View File

@ -81,7 +81,7 @@ public class StunStack
*/ */
private final Hashtable<TransactionID, StunClientTransaction> private final Hashtable<TransactionID, StunClientTransaction>
clientTransactions clientTransactions
= new Hashtable<TransactionID, StunClientTransaction>(); = new Hashtable<>();
/** /**
* The <tt>Thread</tt> which expires the <tt>StunServerTransaction</tt>s of * The <tt>Thread</tt> which expires the <tt>StunServerTransaction</tt>s of
@ -96,7 +96,7 @@ public class StunStack
*/ */
private final Hashtable<TransactionID, StunServerTransaction> private final Hashtable<TransactionID, StunServerTransaction>
serverTransactions serverTransactions
= new Hashtable<TransactionID, StunServerTransaction>(); = new Hashtable<>();
/** /**
* A dispatcher for incoming requests event; * A dispatcher for incoming requests event;
@ -310,8 +310,7 @@ public class StunStack
*/ */
if (clientTransactionsToCancel == null) if (clientTransactionsToCancel == null)
{ {
clientTransactionsToCancel clientTransactionsToCancel = new LinkedList<>();
= new LinkedList<StunClientTransaction>();
} }
clientTransactionsToCancel.add(tran); clientTransactionsToCancel.add(tran);
} }
@ -352,8 +351,7 @@ public class StunStack
if (serverTransactionsToExpire == null) if (serverTransactionsToExpire == null)
{ {
serverTransactionsToExpire serverTransactionsToExpire = new LinkedList<>();
= new LinkedList<StunServerTransaction>();
} }
serverTransactionsToExpire.add(tran); serverTransactionsToExpire.add(tran);
} }
@ -1079,8 +1077,7 @@ public class StunStack
synchronized (clientTransactions) synchronized (clientTransactions)
{ {
clientTransactionsToCancel clientTransactionsToCancel
= new ArrayList<StunClientTransaction>( = new ArrayList<>(clientTransactions.values());
clientTransactions.values());
clientTransactions.clear(); clientTransactions.clear();
} }
/* /*
@ -1097,8 +1094,7 @@ public class StunStack
synchronized (serverTransactions) synchronized (serverTransactions)
{ {
serverTransactionsToExpire serverTransactionsToExpire
= new ArrayList<StunServerTransaction>( = new ArrayList<>(serverTransactions.values());
serverTransactions.values());
serverTransactions.clear(); serverTransactions.clear();
} }
for (StunServerTransaction tran : serverTransactionsToExpire) for (StunServerTransaction tran : serverTransactionsToExpire)

View File

@ -131,8 +131,8 @@ public class TransactionID
for(int i = 0; i < b; i++) for(int i = 0; i < b; i++)
{ {
tid.transactionID[i] = (byte)((left >> (i * 8)) & 0xFFl); tid.transactionID[i] = (byte)((left >> (i * 8)) & 0xFFL);
tid.transactionID[i + b] = (byte)((right >> (i * 8)) & 0xFFl); tid.transactionID[i + b] = (byte)((right >> (i * 8)) & 0xFFL);
} }
//calculate hashcode for Hashtable storage. //calculate hashcode for Hashtable storage.

View File

@ -260,8 +260,7 @@ public class MessageEventDispatchingTest extends TestCase
private class PlainRequestCollector implements RequestListener private class PlainRequestCollector implements RequestListener
{ {
/** all requests we've received so far. */ /** all requests we've received so far. */
public Vector<StunMessageEvent> receivedRequests public final Vector<StunMessageEvent> receivedRequests = new Vector<>();
= new Vector<StunMessageEvent>();
/** /**
* Stores incoming requests. * Stores incoming requests.
@ -299,7 +298,7 @@ public class MessageEventDispatchingTest extends TestCase
private static class PlainResponseCollector private static class PlainResponseCollector
extends AbstractResponseCollector extends AbstractResponseCollector
{ {
public final Vector<Object> receivedResponses = new Vector<Object>(); public final Vector<Object> receivedResponses = new Vector<>();
/** /**
* Notifies this <tt>ResponseCollector</tt> that a transaction described by * Notifies this <tt>ResponseCollector</tt> that a transaction described by

View File

@ -515,7 +515,7 @@ public class TransactionSupportTests extends TestCase
* *
*/ */
private Vector<StunMessageEvent> receivedRequestsVector private Vector<StunMessageEvent> receivedRequestsVector
= new Vector<StunMessageEvent>(); = new Vector<>();
/** /**
* Logs the newly received request. * Logs the newly received request.
@ -543,7 +543,7 @@ public class TransactionSupportTests extends TestCase
*/ */
public Vector<StunMessageEvent> getRequestsForTransaction(byte[] tranid) public Vector<StunMessageEvent> getRequestsForTransaction(byte[] tranid)
{ {
Vector<StunMessageEvent> newVec = new Vector<StunMessageEvent>(); Vector<StunMessageEvent> newVec = new Vector<>();
for (StunMessageEvent evt : receivedRequestsVector) for (StunMessageEvent evt : receivedRequestsVector)
{ {
@ -581,7 +581,7 @@ public class TransactionSupportTests extends TestCase
/** /**
* The responses we've collected so far. * The responses we've collected so far.
*/ */
public final Vector<Object> receivedResponses = new Vector<Object>(); public final Vector<Object> receivedResponses = new Vector<>();
/** /**
* Notifies this <tt>ResponseCollector</tt> that a transaction described by * Notifies this <tt>ResponseCollector</tt> that a transaction described by

View File

@ -109,7 +109,7 @@ public class OptionalAttributeAttributeTest extends TestCase
assertEquals("failed null comparison", expectedReturn, actualReturn); assertEquals("failed null comparison", expectedReturn, actualReturn);
//wrong type comparison //wrong type comparison
obj = new String("hehe :)"); obj = "hehe :)";
actualReturn = optionalAttribute.equals(obj); actualReturn = optionalAttribute.equals(obj);
assertEquals("failed wrong type comparison", expectedReturn, assertEquals("failed wrong type comparison", expectedReturn,
actualReturn); actualReturn);

View File

@ -253,8 +253,8 @@ public class UnknownAttributesAttributeTest extends TestCase
Iterator<Character> iterator = unknownAttributesAttribute.getAttributes(); Iterator<Character> iterator = unknownAttributesAttribute.getAttributes();
actualId1 = iterator.next().charValue(); actualId1 = iterator.next();
actualId2 = iterator.next().charValue();; actualId2 = iterator.next();
assertEquals("getAttributes() return value mismatch", expectedId1, actualId1); assertEquals("getAttributes() return value mismatch", expectedId1, actualId1);
assertEquals("getAttributes() return value mismatch", expectedId2, actualId2); assertEquals("getAttributes() return value mismatch", expectedId2, actualId2);

View File

@ -67,8 +67,8 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
testDataSize = size; testDataSize = size;
long start, elapsed; long start, elapsed;
send_position = new ArrayList<Integer>(); send_position = new ArrayList<>();
recv_position = new ArrayList<Integer>(); recv_position = new ArrayList<>();
// Create some dummy data // Create some dummy data
byte[] dummy = createDummyData(size); byte[] dummy = createDummyData(size);
send_stream = new ByteFifoBuffer(size); send_stream = new ByteFifoBuffer(size);

View File

@ -46,7 +46,7 @@ public class ResponseSequenceServer
/** /**
* The sequence of responses to send. * The sequence of responses to send.
*/ */
private Vector<Object> messageSequence = new Vector<Object>(); private Vector<Object> messageSequence = new Vector<>();
/** /**
* The <tt>StunStack</tt> used by this instance for the purposes of STUN * The <tt>StunStack</tt> used by this instance for the purposes of STUN
@ -110,7 +110,7 @@ public class ResponseSequenceServer
if (response == null) if (response == null)
{ {
//leave a mark to skip a message //leave a mark to skip a message
messageSequence.add(new Boolean(false)); messageSequence.add(false);
} }
else else
messageSequence.add(response); messageSequence.add(response);

View File

@ -60,8 +60,7 @@ public class AwsTest
} }
AwsCandidateHarvester mch = new AwsCandidateHarvester(); AwsCandidateHarvester mch = new AwsCandidateHarvester();
List<CandidateHarvester> harvesters List<CandidateHarvester> harvesters = new ArrayList<>();
= new ArrayList<CandidateHarvester>();
harvesters.add(mch); harvesters.add(mch);
Agent localAgent = createAgent(2020, false, harvesters); Agent localAgent = createAgent(2020, false, harvesters);

View File

@ -97,7 +97,7 @@ public class IceDistributed
= new BufferedReader(new InputStreamReader(System.in)); = new BufferedReader(new InputStreamReader(System.in));
StringBuffer buff = new StringBuffer(); StringBuffer buff = new StringBuffer();
String line = new String(); String line;
while ( (line = reader.readLine()) != null) while ( (line = reader.readLine()) != null)
{ {

View File

@ -78,8 +78,7 @@ public class MappingTest
MappingCandidateHarvester natHarvester MappingCandidateHarvester natHarvester
= new MappingCandidateHarvester(publicAddress, localAddress); = new MappingCandidateHarvester(publicAddress, localAddress);
List<CandidateHarvester> harvesters List<CandidateHarvester> harvesters = new ArrayList<>();
= new ArrayList<CandidateHarvester>();
harvesters.add(natHarvester); harvesters.add(natHarvester);
Agent localAgent = createAgent(2020, false, harvesters); Agent localAgent = createAgent(2020, false, harvesters);

View File

@ -18,13 +18,11 @@
package test; package test;
import java.util.*; import java.util.*;
import java.util.StringTokenizer;
import javax.sdp.*; import javax.sdp.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.ice.Agent;
import org.ice4j.ice.sdp.*; import org.ice4j.ice.sdp.*;
/** /**

View File

@ -80,7 +80,7 @@ public class TrickleIce
localAgent.startCandidateTrickle(printer); localAgent.startCandidateTrickle(printer);
List<Component> allComponents = new LinkedList<Component>(); List<Component> allComponents = new LinkedList<>();
int allCandidates = 0; int allCandidates = 0;
for (IceMediaStream stream : localAgent.getStreams()) for (IceMediaStream stream : localAgent.getStreams())
{ {
@ -139,7 +139,7 @@ public class TrickleIce
if(iceCandidates == null) if(iceCandidates == null)
{ {
try{Thread.sleep(1000);}catch(Exception e){}; try{Thread.sleep(1000);}catch(Exception e){}
logger.info("ICE stats: time=" logger.info("ICE stats: time="
+ agent.getTotalHarvestingTime() + "ms"); + agent.getTotalHarvestingTime() + "ms");