proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LazyEscapingCharSequence.java
|
LazyEscapingCharSequence
|
produceEscapedOutput
|
class LazyEscapingCharSequence extends AbstractLazyCharSequence {
private final IEngineConfiguration configuration;
private final TemplateMode templateMode;
private final Object input;
public LazyEscapingCharSequence(final IEngineConfiguration configuration, final TemplateMode templateMode, final Object input) {
super();
if (configuration == null) {
throw new IllegalArgumentException("Engine Configuraion is null, which is forbidden");
}
if (templateMode == null) {
throw new IllegalArgumentException("Template Mode is null, which is forbidden");
}
this.configuration = configuration;
this.templateMode = templateMode;
this.input = input;
}
@Override
protected String resolveText() {
final Writer stringWriter = new FastStringWriter();
produceEscapedOutput(stringWriter);
return stringWriter.toString();
}
@Override
protected void writeUnresolved(final Writer writer) throws IOException {
produceEscapedOutput(writer);
}
private void produceEscapedOutput(final Writer writer) {<FILL_FUNCTION_BODY>}
}
|
/*
* Producing ESCAPED output is somewhat simple in HTML or XML modes, as it simply consists of converting
* input into a String and HTML-or-XML-escaping it.
*
* But for JavaScript or CSS, it becomes a bit more complicated than that. JavaScript will output a complete
* literal (incl. single quotes) if input is a String or a non-recognized value type, but will print input
* as an object, number, boolean, etc. if it is recognized to be of one of these types. CSS will output
* quoted literals.
*
* Note that, when in TEXT mode, HTML escaping will be used (as TEXT is many times used for
* processing HTML templates)
*/
try {
switch (templateMode) {
case TEXT:
// fall-through
case HTML:
if (this.input != null) {
HtmlEscape.escapeHtml4Xml(this.input.toString(), writer);
}
return;
case XML:
if (this.input != null) {
// Note we are outputting a body content here, so it is important that we use the version
// of XML escaping meant for content, not attributes (slight differences)
XmlEscape.escapeXml10(this.input.toString(), writer);
}
return;
case JAVASCRIPT:
final IStandardJavaScriptSerializer javaScriptSerializer = StandardSerializers.getJavaScriptSerializer(this.configuration);
javaScriptSerializer.serializeValue(this.input, writer);
return;
case CSS:
final IStandardCSSSerializer cssSerializer = StandardSerializers.getCSSSerializer(this.configuration);
cssSerializer.serializeValue(this.input, writer);
return;
case RAW:
if (this.input != null) {
writer.write(this.input.toString());
}
return;
default:
throw new TemplateProcessingException(
"Unrecognized template mode " + templateMode + ". Cannot produce escaped output for " +
"this template mode.");
}
} catch (final IOException e) {
throw new TemplateProcessingException("An error happened while trying to produce escaped output", e);
}
| 288
| 552
| 840
|
<methods>public final char charAt(int) ,public final boolean equals(java.lang.Object) ,public final int hashCode() ,public final int length() ,public final java.lang.CharSequence subSequence(int, int) ,public final java.lang.String toString() ,public final void write(java.io.Writer) throws java.io.IOException<variables>private java.lang.String resolvedText
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LazyProcessingCharSequence.java
|
LazyProcessingCharSequence
|
resolveText
|
class LazyProcessingCharSequence extends AbstractLazyCharSequence {
private final ITemplateContext context;
private final TemplateModel templateModel;
public LazyProcessingCharSequence(final ITemplateContext context, final TemplateModel templateModel) {
super();
if (context == null) {
throw new IllegalArgumentException("Template Context is null, which is forbidden");
}
if (templateModel == null) {
throw new IllegalArgumentException("Template Model is null, which is forbidden");
}
this.context = context;
this.templateModel = templateModel;
}
@Override
protected String resolveText() {<FILL_FUNCTION_BODY>}
@Override
protected void writeUnresolved(final Writer writer) throws IOException {
this.context.getConfiguration().getTemplateManager().process(this.templateModel, this.context, writer);
}
}
|
final Writer stringWriter = new FastStringWriter();
this.context.getConfiguration().getTemplateManager().process(this.templateModel, this.context, stringWriter);
return stringWriter.toString();
| 231
| 51
| 282
|
<methods>public final char charAt(int) ,public final boolean equals(java.lang.Object) ,public final int hashCode() ,public final int length() ,public final java.lang.CharSequence subSequence(int, int) ,public final java.lang.String toString() ,public final void write(java.io.Writer) throws java.io.IOException<variables>private java.lang.String resolvedText
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/ListUtils.java
|
ListUtils
|
sort
|
class ListUtils {
public static List<?> toList(final Object target) {
Validate.notNull(target, "Cannot convert null to list");
if (target instanceof List<?>) {
return (List<?>) target;
}
if (target.getClass().isArray()) {
return new ArrayList<Object>(Arrays.asList((Object[])target));
}
if (target instanceof Iterable<?>) {
final List<Object> elements = new ArrayList<Object>(10);
for (final Object element : (Iterable<?>)target) {
elements.add(element);
}
return elements;
}
throw new IllegalArgumentException(
"Cannot convert object of class \"" + target.getClass().getName() + "\" to a list");
}
public static int size(final List<?> target) {
Validate.notNull(target, "Cannot get list size of null");
return target.size();
}
public static boolean isEmpty(final List<?> target) {
return target == null || target.isEmpty();
}
public static boolean contains(final List<?> target, final Object element) {
Validate.notNull(target, "Cannot execute list contains: target is null");
return target.contains(element);
}
public static boolean containsAll(final List<?> target, final Object[] elements) {
Validate.notNull(target, "Cannot execute list containsAll: target is null");
Validate.notNull(elements, "Cannot execute list containsAll: elements is null");
return containsAll(target, Arrays.asList(elements));
}
public static boolean containsAll(final List<?> target, final Collection<?> elements) {
Validate.notNull(target, "Cannot execute list contains: target is null");
Validate.notNull(elements, "Cannot execute list containsAll: elements is null");
return target.containsAll(elements);
}
/**
* <p>
* Creates an new instance of the list add the sorted list to it.
* </p>
*
* @param list the list which content should be ordered.
* @param <T> the type of the list elements.
* @return a new sorted list.
* @see java.util.Collections#sort(List)
*/
public static <T extends Comparable<? super T>> List<T> sort(final List<T> list) {
Validate.notNull(list, "Cannot execute list sort: list is null");
final Object[] a = list.toArray();
Arrays.sort(a);
return fillNewList(a, list.getClass());
}
/**
* <p>
* Creates an new instance of the list add the sorted list to it.
* </p>
*
* @param list the list which content should be ordered.
* @param c the comparator.
* @param <T> the type of the list elements.
* @return a new sorted list.
* @see java.util.Collections#sort(List, Comparator)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> List<T> sort(final List<T> list, final Comparator<? super T> c) {<FILL_FUNCTION_BODY>}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> List<T> fillNewList(
final Object[] a, final Class<? extends List> listType) {
List<T> newList;
try {
newList = listType.getConstructor().newInstance();
} catch (final Exception e) {
newList = new ArrayList<T>(a.length + 2);
}
for (final Object object : a) {
newList.add((T)object);
}
return newList;
}
private ListUtils() {
super();
}
}
|
Validate.notNull(list, "Cannot execute list sort: list is null");
final Object[] a = list.toArray();
Arrays.sort(a, (Comparator) c);
return fillNewList(a, list.getClass());
| 1,054
| 67
| 1,121
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LoggingUtils.java
|
LoggingUtils
|
loggifyTemplateName
|
class LoggingUtils {
public static String loggifyTemplateName(final String template) {<FILL_FUNCTION_BODY>}
private LoggingUtils() {
super();
}
}
|
if (template == null) {
return null;
}
if (template.length() <= 120) {
return template.replace('\n', ' ');
}
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(template.substring(0, 35).replace('\n', ' '));
strBuilder.append("[...]");
strBuilder.append(template.substring(template.length() - 80).replace('\n', ' '));
return strBuilder.toString();
| 64
| 135
| 199
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/MapUtils.java
|
MapUtils
|
containsAllKeys
|
class MapUtils {
public static int size(final Map<?,?> target) {
Validate.notNull(target, "Cannot get map size of null");
return target.size();
}
public static boolean isEmpty(final Map<?,?> target) {
return target == null || target.isEmpty();
}
public static <X> boolean containsKey(final Map<? super X,?> target, final X key) {
Validate.notNull(target, "Cannot execute map containsKey: target is null");
return target.containsKey(key);
}
public static <X> boolean containsAllKeys(final Map<? super X,?> target, final X[] keys) {
Validate.notNull(target, "Cannot execute map containsAllKeys: target is null");
Validate.notNull(keys, "Cannot execute map containsAllKeys: keys is null");
return containsAllKeys(target, Arrays.asList(keys));
}
public static <X> boolean containsAllKeys(final Map<? super X,?> target, final Collection<X> keys) {<FILL_FUNCTION_BODY>}
public static <X> boolean containsValue(final Map<?,? super X> target, final X value) {
Validate.notNull(target, "Cannot execute map containsValue: target is null");
return target.containsValue(value);
}
public static <X> boolean containsAllValues(final Map<?,? super X> target, final X[] values) {
Validate.notNull(target, "Cannot execute map containsAllValues: target is null");
Validate.notNull(values, "Cannot execute map containsAllValues: values is null");
return containsAllValues(target, Arrays.asList(values));
}
public static <X> boolean containsAllValues(final Map<?,? super X> target, final Collection<X> values) {
Validate.notNull(target, "Cannot execute map containsAllValues: target is null");
Validate.notNull(values, "Cannot execute map containsAllValues: values is null");
return target.values().containsAll(values);
}
private MapUtils() {
super();
}
}
|
Validate.notNull(target, "Cannot execute map containsAllKeys: target is null");
Validate.notNull(keys, "Cannot execute map containsAllKeys: keys is null");
return target.keySet().containsAll(keys);
| 569
| 61
| 630
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/PatternSpec.java
|
PatternSpec
|
matches
|
class PatternSpec {
private static final int DEFAULT_PATTERN_SET_SIZE = 3;
private LinkedHashSet<String> patternStrs;
private LinkedHashSet<Pattern> patterns;
public PatternSpec() {
super();
}
public boolean isEmpty() {
return this.patterns == null || this.patterns.size() == 0;
}
public Set<String> getPatterns() {
if (this.patternStrs == null) {
return Collections.EMPTY_SET;
}
return Collections.unmodifiableSet(this.patternStrs);
}
public void setPatterns(final Set<String> newPatterns) {
if (newPatterns != null) {
if (this.patterns == null) {
this.patternStrs = new LinkedHashSet<String>(DEFAULT_PATTERN_SET_SIZE);
this.patterns = new LinkedHashSet<Pattern>(DEFAULT_PATTERN_SET_SIZE);
} else {
this.patternStrs.clear();
this.patterns.clear();
}
this.patternStrs.addAll(newPatterns);
for (final String pattern : newPatterns) {
this.patterns.add(PatternUtils.strPatternToPattern(pattern));
}
} else if (this.patterns != null) {
this.patternStrs.clear();
this.patterns.clear();
}
}
public void addPattern(final String pattern) {
Validate.notEmpty(pattern, "Pattern cannot be null or empty");
if (this.patterns == null) {
this.patternStrs = new LinkedHashSet<String>(DEFAULT_PATTERN_SET_SIZE);
this.patterns = new LinkedHashSet<Pattern>(DEFAULT_PATTERN_SET_SIZE);
}
this.patternStrs.add(pattern);
this.patterns.add(PatternUtils.strPatternToPattern(pattern));
}
public void clearPatterns() {
if (this.patterns != null) {
this.patternStrs.clear();
this.patterns.clear();
}
}
public boolean matches(final String templateName) {<FILL_FUNCTION_BODY>}
}
|
if (this.patterns == null) {
return false;
}
for (final Pattern p : this.patterns) {
if (p.matcher(templateName).matches()) {
return true;
}
}
return false;
| 613
| 70
| 683
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/PatternUtils.java
|
PatternUtils
|
strPatternToPattern
|
class PatternUtils {
public static Pattern strPatternToPattern(final String pattern) {<FILL_FUNCTION_BODY>}
private PatternUtils() {
super();
}
}
|
final String pat =
pattern.replace(".", "\\.").replace("(", "\\(").replace(")", "\\)").
replace("[","\\[").replace("]","\\]").replace("?","\\?").replace("$","\\$").replace("+","\\+").
replace("*","(?:.*?)");
return Pattern.compile('^' + pat + '$');
| 64
| 99
| 163
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/ProcessorComparators.java
|
PreProcessorPrecedenceComparator
|
compare
|
class PreProcessorPrecedenceComparator implements Comparator<IPreProcessor> {
PreProcessorPrecedenceComparator() {
super();
}
public int compare(final IPreProcessor o1, final IPreProcessor o2) {<FILL_FUNCTION_BODY>}
/*
* Processors are wrapped and therefore we can apply dialect precedence
*/
private int compareWrapped(final ProcessorConfigurationUtils.PreProcessorWrapper o1w, final ProcessorConfigurationUtils.PreProcessorWrapper o2w) {
final int dialectPrecedenceComp = compareInts(o1w.getDialect().getDialectProcessorPrecedence(), o2w.getDialect().getDialectProcessorPrecedence());
if (dialectPrecedenceComp != 0) {
return dialectPrecedenceComp;
}
final IPreProcessor o1 = o1w.unwrap();
final IPreProcessor o2 = o2w.unwrap();
final int processorPrecedenceComp = compareInts(o1.getPrecedence(), o2.getPrecedence());
if (processorPrecedenceComp != 0) {
return processorPrecedenceComp;
}
final int classNameComp = o1.getClass().getName().compareTo(o2.getClass().getName());
if (classNameComp != 0) {
return classNameComp;
}
return compareInts(System.identityHashCode(o1), System.identityHashCode(o2)); // Cannot be 0
}
private static int compareInts(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
|
if (o1 == o2) {
// This is the only case in which the comparison of two processors will return 0
return 0;
}
if (o1 instanceof ProcessorConfigurationUtils.PreProcessorWrapper && o2 instanceof ProcessorConfigurationUtils.PreProcessorWrapper) {
return compareWrapped((ProcessorConfigurationUtils.PreProcessorWrapper)o1, (ProcessorConfigurationUtils.PreProcessorWrapper)o2);
}
final int preProcessorPrecedenceComp = compareInts(o1.getPrecedence(), o2.getPrecedence());
if (preProcessorPrecedenceComp != 0) {
return preProcessorPrecedenceComp;
}
final int classNameComp = o1.getClass().getName().compareTo(o2.getClass().getName());
if (classNameComp != 0) {
return classNameComp;
}
return compareInts(System.identityHashCode(o1), System.identityHashCode(o2)); // Cannot be 0
| 432
| 240
| 672
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/SetUtils.java
|
SetUtils
|
toSet
|
class SetUtils {
public static Set<?> toSet(final Object target) {<FILL_FUNCTION_BODY>}
public static int size(final Set<?> target) {
Validate.notNull(target, "Cannot get set size of null");
return target.size();
}
public static boolean isEmpty(final Set<?> target) {
return target == null || target.isEmpty();
}
public static boolean contains(final Set<?> target, final Object element) {
Validate.notNull(target, "Cannot execute set contains: target is null");
return target.contains(element);
}
public static boolean containsAll(final Set<?> target, final Object[] elements) {
Validate.notNull(target, "Cannot execute set containsAll: target is null");
Validate.notNull(elements, "Cannot execute set containsAll: elements is null");
return containsAll(target, Arrays.asList(elements));
}
public static boolean containsAll(final Set<?> target, final Collection<?> elements) {
Validate.notNull(target, "Cannot execute set contains: target is null");
Validate.notNull(elements, "Cannot execute set containsAll: elements is null");
return target.containsAll(elements);
}
public static <X> Set<X> singletonSet(final X element) {
final Set<X> set = new HashSet<X>(2, 1.0f);
set.add(element);
return Collections.unmodifiableSet(set);
}
private SetUtils() {
super();
}
}
|
Validate.notNull(target, "Cannot convert null to set");
if (target instanceof Set<?>) {
return (Set<?>) target;
}
if (target.getClass().isArray()) {
return new LinkedHashSet<Object>(Arrays.asList((Object[])target));
}
if (target instanceof Iterable<?>) {
final Set<Object> elements = new LinkedHashSet<Object>();
for (final Object element : (Iterable<?>)target) {
elements.add(element);
}
return elements;
}
throw new IllegalArgumentException(
"Cannot convert object of class \"" + target.getClass().getName() + "\" to a set");
| 438
| 195
| 633
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/Validate.java
|
Validate
|
notEmpty
|
class Validate {
public static void notNull(final Object object, final String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
public static void notEmpty(final String object, final String message) {
if (StringUtils.isEmptyOrWhitespace(object)) {
throw new IllegalArgumentException(message);
}
}
public static void notEmpty(final Collection<?> object, final String message) {<FILL_FUNCTION_BODY>}
public static void notEmpty(final Object[] object, final String message) {
if (object == null || object.length == 0) {
throw new IllegalArgumentException(message);
}
}
public static void containsNoNulls(final Iterable<?> collection, final String message) {
for (final Object object : collection) {
notNull(object, message);
}
}
public static void containsNoEmpties(final Iterable<String> collection, final String message) {
for (final String object : collection) {
notEmpty(object, message);
}
}
public static void containsNoNulls(final Object[] array, final String message) {
for (final Object object : array) {
notNull(object, message);
}
}
public static void isTrue(final boolean condition, final String message) {
if (!condition) {
throw new IllegalArgumentException(message);
}
}
private Validate() {
super();
}
}
|
if (object == null || object.size() == 0) {
throw new IllegalArgumentException(message);
}
| 397
| 31
| 428
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalArrayUtils.java
|
TemporalArrayUtils
|
arrayFormat
|
class TemporalArrayUtils {
private final TemporalFormattingUtils temporalFormattingUtils;
public TemporalArrayUtils(final Locale locale, final ZoneId defaultZoneId) {
super();
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(defaultZoneId, "ZoneId cannot be null");
temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId);
}
public String[] arrayFormat(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::format, String.class);
}
public String[] arrayFormat(final Object[] target, final Locale locale) {
return arrayFormat(target, time -> temporalFormattingUtils.format(time, locale), String.class);
}
public String[] arrayFormat(final Object[] target, final String pattern) {
return arrayFormat(target, time -> temporalFormattingUtils.format(time, pattern, null), String.class);
}
public String[] arrayFormat(final Object[] target, final String pattern, final Locale locale) {
return arrayFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null), String.class);
}
public Integer[] arrayDay(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::day, Integer.class);
}
public Integer[] arrayMonth(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::month, Integer.class);
}
public String[] arrayMonthName(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::monthName, String.class);
}
public String[] arrayMonthNameShort(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::monthNameShort, String.class);
}
public Integer[] arrayYear(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::year, Integer.class);
}
public Integer[] arrayDayOfWeek(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::dayOfWeek, Integer.class);
}
public String[] arrayDayOfWeekName(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::dayOfWeekName, String.class);
}
public String[] arrayDayOfWeekNameShort(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::dayOfWeekNameShort, String.class);
}
public Integer[] arrayHour(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::hour, Integer.class);
}
public Integer[] arrayMinute(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::minute, Integer.class);
}
public Integer[] arraySecond(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::second, Integer.class);
}
public Integer[] arrayNanosecond(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::nanosecond, Integer.class);
}
public String[] arrayFormatISO(final Object[] target) {
return arrayFormat(target, temporalFormattingUtils::formatISO, String.class);
}
private <R extends Object> R[] arrayFormat(
final Object[] target, final Function<Object, R> mapFunction, final Class<R> returnType) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(target, "Target cannot be null");
return Stream.of(target)
.map(time -> mapFunction.apply(time))
.toArray(length -> (R[]) Array.newInstance(returnType, length));
| 876
| 66
| 942
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalCreationUtils.java
|
TemporalCreationUtils
|
zoneId
|
class TemporalCreationUtils {
public TemporalCreationUtils() {
super();
}
/**
*
* @return a instance of java.time.LocalDate
* @since 2.1.0
*/
public Temporal create(final Object year, final Object month, final Object day) {
return LocalDate.of(integer(year), integer(month), integer(day));
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal create(final Object year, final Object month, final Object day,
final Object hour, final Object minute) {
return LocalDateTime.of(integer(year), integer(month), integer(day), integer(hour), integer(minute));
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal create(final Object year, final Object month, final Object day,
final Object hour, final Object minute, final Object second) {
return LocalDateTime.of(integer(year), integer(month), integer(day),
integer(hour), integer(minute), integer(second));
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal create(final Object year, final Object month, final Object day,
final Object hour, final Object minute, final Object second, final Object nanosecond) {
return LocalDateTime.of(integer(year), integer(month), integer(day),
integer(hour), integer(minute), integer(second), integer(nanosecond));
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal createNow() {
return LocalDateTime.now();
}
/**
*
* @return a instance of java.time.ZonedDateTime
* @since 2.1.0
*/
public Temporal createNowForTimeZone(final Object zoneId) {
return ZonedDateTime.now(zoneId(zoneId));
}
/**
*
* @return a instance of java.time.LocalDate
* @since 2.1.0
*/
public Temporal createToday() {
return LocalDate.now();
}
/**
*
* @return a instance of java.time.ZonedDateTime with 00:00:00.000 for the time part
* @since 2.1.0
*/
public Temporal createTodayForTimeZone(final Object zoneId) {
return ZonedDateTime.now(zoneId(zoneId))
.withHour(0).withMinute(0).withSecond(0).withNano(0);
}
/**
*
* @return a instance of java.time.LocalDate
* @since 2.1.0
*/
public Temporal createDate(String isoDate) {
return LocalDate.parse(isoDate);
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal createDateTime(String isoDate) {
return LocalDateTime.parse(isoDate);
}
/**
*
* @return a instance of java.time.LocalDate
* @since 2.1.0
*/
public Temporal createDate(String isoDate, String pattern) {
return LocalDate.parse(isoDate, DateTimeFormatter.ofPattern(pattern));
}
/**
*
* @return a instance of java.time.LocalDateTime
* @since 2.1.0
*/
public Temporal createDateTime(String isoDate, String pattern) {
return LocalDateTime.parse(isoDate, DateTimeFormatter.ofPattern(pattern));
}
private int integer(final Object number) {
Validate.notNull(number, "Argument cannot be null");
return EvaluationUtils.evaluateAsNumber(number).intValue();
}
private ZoneId zoneId(final Object zoneId) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(zoneId, "ZoneId cannot be null");
if (zoneId instanceof ZoneId) {
return (ZoneId) zoneId;
} else if (zoneId instanceof TimeZone) {
TimeZone timeZone = (TimeZone) zoneId;
return timeZone.toZoneId();
} else {
return ZoneId.of(zoneId.toString());
}
| 1,088
| 100
| 1,188
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalFormattingUtils.java
|
TemporalFormattingUtils
|
formatDate
|
class TemporalFormattingUtils {
// Even though Java comes with several patterns for ISO8601, we use the same pattern of Thymeleaf #dates utility.
private static final DateTimeFormatter ISO8601_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
private final Locale locale;
private final ZoneId defaultZoneId;
public TemporalFormattingUtils(final Locale locale, final ZoneId defaultZoneId) {
super();
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(defaultZoneId, "ZoneId cannot be null");
this.locale = locale;
this.defaultZoneId = defaultZoneId;
}
public String format(final Object target) {
return formatDate(target);
}
public String format(final Object target, final Locale locale) {
Validate.notNull(locale, "Locale cannot be null");
return formatDate(target, null, locale, null);
}
public String format(final Object target, final String pattern, final ZoneId zoneId) {
return format(target, pattern, null, zoneId);
}
public String format(final Object target, final String pattern, final Locale locale, final ZoneId zoneId) {
Validate.notEmpty(pattern, "Pattern cannot be null or empty");
return formatDate(target, pattern, locale, zoneId);
}
public Integer day(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.DAY_OF_MONTH));
}
public Integer month(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.MONTH_OF_YEAR));
}
public String monthName(final Object target) {
return format(target, "MMMM", null);
}
public String monthNameShort(final Object target) {
return format(target, "MMM", null);
}
public Integer year(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.YEAR));
}
public Integer dayOfWeek(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.DAY_OF_WEEK));
}
public String dayOfWeekName(final Object target) {
return format(target, "EEEE", null);
}
public String dayOfWeekNameShort(final Object target) {
return format(target, "EEE", null);
}
public Integer hour(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.HOUR_OF_DAY));
}
public Integer minute(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.MINUTE_OF_HOUR));
}
public Integer second(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.SECOND_OF_MINUTE));
}
public Integer nanosecond(final Object target) {
if (target == null) {
return null;
}
final TemporalAccessor time = TemporalObjects.temporal(target);
return Integer.valueOf(time.get(ChronoField.NANO_OF_SECOND));
}
public String formatISO(final Object target) {
if (target == null) {
return null;
} else if (target instanceof TemporalAccessor) {
ChronoZonedDateTime time = TemporalObjects.zonedTime(target, defaultZoneId);
return ISO8601_DATE_TIME_FORMATTER.withLocale(locale).format(time);
} else {
throw new IllegalArgumentException(
"Cannot format object of class \"" + target.getClass().getName() + "\" as a date");
}
}
private String formatDate(final Object target) {
return formatDate(target, null, null, null);
}
private String formatDate(final Object target, final String pattern, final Locale localeOverride, final ZoneId zoneId) {<FILL_FUNCTION_BODY>}
private static DateTimeFormatter computeFormatter(final String pattern, final Class<?> targetClass,
final Locale locale, final ZoneId zoneId) {
final FormatStyle formatStyle;
switch (pattern) {
case "SHORT" : formatStyle = FormatStyle.SHORT; break;
case "MEDIUM" : formatStyle = FormatStyle.MEDIUM; break;
case "LONG" : formatStyle = FormatStyle.LONG; break;
case "FULL" : formatStyle = FormatStyle.FULL; break;
default : formatStyle = null; break;
}
if (formatStyle != null) {
if (LocalDate.class.isAssignableFrom(targetClass)) {
return DateTimeFormatter.ofLocalizedDate(formatStyle).withLocale(locale);
}
if (LocalTime.class.isAssignableFrom(targetClass)) {
return DateTimeFormatter.ofLocalizedTime(formatStyle).withLocale(locale);
}
return DateTimeFormatter.ofLocalizedDateTime(formatStyle).withLocale(locale);
}
return DateTimeFormatter.ofPattern(pattern, locale).withZone(zoneId);
}
}
|
if (target == null) {
return null;
}
Locale formattingLocale = localeOverride != null ? localeOverride : this.locale;
try {
DateTimeFormatter formatter;
if (StringUtils.isEmptyOrWhitespace(pattern)) {
formatter = TemporalObjects.formatterFor(target, formattingLocale);
return formatter.format(TemporalObjects.temporal(target));
} else {
formatter = computeFormatter(pattern, target.getClass(), formattingLocale, zoneId);
return formatter.format(TemporalObjects.zonedTime(target, this.defaultZoneId));
}
} catch (final Exception e) {
throw new TemplateProcessingException(
"Error formatting date for locale " + formattingLocale, e);
}
| 1,627
| 207
| 1,834
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalListUtils.java
|
TemporalListUtils
|
listFormat
|
class TemporalListUtils {
private final TemporalFormattingUtils temporalFormattingUtils;
public TemporalListUtils(final Locale locale, final ZoneId defaultZoneId) {
super();
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(defaultZoneId, "ZoneId cannot be null");
temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId);
}
public List<String> listFormat(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::format);
}
public <T extends Temporal> List<String> listFormat(final List<T> target, final Locale locale) {
return listFormat(target, time -> temporalFormattingUtils.format(time, locale));
}
public <T extends Temporal> List<String> listFormat(final List<T> target, final String pattern) {
return listFormat(target, time -> temporalFormattingUtils.format(time, pattern, null));
}
public <T extends Temporal> List<String> listFormat(final List<T> target, final String pattern, final Locale locale) {
return listFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null));
}
public List<Integer> listDay(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::day);
}
public List<Integer> listMonth(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::month);
}
public List<String> listMonthName(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::monthName);
}
public List<String> listMonthNameShort(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::monthNameShort);
}
public List<Integer> listYear(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::year);
}
public List<Integer> listDayOfWeek(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::dayOfWeek);
}
public List<String> listDayOfWeekName(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::dayOfWeekName);
}
public List<String> listDayOfWeekNameShort(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::dayOfWeekNameShort);
}
public List<Integer> listHour(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::hour);
}
public List<Integer> listMinute(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::minute);
}
public List<Integer> listSecond(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::second);
}
public List<Integer> listNanosecond(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::nanosecond);
}
public List<String> listFormatISO(final List<? extends Temporal> target) {
return listFormat(target, temporalFormattingUtils::formatISO);
}
private <R extends Object, T extends Temporal> List<R> listFormat(
final List<T> target, final Function<T, R> mapFunction) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(target, "Target cannot be null");
return target.stream()
.map(time -> mapFunction.apply(time))
.collect(toList());
| 961
| 49
| 1,010
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalObjects.java
|
TemporalObjects
|
formatterFor
|
class TemporalObjects {
public TemporalObjects() {
super();
}
public static DateTimeFormatter formatterFor(final Object target, final Locale locale) {<FILL_FUNCTION_BODY>}
/**
* Creates a Temporal object filling the missing fields of the provided time with default values.
* @param target the temporal object to be converted
* @param defaultZoneId the default value for ZoneId
* @return a Temporal object
*/
public static ChronoZonedDateTime zonedTime(final Object target, final ZoneId defaultZoneId) {
Validate.notNull(target, "Target cannot be null");
Validate.notNull(defaultZoneId, "ZoneId cannot be null");
if (target instanceof Instant) {
return ZonedDateTime.ofInstant((Instant) target, defaultZoneId);
} else if (target instanceof LocalDate) {
return ZonedDateTime.of((LocalDate) target, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof LocalDateTime) {
return ZonedDateTime.of((LocalDateTime) target, defaultZoneId);
} else if (target instanceof LocalTime) {
return ZonedDateTime.of(LocalDate.now(), (LocalTime) target, defaultZoneId);
} else if (target instanceof OffsetDateTime) {
return ((OffsetDateTime) target).toZonedDateTime();
} else if (target instanceof OffsetTime) {
LocalTime localTime = ((OffsetTime) target).toLocalTime();
return ZonedDateTime.of(LocalDate.now(), localTime, defaultZoneId);
} else if (target instanceof Year) {
LocalDate localDate = ((Year) target).atDay(1);
return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof YearMonth) {
LocalDate localDate = ((YearMonth) target).atDay(1);
return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
} else if (target instanceof ZonedDateTime) {
return (ChronoZonedDateTime) target;
} else {
throw new IllegalArgumentException(
"Cannot format object of class \"" + target.getClass().getName() + "\" as a date");
}
}
public static TemporalAccessor temporal(final Object target) {
Validate.notNull(target, "Target cannot be null");
if (target instanceof TemporalAccessor) {
return (TemporalAccessor) target;
} else {
throw new IllegalArgumentException(
"Cannot normalize class \"" + target.getClass().getName() + "\" as a date");
}
}
private static DateTimeFormatter yearMonthFormatter(final Locale locale) {
if (shouldDisplayYearBeforeMonth(locale)) {
return new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR)
.appendLiteral(' ')
.appendText(ChronoField.MONTH_OF_YEAR)
.toFormatter()
.withLocale(locale);
} else {
return new DateTimeFormatterBuilder()
.appendText(ChronoField.MONTH_OF_YEAR)
.appendLiteral(' ')
.appendValue(ChronoField.YEAR)
.toFormatter()
.withLocale(locale);
}
}
private static boolean shouldDisplayYearBeforeMonth(final Locale locale) {
// We use "Month Year" or "Year Month" depending on the locale according to https://en.wikipedia.org/wiki/Date_format_by_country
String country = locale.getCountry();
switch (country) {
case "BT" :
case "CA" :
case "CN" :
case "KP" :
case "KR" :
case "TW" :
case "HU" :
case "IR" :
case "JP" :
case "LT" :
case "MN" :
return true;
default:
return false;
}
}
}
|
Validate.notNull(target, "Target cannot be null");
Validate.notNull(locale, "Locale cannot be null");
if (target instanceof Instant) {
return new DateTimeFormatterBuilder().appendInstant().toFormatter();
} else if (target instanceof LocalDate) {
return DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale);
} else if (target instanceof LocalDateTime) {
return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.MEDIUM).withLocale(locale);
} else if (target instanceof LocalTime) {
return DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).withLocale(locale);
} else if (target instanceof OffsetDateTime) {
return new DateTimeFormatterBuilder()
.appendLocalized(FormatStyle.LONG, FormatStyle.MEDIUM)
.appendLocalizedOffset(TextStyle.FULL)
.toFormatter()
.withLocale(locale);
} else if (target instanceof OffsetTime) {
return new DateTimeFormatterBuilder()
.appendValue(ChronoField.HOUR_OF_DAY)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE)
.appendLocalizedOffset(TextStyle.FULL)
.toFormatter()
.withLocale(locale);
} else if (target instanceof Year) {
return new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR)
.toFormatter();
} else if (target instanceof YearMonth) {
return yearMonthFormatter(locale);
} else if (target instanceof ZonedDateTime) {
return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withLocale(locale);
} else {
throw new IllegalArgumentException(
"Cannot format object of class \"" + target.getClass().getName() + "\" as a date");
}
| 1,032
| 521
| 1,553
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalSetUtils.java
|
TemporalSetUtils
|
setFormat
|
class TemporalSetUtils {
private final TemporalFormattingUtils temporalFormattingUtils;
public TemporalSetUtils(final Locale locale, final ZoneId defaultZoneId) {
super();
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(defaultZoneId, "ZoneId cannot be null");
temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId);
}
public Set<String> setFormat(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::format);
}
public <T extends Temporal> Set<String> setFormat(final Set<T> target, final Locale locale) {
return setFormat(target, time -> temporalFormattingUtils.format(time, locale));
}
public <T extends Temporal> Set<String> setFormat(final Set<T> target, final String pattern) {
return setFormat(target, time -> temporalFormattingUtils.format(time, pattern, null));
}
public <T extends Temporal> Set<String> setFormat(final Set<T> target, final String pattern, final Locale locale) {
return setFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null));
}
public Set<Integer> setDay(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::day);
}
public Set<Integer> setMonth(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::month);
}
public Set<String> setMonthName(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::monthName);
}
public Set<String> setMonthNameShort(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::monthNameShort);
}
public Set<Integer> setYear(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::year);
}
public Set<Integer> setDayOfWeek(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::dayOfWeek);
}
public Set<String> setDayOfWeekName(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::dayOfWeekName);
}
public Set<String> setDayOfWeekNameShort(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::dayOfWeekNameShort);
}
public Set<Integer> setHour(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::hour);
}
public Set<Integer> setMinute(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::minute);
}
public Set<Integer> setSecond(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::second);
}
public Set<Integer> setNanosecond(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::nanosecond);
}
public Set<String> setFormatISO(final Set<? extends Temporal> target) {
return setFormat(target, temporalFormattingUtils::formatISO);
}
private <R extends Object, T extends Temporal> Set<R> setFormat(
final Set<T> target, final Function<T, R> mapFunction) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(target, "Target cannot be null");
return target.stream()
.map(time -> mapFunction.apply(time))
.collect(toSet());
| 959
| 49
| 1,008
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebApplication.java
|
JakartaServletWebApplication
|
buildExchange
|
class JakartaServletWebApplication implements IServletWebApplication {
// This class is made NOT final so that it can be proxied by Dependency Injection frameworks
private final ServletContext servletContext;
JakartaServletWebApplication(final ServletContext servletContext) {
super();
Validate.notNull(servletContext, "Servlet context cannot be null");
this.servletContext = servletContext;
}
public static JakartaServletWebApplication buildApplication(final ServletContext servletContext) {
return new JakartaServletWebApplication(servletContext);
}
public IServletWebExchange buildExchange(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse) {<FILL_FUNCTION_BODY>}
@Override
public Enumeration<String> getAttributeNames() {
return this.servletContext.getAttributeNames();
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.servletContext.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
this.servletContext.setAttribute(name, value);
}
@Override
public InputStream getResourceAsStream(final String path) {
Validate.notNull(path, "Path cannot be null");
return this.servletContext.getResourceAsStream(path);
}
@Override
public URL getResource(final String path) throws MalformedURLException {
Validate.notNull(path, "Path cannot be null");
return this.servletContext.getResource(path);
}
@Override
public Object getNativeServletContextObject() {
return this.servletContext;
}
private boolean servletContextMatches(final HttpServletRequest httpServletRequest) {
// We should not be directly matching servletContext objects because a wrapper might have been applied
final String servletContextPath = this.servletContext.getContextPath();
final String requestServletContextPath = httpServletRequest.getServletContext().getContextPath();
return Objects.equals(servletContextPath, requestServletContextPath);
}
}
|
Validate.notNull(httpServletRequest, "Request cannot be null");
Validate.notNull(httpServletResponse, "Response cannot be null");
Validate.isTrue(servletContextMatches(httpServletRequest),
"Cannot build an application for a request which servlet context does not match with " +
"the application that it is being built for.");
final JakartaServletWebRequest request = new JakartaServletWebRequest(httpServletRequest);
final JakartaServletWebSession session = new JakartaServletWebSession(httpServletRequest);
return new JakartaServletWebExchange(request, session, this, httpServletResponse);
| 588
| 166
| 754
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebRequest.java
|
JakartaServletWebRequest
|
getCookieMap
|
class JakartaServletWebRequest implements IServletWebRequest {
private final HttpServletRequest request;
JakartaServletWebRequest(final HttpServletRequest request) {
super();
Validate.notNull(request, "Request cannot be null");
this.request = request;
}
@Override
public String getMethod() {
return this.request.getMethod();
}
@Override
public String getScheme() {
return this.request.getScheme();
}
@Override
public String getServerName() {
return this.request.getServerName();
}
@Override
public Integer getServerPort() {
return Integer.valueOf(this.request.getServerPort());
}
@Override
public String getContextPath() {
final String contextPath = this.request.getContextPath();
// This protects against a redirection behaviour in Jetty
return (contextPath != null && contextPath.length() == 1 && contextPath.charAt(0) == '/')? "" : contextPath;
}
@Override
public String getRequestURI() {
return this.request.getRequestURI();
}
@Override
public String getQueryString() {
return this.request.getQueryString();
}
@Override
public Enumeration<String> getHeaderNames() {
return this.request.getHeaderNames();
}
@Override
public Enumeration<String> getHeaders(final String name) {
return this.request.getHeaders(name);
}
@Override
public String getHeaderValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getHeader(name);
}
@Override
public Map<String, String[]> getParameterMap() {
return this.request.getParameterMap();
}
@Override
public String getParameterValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getParameter(name);
}
@Override
public String[] getParameterValues(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getParameterValues(name);
}
@Override
public boolean containsCookie(final String name) {
Validate.notNull(name, "Name cannot be null");
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return false;
}
for (int i = 0; i < cookies.length; i++) {
if (name.equals(cookies[i].getName())) {
return true;
}
}
return false;
}
@Override
public int getCookieCount() {
final Cookie[] cookies = this.request.getCookies();
return (cookies == null? 0 : cookies.length);
}
@Override
public Set<String> getAllCookieNames() {
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return Collections.emptySet();
}
final Set<String> cookieNames = new LinkedHashSet<String>(3);
for (int i = 0; i < cookies.length; i++) {
cookieNames.add(cookies[i].getName());
}
return Collections.unmodifiableSet(cookieNames);
}
@Override
public Map<String, String[]> getCookieMap() {<FILL_FUNCTION_BODY>}
@Override
public String[] getCookieValues(final String name) {
Validate.notNull(name, "Name cannot be null");
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return null;
}
String[] cookieValues = null;
for (int i = 0; i < cookies.length; i++) {
final String cookieName = cookies[i].getName();
if (name.equals(cookieName)) {
final String cookieValue = cookies[i].getValue();
if (cookieValues != null) {
final String[] newCookieValues = Arrays.copyOf(cookieValues, cookieValues.length + 1);
newCookieValues[cookieValues.length] = cookieValue;
cookieValues = newCookieValues;
} else {
cookieValues = new String[]{cookieValue};
}
}
}
return cookieValues;
}
@Override
public Object getNativeRequestObject() {
return this.request;
}
}
|
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return Collections.emptyMap();
}
final Map<String,String[]> cookieMap = new LinkedHashMap<String,String[]>(3);
for (int i = 0; i < cookies.length; i++) {
final String cookieName = cookies[i].getName();
final String cookieValue = cookies[i].getValue();
if (cookieMap.containsKey(cookieName)) {
final String[] currentCookieValues = cookieMap.get(cookieName);
final String[] newCookieValues = Arrays.copyOf(currentCookieValues, currentCookieValues.length + 1);
newCookieValues[currentCookieValues.length] = cookieValue;
cookieMap.put(cookieName, newCookieValues);
} else {
cookieMap.put(cookieName, new String[]{cookieValue});
}
}
return Collections.unmodifiableMap(cookieMap);
| 1,189
| 255
| 1,444
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebSession.java
|
JakartaServletWebSession
|
getAttributeValue
|
class JakartaServletWebSession implements IServletWebSession {
private final HttpServletRequest request;
private HttpSession session;
JakartaServletWebSession(final HttpServletRequest request) {
super();
Validate.notNull(request, "Request cannot be null");
this.request = request;
this.session = this.request.getSession(false); // Might initialize property as null
}
@Override
public boolean exists() {
return this.session != null;
}
@Override
public Enumeration<String> getAttributeNames() {
if (this.session == null) {
return Collections.emptyEnumeration();
}
return this.session.getAttributeNames();
}
@Override
public Object getAttributeValue(final String name) {<FILL_FUNCTION_BODY>}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
if (this.session == null) {
// Setting an attribute will actually create a new session
this.session = this.request.getSession(true);
}
this.session.setAttribute(name, value);
}
@Override
public Object getNativeSessionObject() {
return this.session;
}
}
|
Validate.notNull(name, "Name cannot be null");
if (this.session == null) {
return null;
}
return this.session.getAttribute(name);
| 343
| 50
| 393
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebApplication.java
|
JavaxServletWebApplication
|
buildExchange
|
class JavaxServletWebApplication implements IServletWebApplication {
// This class is made NOT final so that it can be proxied by Dependency Injection frameworks
private final ServletContext servletContext;
JavaxServletWebApplication(final ServletContext servletContext) {
super();
Validate.notNull(servletContext, "Servlet context cannot be null");
this.servletContext = servletContext;
}
public static JavaxServletWebApplication buildApplication(final ServletContext servletContext) {
return new JavaxServletWebApplication(servletContext);
}
public IServletWebExchange buildExchange(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse) {<FILL_FUNCTION_BODY>}
@Override
public Enumeration<String> getAttributeNames() {
return this.servletContext.getAttributeNames();
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.servletContext.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
this.servletContext.setAttribute(name, value);
}
@Override
public InputStream getResourceAsStream(final String path) {
Validate.notNull(path, "Path cannot be null");
return this.servletContext.getResourceAsStream(path);
}
@Override
public URL getResource(final String path) throws MalformedURLException {
Validate.notNull(path, "Path cannot be null");
return this.servletContext.getResource(path);
}
@Override
public Object getNativeServletContextObject() {
return this.servletContext;
}
private boolean servletContextMatches(final HttpServletRequest httpServletRequest) {
// We should not be directly matching servletContext objects because a wrapper might have been applied
final String servletContextPath = this.servletContext.getContextPath();
final String requestServletContextPath = httpServletRequest.getServletContext().getContextPath();
return Objects.equals(servletContextPath, requestServletContextPath);
}
}
|
Validate.notNull(httpServletRequest, "Request cannot be null");
Validate.notNull(httpServletResponse, "Response cannot be null");
Validate.isTrue(servletContextMatches(httpServletRequest),
"Cannot build an application for a request which servlet context does not match with " +
"the application that it is being built for.");
final JavaxServletWebRequest request = new JavaxServletWebRequest(httpServletRequest);
final JavaxServletWebSession session = new JavaxServletWebSession(httpServletRequest);
return new JavaxServletWebExchange(request, session, this, httpServletResponse);
| 584
| 161
| 745
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebRequest.java
|
JavaxServletWebRequest
|
getCookieValues
|
class JavaxServletWebRequest implements IServletWebRequest {
private final HttpServletRequest request;
JavaxServletWebRequest(final HttpServletRequest request) {
super();
Validate.notNull(request, "Request cannot be null");
this.request = request;
}
@Override
public String getMethod() {
return this.request.getMethod();
}
@Override
public String getScheme() {
return this.request.getScheme();
}
@Override
public String getServerName() {
return this.request.getServerName();
}
@Override
public Integer getServerPort() {
return Integer.valueOf(this.request.getServerPort());
}
@Override
public String getContextPath() {
final String contextPath = this.request.getContextPath();
// This protects against a redirection behaviour in Jetty
return (contextPath != null && contextPath.length() == 1 && contextPath.charAt(0) == '/')? "" : contextPath;
}
@Override
public String getRequestURI() {
return this.request.getRequestURI();
}
@Override
public String getQueryString() {
return this.request.getQueryString();
}
@Override
public Enumeration<String> getHeaderNames() {
return this.request.getHeaderNames();
}
@Override
public Enumeration<String> getHeaders(final String name) {
return this.request.getHeaders(name);
}
@Override
public String getHeaderValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getHeader(name);
}
@Override
public Map<String, String[]> getParameterMap() {
return this.request.getParameterMap();
}
@Override
public String getParameterValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getParameter(name);
}
@Override
public String[] getParameterValues(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.request.getParameterValues(name);
}
@Override
public boolean containsCookie(final String name) {
Validate.notNull(name, "Name cannot be null");
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return false;
}
for (int i = 0; i < cookies.length; i++) {
if (name.equals(cookies[i].getName())) {
return true;
}
}
return false;
}
@Override
public int getCookieCount() {
final Cookie[] cookies = this.request.getCookies();
return (cookies == null? 0 : cookies.length);
}
@Override
public Set<String> getAllCookieNames() {
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return Collections.emptySet();
}
final Set<String> cookieNames = new LinkedHashSet<String>(3);
for (int i = 0; i < cookies.length; i++) {
cookieNames.add(cookies[i].getName());
}
return Collections.unmodifiableSet(cookieNames);
}
@Override
public Map<String, String[]> getCookieMap() {
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return Collections.emptyMap();
}
final Map<String,String[]> cookieMap = new LinkedHashMap<String,String[]>(3);
for (int i = 0; i < cookies.length; i++) {
final String cookieName = cookies[i].getName();
final String cookieValue = cookies[i].getValue();
if (cookieMap.containsKey(cookieName)) {
final String[] currentCookieValues = cookieMap.get(cookieName);
final String[] newCookieValues = Arrays.copyOf(currentCookieValues, currentCookieValues.length + 1);
newCookieValues[currentCookieValues.length] = cookieValue;
cookieMap.put(cookieName, newCookieValues);
} else {
cookieMap.put(cookieName, new String[]{cookieValue});
}
}
return Collections.unmodifiableMap(cookieMap);
}
@Override
public String[] getCookieValues(final String name) {<FILL_FUNCTION_BODY>}
@Override
public Object getNativeRequestObject() {
return this.request;
}
}
|
Validate.notNull(name, "Name cannot be null");
final Cookie[] cookies = this.request.getCookies();
if (cookies == null) {
return null;
}
String[] cookieValues = null;
for (int i = 0; i < cookies.length; i++) {
final String cookieName = cookies[i].getName();
if (name.equals(cookieName)) {
final String cookieValue = cookies[i].getValue();
if (cookieValues != null) {
final String[] newCookieValues = Arrays.copyOf(cookieValues, cookieValues.length + 1);
newCookieValues[cookieValues.length] = cookieValue;
cookieValues = newCookieValues;
} else {
cookieValues = new String[]{cookieValue};
}
}
}
return cookieValues;
| 1,224
| 218
| 1,442
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebSession.java
|
JavaxServletWebSession
|
getAttributeValue
|
class JavaxServletWebSession implements IServletWebSession {
private final HttpServletRequest request;
private HttpSession session;
JavaxServletWebSession(final HttpServletRequest request) {
super();
Validate.notNull(request, "Request cannot be null");
this.request = request;
this.session = this.request.getSession(false); // Might initialize property as null
}
@Override
public boolean exists() {
return this.session != null;
}
@Override
public Enumeration<String> getAttributeNames() {
if (this.session == null) {
return Collections.emptyEnumeration();
}
return this.session.getAttributeNames();
}
@Override
public Object getAttributeValue(final String name) {<FILL_FUNCTION_BODY>}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
if (this.session == null) {
// Setting an attribute will actually create a new session
this.session = this.request.getSession(true);
}
this.session.setAttribute(name, value);
}
@Override
public Object getNativeSessionObject() {
return this.session;
}
}
|
Validate.notNull(name, "Name cannot be null");
if (this.session == null) {
return null;
}
return this.session.getAttribute(name);
| 341
| 50
| 391
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/WdmAgent.java
|
DefineTransformer
|
transform
|
class DefineTransformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className,
Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {<FILL_FUNCTION_BODY>}
}
|
DriverManagerType driverManagerType = null;
switch (className) {
case "org/openqa/selenium/chrome/ChromeDriver":
driverManagerType = CHROME;
break;
case "org/openqa/selenium/firefox/FirefoxDriver":
driverManagerType = FIREFOX;
break;
case "org/openqa/selenium/opera/OperaDriver":
driverManagerType = OPERA;
break;
case "org/openqa/selenium/edge/EdgeDriver":
driverManagerType = EDGE;
break;
case "org/openqa/selenium/ie/InternetExplorerDriver":
driverManagerType = IEXPLORER;
break;
default:
break;
}
if (driverManagerType != null) {
log.debug(
"WebDriverManager Agent is going to resolve the driver for {}",
driverManagerType);
WebDriverManager.getInstance(driverManagerType).setup();
}
return classfileBuffer;
| 75
| 273
| 348
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/cache/CacheHandler.java
|
CacheHandler
|
getFilesInCache
|
class CacheHandler {
final Logger log = getLogger(lookup().lookupClass());
private Config config;
public CacheHandler(Config config) {
this.config = config;
}
public List<File> filterCacheBy(List<File> input, String key,
boolean isVersion) {
String pathSeparator = isVersion ? separator : "";
List<File> output = new ArrayList<>(input);
if (!key.isEmpty() && !input.isEmpty()) {
output = input.stream()
.filter(file -> file.toString().toLowerCase(ROOT)
.contains(pathSeparator + key.toLowerCase(ROOT)))
.collect(toList());
}
log.trace("Filter cache by {} -- input list {} -- output list {} ", key,
input, output);
return output;
}
public List<File> getFilesInCache() {<FILL_FUNCTION_BODY>}
public Optional<String> getDriverFromCache(String driverVersion,
String driverName, DriverManagerType driverManagerType,
Architecture arch, String os) {
log.trace("Checking if {} exists in cache", driverName);
List<File> filesInCache = getFilesInCache();
if (!filesInCache.isEmpty()) {
// Filter by name
filesInCache = filterCacheBy(filesInCache, driverName, false);
// Filter by version
filesInCache = filterCacheBy(filesInCache, driverVersion, true);
// Filter by OS
filesInCache = filterCacheBy(filesInCache, os, false);
// Filter by ARM64 architecture
filesInCache = config.getArchitecture().filterArm64(filesInCache);
if (filesInCache.size() == 1 && config.getArchitecture() != ARM64) {
return Optional.of(filesInCache.get(0).toString());
}
// Filter by arch
if (os.equalsIgnoreCase("win") && (driverManagerType == CHROME
|| driverManagerType == CHROMIUM)) {
log.trace(
"Avoid filtering for architecture {} with {} in Windows",
arch, driverName);
} else {
filesInCache = filterCacheBy(filesInCache, arch.toString(),
false);
}
if (!filesInCache.isEmpty()) {
return Optional.of(
filesInCache.get(filesInCache.size() - 1).toString());
}
}
log.trace("{} not found in cache", driverName);
return Optional.empty();
}
}
|
List<File> listFiles = (List<File>) listFiles(config.getCacheFolder(),
null, true);
sort(listFiles);
return listFiles;
| 651
| 46
| 697
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/cache/ResolutionCache.java
|
ResolutionCache
|
getExpirationDateFromResolutionCache
|
class ResolutionCache {
final Logger log = getLogger(lookup().lookupClass());
static final String TTL = "-ttl";
static final String RESOLUTION_CACHE_INFO = "WebDriverManager Resolution Cache";
Properties props = new Properties() {
private static final long serialVersionUID = 3734950329657085291L;
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy z");
Config config;
File resolutionCacheFile;
public ResolutionCache(Config config) {
this.config = config;
if (!config.isAvoidResolutionCache()) {
File resolutionCachePath = config.getResolutionCachePath();
this.resolutionCacheFile = new File(resolutionCachePath,
config.getResolutionCache());
try {
if (!resolutionCacheFile.exists()) {
boolean createNewFile = resolutionCacheFile.createNewFile();
if (createNewFile) {
log.debug("Created new resolution cache file at {}",
resolutionCacheFile);
}
}
try (InputStream fis = new FileInputStream(
resolutionCacheFile)) {
props.load(fis);
}
} catch (Exception e) {
throw new WebDriverManagerException(
"Exception reading resolution cache as a properties file",
e);
}
}
}
public String getValueFromResolutionCache(String key) {
return props.getProperty(key, null);
}
private Date getExpirationDateFromResolutionCache(String key) {<FILL_FUNCTION_BODY>}
public void putValueInResolutionCacheIfEmpty(String key, String value,
int ttl) {
if (ttl > 0 && getValueFromResolutionCache(key) == null) {
props.put(key, value);
long now = new Date().getTime();
Date expirationDate = new Date(now + SECONDS.toMillis(ttl));
String expirationDateStr = formatDate(expirationDate);
props.put(getExpirationKey(key), expirationDateStr);
if (log.isDebugEnabled()) {
log.debug("Storing resolution {}={} in cache (valid until {})",
key, value, expirationDateStr);
}
storeProperties();
}
}
private synchronized void storeProperties() {
try (OutputStream fos = new FileOutputStream(resolutionCacheFile)) {
props.store(fos, RESOLUTION_CACHE_INFO);
} catch (Exception e) {
log.warn(
"Exception writing resolution cache as a properties file {}",
e.getClass().getName());
}
}
private void clearFromResolutionCache(String key) {
props.remove(key);
props.remove(getExpirationKey(key));
storeProperties();
}
public void clear() {
log.info("Clearing WebDriverManager resolution cache");
props.clear();
storeProperties();
}
private boolean checkValidity(String key, String value,
Date expirationDate) {
long now = new Date().getTime();
long expirationTime = expirationDate != null ? expirationDate.getTime()
: 0;
boolean isValid = value != null && expirationTime != 0
&& expirationTime > now;
if (!isValid) {
log.debug("Removing resolution {}={} from cache (expired on {})",
key, value, expirationDate);
clearFromResolutionCache(key);
}
return isValid;
}
private String formatDate(Date date) {
return date != null ? dateFormat.format(date) : "";
}
private String getExpirationKey(String key) {
return key + TTL;
}
public boolean checkKeyInResolutionCache(String key) {
return checkKeyInResolutionCache(key, true);
}
public boolean checkKeyInResolutionCache(String key, boolean showLog) {
String valueFromResolutionCache = getValueFromResolutionCache(key);
boolean valueInResolutionCache = valueFromResolutionCache != null
&& !valueFromResolutionCache.isEmpty();
if (valueInResolutionCache) {
Date expirationDate = getExpirationDateFromResolutionCache(key);
valueInResolutionCache &= checkValidity(key,
valueFromResolutionCache, expirationDate);
if (valueInResolutionCache) {
String strDate = formatDate(expirationDate);
if (showLog) {
log.debug("Resolution {}={} in cache (valid until {})", key,
valueFromResolutionCache, strDate);
}
}
}
return valueInResolutionCache;
}
}
|
Date result = new Date(0);
try {
result = dateFormat.parse(props.getProperty(getExpirationKey(key)));
return result;
} catch (Exception e) {
log.warn("Exception parsing date ({}) from resolution cache {}",
key, e.getMessage());
}
return result;
| 1,264
| 86
| 1,350
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/docker/DockerHost.java
|
DockerHost
|
endpointFromEnv
|
class DockerHost {
static final Logger log = getLogger(lookup().lookupClass());
public static final String DEFAULT_ADDRESS = "localhost";
private static final int DEFAULT_PORT = 2375;
private static final String DEFAULT_UNIX_ENDPOINT = "unix:///var/run/docker.sock";
private static final String DEFAULT_WINDOWS_ENDPOINT = "npipe:////./pipe/docker_engine";
private String host;
private URI uri;
private URI bindUri;
private String address;
private int port;
private String certPath;
private String endpoint;
private DockerHost(String endpoint, String certPath) {
if (endpoint.startsWith("unix://")) {
this.port = 0;
this.address = DEFAULT_ADDRESS;
this.host = endpoint;
this.uri = URI.create(endpoint);
this.bindUri = URI.create(endpoint);
} else {
String stripped = endpoint.replaceAll(".*://", "");
Pattern hostPattern = Pattern.compile("^\\s*(.*?):(\\d+)\\s*$");
Matcher hostMatcher = hostPattern.matcher(stripped);
String scheme = isNullOrEmpty(certPath) ? "http" : "https";
this.address = hostMatcher.matches() ? hostMatcher.group(1)
: DEFAULT_ADDRESS;
this.port = hostMatcher.matches()
? Integer.parseInt(hostMatcher.group(2))
: defaultPort();
this.host = address + ":" + port;
this.uri = URI.create(scheme + "://" + address + ":" + port);
this.bindUri = URI.create("tcp://" + address + ":" + port);
}
this.endpoint = endpoint;
this.certPath = certPath;
}
public String endpoint() {
return endpoint;
}
public String host() {
return host;
}
public URI uri() {
return uri;
}
public URI bindUri() {
return bindUri;
}
public int port() {
return port;
}
public String address() {
return address;
}
public String dockerCertPath() {
return certPath;
}
public static DockerHost fromEnv() {
String host = endpointFromEnv();
String certPath = certPathFromEnv();
return new DockerHost(host, certPath);
}
public static DockerHost from(String endpoint, String certPath) {
return new DockerHost(endpoint, certPath);
}
public static String defaultDockerEndpoint() {
String osName = System.getProperty("os.name");
String os = osName.toLowerCase(ROOT);
if (os.equalsIgnoreCase("linux") || os.contains("mac")) {
return defaultUnixEndpoint();
} else if (os.contains("windows")) {
return defaultWindowsEndpoint();
} else {
return "http://" + defaultAddress() + ":" + defaultPort();
}
}
public static String endpointFromEnv() {<FILL_FUNCTION_BODY>}
public static String defaultUnixEndpoint() {
return DEFAULT_UNIX_ENDPOINT;
}
public static String defaultWindowsEndpoint() {
return DEFAULT_WINDOWS_ENDPOINT;
}
public static String defaultAddress() {
return DEFAULT_ADDRESS;
}
public static int defaultPort() {
return DEFAULT_PORT;
}
public static int portFromEnv() {
String port = System.getenv("DOCKER_PORT");
if (port == null) {
return defaultPort();
}
try {
return Integer.parseInt(port);
} catch (NumberFormatException e) {
return defaultPort();
}
}
public static String defaultCertPath() {
String userHome = System.getProperty("user.home");
return Paths.get(userHome, ".docker").toString();
}
public static String certPathFromEnv() {
return System.getenv("DOCKER_CERT_PATH");
}
public static String configPathFromEnv() {
return System.getenv("DOCKER_CONFIG");
}
}
|
String dockerHost = System.getenv("DOCKER_HOST");
if (dockerHost == null) {
dockerHost = defaultDockerEndpoint();
}
return dockerHost;
| 1,110
| 50
| 1,160
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/docker/DockerHubService.java
|
DockerHubService
|
listTags
|
class DockerHubService {
final Logger log = getLogger(lookup().lookupClass());
static final String GET_IMAGE_TAGS_PATH_FORMAT = "%sv2/repositories/%s/tags?page=%s&page_size=1024";
private Config config;
private HttpClient client;
public DockerHubService(Config config, HttpClient client) {
this.config = config;
this.client = client;
}
public List<DockerHubTag> listTags(String dockerImageFormat) {<FILL_FUNCTION_BODY>}
}
|
log.debug("Getting browser image list from Docker Hub");
List<DockerHubTag> results = new ArrayList<>();
String dockerHubUrl = config.getDockerHubUrl();
String repo = dockerImageFormat.substring(0,
dockerImageFormat.indexOf(":"));
Object url = String.format(GET_IMAGE_TAGS_PATH_FORMAT, dockerHubUrl,
repo, 1);
Gson gson = new GsonBuilder().create();
try {
do {
log.trace("Sending request to {}", url);
HttpGet createHttpGet = client
.createHttpGet(new URL(url.toString()));
ClassicHttpResponse response = client.execute(createHttpGet);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
DockerHubTags dockerHubTags = gson.fromJson(reader,
DockerHubTags.class);
results.addAll(dockerHubTags.getResults());
url = dockerHubTags.next;
response.close();
} while (url != null);
} catch (Exception e) {
log.warn("Exception getting browser image list from Docker Hub", e);
}
return results;
| 155
| 318
| 473
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/ChromeDriverManager.java
|
ChromeDriverManager
|
getCapabilities
|
class ChromeDriverManager extends WebDriverManager {
private static final String CHROMEDRIVER_DOWNLOAD_OLD_PATTERN = "https://chromedriver.storage.googleapis.com/%s/chromedriver_%s%s.zip";
@Override
public DriverManagerType getDriverManagerType() {
return CHROME;
}
@Override
protected String getDriverName() {
return "chromedriver";
}
@Override
protected String getDriverVersion() {
return config().getChromeDriverVersion();
}
@Override
protected String getBrowserVersion() {
return config().getChromeVersion();
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setChromeDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setChromeVersion(browserVersion);
}
@Override
protected URL getDriverUrl() {
return getDriverUrlCkeckingMirror(config().getChromeDriverUrl());
}
@Override
protected Optional<URL> getMirrorUrl() {
return Optional.of(config().getChromeDriverMirrorUrl());
}
@Override
protected Optional<String> getExportParameter() {
return Optional.of(config().getChromeDriverExport());
}
@Override
protected void setDriverUrl(URL url) {
config().setChromeDriverUrl(url);
}
@Override
protected List<URL> getDriverUrls(String driverVersion) throws IOException {
if (isUseMirror()) {
return getDriversFromMirror(getMirrorUrl().get(), driverVersion);
} else {
String cftUrl = config.getChromeLastGoodVersionsUrl();
LastGoodVersions versions = Parser.parseJson(getHttpClient(),
cftUrl, LastGoodVersions.class);
return versions.channels.stable.downloads.chromedriver.stream()
.map(platformUrl -> {
try {
return new URL(platformUrl.url);
} catch (MalformedURLException e) {
throw new WebDriverException(
"Incorrect CfT URL " + platformUrl.url);
}
}).collect(Collectors.toList());
}
}
@Override
protected Optional<String> getLatestDriverVersionFromRepository() {
if (config().isUseBetaVersions()) {
return empty();
} else {
return getDriverVersionFromRepository(empty());
}
}
@Override
protected Charset getVersionCharset() {
return StandardCharsets.UTF_8;
}
@Override
protected NamespaceContext getNamespaceContext() {
return S3_NAMESPACE_CONTEXT;
}
@Override
protected Optional<URL> buildUrl(String driverVersion) {
return buildUrl(driverVersion, config());
}
Optional<URL> buildUrl(String driverVersion, Config config) {
Optional<URL> optionalUrl = empty();
if (!config.isUseMirror() && !isNullOrEmpty(driverVersion)) {
String downloadUrlPattern = config.getChromeDownloadUrlPattern();
OperatingSystem os = config.getOperatingSystem();
Architecture arch = config.getArchitecture();
String archLabel = os.isLinux() ? "64"
: arch.toString().toLowerCase(ROOT);
if (os.isWin() && !X32.equals(arch)) {
archLabel = "64";
}
if (os.isMac() && !ARM64.equals(arch)) {
archLabel = "x64";
}
String separator = os.isMac() ? "-" : "";
String label = os.getName() + separator + archLabel;
String builtUrl = String.format(downloadUrlPattern, driverVersion,
label, label);
if (!VersionDetector.isCfT(driverVersion)) {
archLabel = os.isWin() ? "32" : "64";
builtUrl = String.format(CHROMEDRIVER_DOWNLOAD_OLD_PATTERN,
driverVersion, os.getName(), archLabel);
}
log.debug("Using URL built from repository pattern: {}", builtUrl);
try {
optionalUrl = Optional.of(new URL(builtUrl));
} catch (MalformedURLException e) {
log.warn("Error building URL from pattern {} {}", builtUrl,
e.getMessage());
}
}
return optionalUrl;
}
@Override
protected Capabilities getCapabilities() {<FILL_FUNCTION_BODY>}
@Override
public WebDriverManager browserInDockerAndroid() {
this.dockerEnabled = true;
this.androidEnabled = true;
return this;
}
@Override
public WebDriverManager exportParameter(String exportParameter) {
config().setChromeDriverExport(exportParameter);
return this;
}
}
|
Capabilities options = new ChromeOptions();
try {
addDefaultArgumentsForDocker(options);
} catch (Exception e) {
log.error(
"Exception adding default arguments for Docker, retyring with custom class");
options = new OptionsWithArguments("chrome", "goog:chromeOptions");
try {
addDefaultArgumentsForDocker(options);
} catch (Exception e1) {
log.error("Exception getting default capabilities", e);
}
}
return options;
| 1,429
| 142
| 1,571
|
<methods>public io.github.bonigarcia.wdm.WebDriverManager arch32() ,public io.github.bonigarcia.wdm.WebDriverManager arch64() ,public io.github.bonigarcia.wdm.WebDriverManager architecture(io.github.bonigarcia.wdm.config.Architecture) ,public io.github.bonigarcia.wdm.WebDriverManager arm64() ,public io.github.bonigarcia.wdm.WebDriverManager avoidBrowserDetection() ,public io.github.bonigarcia.wdm.WebDriverManager avoidDockerLocalFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExport() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExternalConnections() ,public io.github.bonigarcia.wdm.WebDriverManager avoidFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidOutputTree() ,public io.github.bonigarcia.wdm.WebDriverManager avoidResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager avoidShutdownHook() ,public io.github.bonigarcia.wdm.WebDriverManager avoidTmpFolder() ,public io.github.bonigarcia.wdm.WebDriverManager avoidUseChromiumDriverSnap() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDocker() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager browserVersion(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionCommand(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionRegex(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager cachePath(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager capabilities(Capabilities) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromedriver() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromiumdriver() ,public io.github.bonigarcia.wdm.WebDriverManager clearDriverCache() ,public io.github.bonigarcia.wdm.WebDriverManager clearResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager commandsPropertiesUrl(java.net.URL) ,public synchronized io.github.bonigarcia.wdm.config.Config config() ,public synchronized WebDriver create() ,public synchronized List<WebDriver> create(int) ,public io.github.bonigarcia.wdm.WebDriverManager disableCsp() ,public io.github.bonigarcia.wdm.WebDriverManager disableTracing() ,public io.github.bonigarcia.wdm.WebDriverManager dockerAvoidPulling() ,public io.github.bonigarcia.wdm.WebDriverManager dockerCustomImage(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDaemonUrl(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDefaultArgs(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerEnvVariables(java.lang.String[]) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerExtraHosts(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager dockerLang(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetwork(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetworkHost() ,public io.github.bonigarcia.wdm.WebDriverManager dockerPrivateEndpoint(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingFrameRate(int) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.nio.file.Path) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingPrefix(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerScreenResolution(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerShmSize(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerStopTimeoutSec(java.lang.Integer) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTimezone(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsMount(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsSize(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerVolumes(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager driverRepositoryUrl(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager driverVersion(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager edgedriver() ,public io.github.bonigarcia.wdm.WebDriverManager enableRecording() ,public io.github.bonigarcia.wdm.WebDriverManager enableVnc() ,public abstract io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager firefoxdriver() ,public io.github.bonigarcia.wdm.WebDriverManager forceDownload() ,public Optional<java.nio.file.Path> getBrowserPath() ,public java.lang.String getDockerBrowserContainerId(WebDriver) ,public java.lang.String getDockerBrowserContainerId() ,public java.net.URL getDockerNoVncUrl(WebDriver) ,public java.net.URL getDockerNoVncUrl() ,public java.nio.file.Path getDockerRecordingPath(WebDriver) ,public java.nio.file.Path getDockerRecordingPath() ,public java.net.URL getDockerSeleniumServerUrl(WebDriver) ,public java.net.URL getDockerSeleniumServerUrl() ,public synchronized io.github.bonigarcia.wdm.docker.DockerService getDockerService() ,public java.lang.String getDockerVncUrl(WebDriver) ,public java.lang.String getDockerVncUrl() ,public java.lang.String getDownloadedDriverPath() ,public java.lang.String getDownloadedDriverVersion() ,public abstract io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() ,public List<java.lang.String> getDriverVersions() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(Class<? extends WebDriver>) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance() ,public List<Map<java.lang.String,java.lang.Object>> getLogs(WebDriver) ,public List<Map<java.lang.String,java.lang.Object>> getLogs() ,public WebDriver getWebDriver() ,public List<WebDriver> getWebDriverList() ,public io.github.bonigarcia.wdm.WebDriverManager gitHubToken(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager iedriver() ,public transient io.github.bonigarcia.wdm.WebDriverManager ignoreDriverVersions(java.lang.String[]) ,public static boolean isDockerAvailable() ,public static boolean isOnline(java.lang.String) ,public static boolean isOnline(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager linux() ,public static org.w3c.dom.Document loadXML(java.io.InputStream) throws org.xml.sax.SAXException, java.io.IOException, javax.xml.parsers.ParserConfigurationException,public io.github.bonigarcia.wdm.WebDriverManager mac() ,public static void main(java.lang.String[]) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager operadriver() ,public io.github.bonigarcia.wdm.WebDriverManager operatingSystem(io.github.bonigarcia.wdm.config.OperatingSystem) ,public io.github.bonigarcia.wdm.WebDriverManager properties(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxy(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyPass(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyUser(java.lang.String) ,public synchronized void quit() ,public synchronized void quit(WebDriver) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.net.URL) ,public void reset() ,public io.github.bonigarcia.wdm.WebDriverManager resolutionCachePath(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager safaridriver() ,public synchronized void setup() ,public void startRecording(WebDriver) ,public void startRecording() ,public void startRecording(WebDriver, java.lang.String) ,public void startRecording(java.lang.String) ,public synchronized void stopDockerRecording() ,public synchronized void stopDockerRecording(WebDriver) ,public void stopRecording(WebDriver) ,public void stopRecording() ,public io.github.bonigarcia.wdm.WebDriverManager timeout(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttl(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttlBrowsers(int) ,public io.github.bonigarcia.wdm.WebDriverManager useBetaVersions() ,public io.github.bonigarcia.wdm.WebDriverManager useLocalCommandsPropertiesFirst() ,public io.github.bonigarcia.wdm.WebDriverManager useMirror() ,public io.github.bonigarcia.wdm.WebDriverManager viewOnly() ,public io.github.bonigarcia.wdm.WebDriverManager watch() ,public io.github.bonigarcia.wdm.WebDriverManager watchAndDisplay() ,public io.github.bonigarcia.wdm.WebDriverManager win() ,public static java.nio.file.Path zipFolder(java.nio.file.Path) <variables>protected static final java.lang.String BROWSER_WATCHER_ID,protected static final java.lang.String CFT_LABEL,protected static final java.lang.String CLI_DOCKER,protected static final java.lang.String CLI_RESOLVER,protected static final java.lang.String CLI_SERVER,protected static final java.lang.String DASH,protected static final java.lang.String IN_DOCKER,protected static final java.lang.String LATEST_RELEASE,protected static final javax.xml.namespace.NamespaceContext S3_NAMESPACE_CONTEXT,protected static final java.lang.String SLASH,protected boolean androidEnabled,protected io.github.bonigarcia.wdm.cache.CacheHandler cacheHandler,protected Capabilities capabilities,protected io.github.bonigarcia.wdm.config.Config config,protected boolean disableCsp,protected boolean displayEnabled,protected boolean dockerEnabled,protected io.github.bonigarcia.wdm.docker.DockerService dockerService,protected java.lang.String downloadedDriverPath,protected java.lang.String downloadedDriverVersion,protected io.github.bonigarcia.wdm.online.Downloader downloader,protected io.github.bonigarcia.wdm.online.HttpClient httpClient,protected boolean isHeadless,protected static final Logger log,protected io.github.bonigarcia.wdm.cache.ResolutionCache resolutionCache,protected java.lang.String resolvedBrowserVersion,protected int retryCount,protected boolean shutdownHook,protected io.github.bonigarcia.wdm.versions.VersionDetector versionDetector,protected boolean watchEnabled,protected io.github.bonigarcia.wdm.webdriver.WebDriverCreator webDriverCreator,protected List<io.github.bonigarcia.wdm.webdriver.WebDriverBrowser> webDriverList
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/ChromiumDriverManager.java
|
ChromiumDriverManager
|
getCapabilities
|
class ChromiumDriverManager extends ChromeDriverManager {
@Override
public DriverManagerType getDriverManagerType() {
return CHROMIUM;
}
@Override
protected String getDriverVersion() {
return config().getChromiumDriverVersion();
}
@Override
protected String getBrowserVersion() {
return config().getChromiumVersion();
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setChromiumDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setChromiumVersion(browserVersion);
}
@Override
protected Capabilities getCapabilities() {<FILL_FUNCTION_BODY>}
}
|
ChromeOptions options = new ChromeOptions();
Optional<Path> browserPath = getBrowserPath();
if (browserPath.isPresent()) {
options.setBinary(browserPath.get().toFile());
}
return options;
| 221
| 67
| 288
|
<methods>public non-sealed void <init>() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() <variables>private static final java.lang.String CHROMEDRIVER_DOWNLOAD_OLD_PATTERN
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/EdgeDriverManager.java
|
EdgeDriverManager
|
buildUrl
|
class EdgeDriverManager extends WebDriverManager {
protected static final String LATEST_STABLE = "LATEST_STABLE";
@Override
public DriverManagerType getDriverManagerType() {
return EDGE;
}
@Override
protected String getDriverName() {
return "msedgedriver";
}
@Override
protected String getShortDriverName() {
return "edgedriver";
}
@Override
protected String getDriverVersion() {
return config().getEdgeDriverVersion();
}
@Override
protected String getBrowserVersion() {
return config().getEdgeVersion();
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setEdgeDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setEdgeVersion(browserVersion);
}
@Override
protected URL getDriverUrl() {
return config().getEdgeDriverUrl();
}
@Override
protected Optional<URL> getMirrorUrl() {
return empty();
}
@Override
protected Optional<String> getExportParameter() {
return Optional.of(config().getEdgeDriverExport());
}
@Override
protected void setDriverUrl(URL url) {
config().setEdgeDriverUrl(url);
}
@Override
protected List<URL> getDriverUrls(String driverVersion) throws IOException {
return getDriversFromXml(
new URL(getDriverUrl() + "?restype=container&comp=list"),
"//Blob/Name", empty());
}
@Override
protected List<File> postDownload(File archive) {
Collection<File> listFiles = listFiles(new File(archive.getParent()),
null, true);
Iterator<File> iterator = listFiles.iterator();
File file = null;
List<File> files = new ArrayList<>();
while (iterator.hasNext()) {
file = iterator.next();
String fileName = file.getName();
if (fileName.contains(getDriverName())) {
log.trace(
"Adding {} at the begining of the resulting file list",
fileName);
files.add(0, file);
} else if (fileName.toLowerCase(ROOT).endsWith(".dylib")) {
log.trace("Adding {} to the resulting file list", fileName);
files.add(file);
}
}
return files;
}
@Override
protected Optional<String> getLatestDriverVersionFromRepository() {
if (config().isUseBetaVersions()) {
return empty();
} else {
return getDriverVersionFromRepository(empty());
}
}
@Override
protected Charset getVersionCharset() {
return StandardCharsets.UTF_16;
}
@Override
protected String getLatestVersionLabel() {
return LATEST_STABLE;
}
@Override
protected Optional<String> getOsLabel() {
String label = "_";
switch (config().getOperatingSystem()) {
case WIN:
label += "WINDOWS";
break;
case MAC:
label += "MACOS";
break;
default:
label += config().getOs();
break;
}
return Optional.of(label);
}
@Override
protected Optional<URL> buildUrl(String driverVersion) {
return buildUrl(driverVersion, config());
}
Optional<URL> buildUrl(String driverVersion, Config config) {<FILL_FUNCTION_BODY>}
@Override
protected Capabilities getCapabilities() {
Capabilities options = new EdgeOptions();
try {
addDefaultArgumentsForDocker(options);
} catch (Exception e) {
log.error(
"Exception adding default arguments for Docker, retyring with custom class");
options = new OptionsWithArguments("MicrosoftEdge",
"ms:edgeOptions");
try {
addDefaultArgumentsForDocker(options);
} catch (Exception e1) {
log.error("Exception getting default capabilities", e);
}
}
return options;
}
@Override
public WebDriverManager exportParameter(String exportParameter) {
config().setEdgeDriverExport(exportParameter);
return this;
}
}
|
Optional<URL> optionalUrl = empty();
if (!config.isUseMirror()) {
String downloadUrlPattern = config.getEdgeDownloadUrlPattern();
OperatingSystem os = config.getOperatingSystem();
Architecture arch = config.getArchitecture();
String archLabel = os.isWin() ? arch.toString() : "64";
String osName = arch != ARM64 ? os.getName() : "arm";
String builtUrl = os == MAC && arch == ARM64
? String.format(downloadUrlPattern, driverVersion, "mac",
"64_m1")
: String.format(downloadUrlPattern, driverVersion, osName,
archLabel);
log.debug("Using URL built from repository pattern: {}", builtUrl);
try {
optionalUrl = Optional.of(new URL(builtUrl));
} catch (MalformedURLException e) {
log.warn("Error building URL from pattern {} {}", builtUrl,
e.getMessage());
}
}
return optionalUrl;
| 1,276
| 282
| 1,558
|
<methods>public io.github.bonigarcia.wdm.WebDriverManager arch32() ,public io.github.bonigarcia.wdm.WebDriverManager arch64() ,public io.github.bonigarcia.wdm.WebDriverManager architecture(io.github.bonigarcia.wdm.config.Architecture) ,public io.github.bonigarcia.wdm.WebDriverManager arm64() ,public io.github.bonigarcia.wdm.WebDriverManager avoidBrowserDetection() ,public io.github.bonigarcia.wdm.WebDriverManager avoidDockerLocalFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExport() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExternalConnections() ,public io.github.bonigarcia.wdm.WebDriverManager avoidFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidOutputTree() ,public io.github.bonigarcia.wdm.WebDriverManager avoidResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager avoidShutdownHook() ,public io.github.bonigarcia.wdm.WebDriverManager avoidTmpFolder() ,public io.github.bonigarcia.wdm.WebDriverManager avoidUseChromiumDriverSnap() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDocker() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager browserVersion(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionCommand(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionRegex(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager cachePath(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager capabilities(Capabilities) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromedriver() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromiumdriver() ,public io.github.bonigarcia.wdm.WebDriverManager clearDriverCache() ,public io.github.bonigarcia.wdm.WebDriverManager clearResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager commandsPropertiesUrl(java.net.URL) ,public synchronized io.github.bonigarcia.wdm.config.Config config() ,public synchronized WebDriver create() ,public synchronized List<WebDriver> create(int) ,public io.github.bonigarcia.wdm.WebDriverManager disableCsp() ,public io.github.bonigarcia.wdm.WebDriverManager disableTracing() ,public io.github.bonigarcia.wdm.WebDriverManager dockerAvoidPulling() ,public io.github.bonigarcia.wdm.WebDriverManager dockerCustomImage(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDaemonUrl(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDefaultArgs(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerEnvVariables(java.lang.String[]) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerExtraHosts(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager dockerLang(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetwork(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetworkHost() ,public io.github.bonigarcia.wdm.WebDriverManager dockerPrivateEndpoint(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingFrameRate(int) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.nio.file.Path) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingPrefix(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerScreenResolution(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerShmSize(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerStopTimeoutSec(java.lang.Integer) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTimezone(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsMount(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsSize(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerVolumes(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager driverRepositoryUrl(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager driverVersion(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager edgedriver() ,public io.github.bonigarcia.wdm.WebDriverManager enableRecording() ,public io.github.bonigarcia.wdm.WebDriverManager enableVnc() ,public abstract io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager firefoxdriver() ,public io.github.bonigarcia.wdm.WebDriverManager forceDownload() ,public Optional<java.nio.file.Path> getBrowserPath() ,public java.lang.String getDockerBrowserContainerId(WebDriver) ,public java.lang.String getDockerBrowserContainerId() ,public java.net.URL getDockerNoVncUrl(WebDriver) ,public java.net.URL getDockerNoVncUrl() ,public java.nio.file.Path getDockerRecordingPath(WebDriver) ,public java.nio.file.Path getDockerRecordingPath() ,public java.net.URL getDockerSeleniumServerUrl(WebDriver) ,public java.net.URL getDockerSeleniumServerUrl() ,public synchronized io.github.bonigarcia.wdm.docker.DockerService getDockerService() ,public java.lang.String getDockerVncUrl(WebDriver) ,public java.lang.String getDockerVncUrl() ,public java.lang.String getDownloadedDriverPath() ,public java.lang.String getDownloadedDriverVersion() ,public abstract io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() ,public List<java.lang.String> getDriverVersions() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(Class<? extends WebDriver>) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance() ,public List<Map<java.lang.String,java.lang.Object>> getLogs(WebDriver) ,public List<Map<java.lang.String,java.lang.Object>> getLogs() ,public WebDriver getWebDriver() ,public List<WebDriver> getWebDriverList() ,public io.github.bonigarcia.wdm.WebDriverManager gitHubToken(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager iedriver() ,public transient io.github.bonigarcia.wdm.WebDriverManager ignoreDriverVersions(java.lang.String[]) ,public static boolean isDockerAvailable() ,public static boolean isOnline(java.lang.String) ,public static boolean isOnline(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager linux() ,public static org.w3c.dom.Document loadXML(java.io.InputStream) throws org.xml.sax.SAXException, java.io.IOException, javax.xml.parsers.ParserConfigurationException,public io.github.bonigarcia.wdm.WebDriverManager mac() ,public static void main(java.lang.String[]) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager operadriver() ,public io.github.bonigarcia.wdm.WebDriverManager operatingSystem(io.github.bonigarcia.wdm.config.OperatingSystem) ,public io.github.bonigarcia.wdm.WebDriverManager properties(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxy(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyPass(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyUser(java.lang.String) ,public synchronized void quit() ,public synchronized void quit(WebDriver) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.net.URL) ,public void reset() ,public io.github.bonigarcia.wdm.WebDriverManager resolutionCachePath(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager safaridriver() ,public synchronized void setup() ,public void startRecording(WebDriver) ,public void startRecording() ,public void startRecording(WebDriver, java.lang.String) ,public void startRecording(java.lang.String) ,public synchronized void stopDockerRecording() ,public synchronized void stopDockerRecording(WebDriver) ,public void stopRecording(WebDriver) ,public void stopRecording() ,public io.github.bonigarcia.wdm.WebDriverManager timeout(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttl(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttlBrowsers(int) ,public io.github.bonigarcia.wdm.WebDriverManager useBetaVersions() ,public io.github.bonigarcia.wdm.WebDriverManager useLocalCommandsPropertiesFirst() ,public io.github.bonigarcia.wdm.WebDriverManager useMirror() ,public io.github.bonigarcia.wdm.WebDriverManager viewOnly() ,public io.github.bonigarcia.wdm.WebDriverManager watch() ,public io.github.bonigarcia.wdm.WebDriverManager watchAndDisplay() ,public io.github.bonigarcia.wdm.WebDriverManager win() ,public static java.nio.file.Path zipFolder(java.nio.file.Path) <variables>protected static final java.lang.String BROWSER_WATCHER_ID,protected static final java.lang.String CFT_LABEL,protected static final java.lang.String CLI_DOCKER,protected static final java.lang.String CLI_RESOLVER,protected static final java.lang.String CLI_SERVER,protected static final java.lang.String DASH,protected static final java.lang.String IN_DOCKER,protected static final java.lang.String LATEST_RELEASE,protected static final javax.xml.namespace.NamespaceContext S3_NAMESPACE_CONTEXT,protected static final java.lang.String SLASH,protected boolean androidEnabled,protected io.github.bonigarcia.wdm.cache.CacheHandler cacheHandler,protected Capabilities capabilities,protected io.github.bonigarcia.wdm.config.Config config,protected boolean disableCsp,protected boolean displayEnabled,protected boolean dockerEnabled,protected io.github.bonigarcia.wdm.docker.DockerService dockerService,protected java.lang.String downloadedDriverPath,protected java.lang.String downloadedDriverVersion,protected io.github.bonigarcia.wdm.online.Downloader downloader,protected io.github.bonigarcia.wdm.online.HttpClient httpClient,protected boolean isHeadless,protected static final Logger log,protected io.github.bonigarcia.wdm.cache.ResolutionCache resolutionCache,protected java.lang.String resolvedBrowserVersion,protected int retryCount,protected boolean shutdownHook,protected io.github.bonigarcia.wdm.versions.VersionDetector versionDetector,protected boolean watchEnabled,protected io.github.bonigarcia.wdm.webdriver.WebDriverCreator webDriverCreator,protected List<io.github.bonigarcia.wdm.webdriver.WebDriverBrowser> webDriverList
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/FirefoxDriverManager.java
|
FirefoxDriverManager
|
getDriverUrls
|
class FirefoxDriverManager extends WebDriverManager {
@Override
public DriverManagerType getDriverManagerType() {
return FIREFOX;
}
@Override
protected String getDriverName() {
return "geckodriver";
}
@Override
protected String getDriverVersion() {
return config().getGeckoDriverVersion();
}
@Override
protected String getBrowserVersion() {
return config().getFirefoxVersion();
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setGeckoDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setFirefoxVersion(browserVersion);
}
@Override
protected URL getDriverUrl() {
return getDriverUrlCkeckingMirror(config().getFirefoxDriverUrl());
}
@Override
protected Optional<URL> getMirrorUrl() {
return Optional.of(config().getFirefoxDriverMirrorUrl());
}
@Override
protected Optional<String> getExportParameter() {
return Optional.of(config().getFirefoxDriverExport());
}
@Override
protected void setDriverUrl(URL url) {
config().setFirefoxDriverUrl(url);
}
@Override
protected List<URL> getDriverUrls(String driverVersion) throws IOException {<FILL_FUNCTION_BODY>}
@Override
protected Optional<String> getLatestDriverVersionFromRepository() {
if (config().isUseBetaVersions()) {
return empty();
} else {
return getDriverVersionFromRepository(empty());
}
}
@Override
protected String getCurrentVersion(URL url) {
int firstDash = url.getFile().indexOf(DASH);
int nextDash = url.getFile().indexOf(DASH, firstDash + 1);
String currentVersion = url.getFile().substring(firstDash + 1,
nextDash);
if (currentVersion.startsWith("v")) {
currentVersion = currentVersion.substring(1);
}
return currentVersion;
}
@Override
protected Optional<String> getDriverVersionFromRepository(
Optional<String> driverVersion) {
URL firefoxDriverUrl = config.getFirefoxDriverGoodVersionsUrl();
try {
log.debug("Reading {} to discover geckodriver version",
firefoxDriverUrl);
GeckodriverSupport versions = Parser.parseJson(httpClient,
firefoxDriverUrl.toString(), GeckodriverSupport.class);
if (resolvedBrowserVersion != null) {
int majorBrowserVersion = Integer
.parseInt(resolvedBrowserVersion);
List<GeckodriverRelease> fileteredList = versions.geckodriverReleases
.stream()
.filter(r -> majorBrowserVersion >= r.minFirefoxVersion
&& (r.maxFirefoxVersion == null
|| (r.maxFirefoxVersion != null
&& majorBrowserVersion <= r.maxFirefoxVersion)))
.collect(toList());
if (!fileteredList.isEmpty()) {
return Optional.of(fileteredList.get(0).geckodriverVersion);
}
}
} catch (Exception e) {
log.warn("Exception getting geckodriver version from {}",
firefoxDriverUrl, e);
}
return empty();
}
@Override
protected Capabilities getCapabilities() {
return new FirefoxOptions();
}
@Override
protected List<File> postDownload(File archive) {
List<File> fileList = super.postDownload(archive);
if (config().getOperatingSystem().isMac()) {
// https://firefox-source-docs.mozilla.org/testing/geckodriver/Notarization.html
log.debug(
"Bypass notarization requirement for geckodriver on Mac OS");
Shell.runAndWait("xattr", "-r", "-d", "com.apple.quarantine",
fileList.iterator().next().toString());
}
return fileList;
}
@Override
public WebDriverManager exportParameter(String exportParameter) {
config().setFirefoxDriverExport(exportParameter);
return this;
}
}
|
if (isUseMirror()) {
String versionPath = driverVersion;
if (!driverVersion.isEmpty() && !driverVersion.equals("0.3.0")) {
versionPath = "v" + versionPath;
}
return getDriversFromMirror(getMirrorUrl().get(), versionPath);
} else {
return getDriversFromGitHub(driverVersion);
}
| 1,222
| 115
| 1,337
|
<methods>public io.github.bonigarcia.wdm.WebDriverManager arch32() ,public io.github.bonigarcia.wdm.WebDriverManager arch64() ,public io.github.bonigarcia.wdm.WebDriverManager architecture(io.github.bonigarcia.wdm.config.Architecture) ,public io.github.bonigarcia.wdm.WebDriverManager arm64() ,public io.github.bonigarcia.wdm.WebDriverManager avoidBrowserDetection() ,public io.github.bonigarcia.wdm.WebDriverManager avoidDockerLocalFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExport() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExternalConnections() ,public io.github.bonigarcia.wdm.WebDriverManager avoidFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidOutputTree() ,public io.github.bonigarcia.wdm.WebDriverManager avoidResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager avoidShutdownHook() ,public io.github.bonigarcia.wdm.WebDriverManager avoidTmpFolder() ,public io.github.bonigarcia.wdm.WebDriverManager avoidUseChromiumDriverSnap() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDocker() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager browserVersion(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionCommand(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionRegex(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager cachePath(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager capabilities(Capabilities) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromedriver() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromiumdriver() ,public io.github.bonigarcia.wdm.WebDriverManager clearDriverCache() ,public io.github.bonigarcia.wdm.WebDriverManager clearResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager commandsPropertiesUrl(java.net.URL) ,public synchronized io.github.bonigarcia.wdm.config.Config config() ,public synchronized WebDriver create() ,public synchronized List<WebDriver> create(int) ,public io.github.bonigarcia.wdm.WebDriverManager disableCsp() ,public io.github.bonigarcia.wdm.WebDriverManager disableTracing() ,public io.github.bonigarcia.wdm.WebDriverManager dockerAvoidPulling() ,public io.github.bonigarcia.wdm.WebDriverManager dockerCustomImage(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDaemonUrl(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDefaultArgs(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerEnvVariables(java.lang.String[]) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerExtraHosts(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager dockerLang(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetwork(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetworkHost() ,public io.github.bonigarcia.wdm.WebDriverManager dockerPrivateEndpoint(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingFrameRate(int) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.nio.file.Path) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingPrefix(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerScreenResolution(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerShmSize(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerStopTimeoutSec(java.lang.Integer) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTimezone(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsMount(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsSize(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerVolumes(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager driverRepositoryUrl(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager driverVersion(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager edgedriver() ,public io.github.bonigarcia.wdm.WebDriverManager enableRecording() ,public io.github.bonigarcia.wdm.WebDriverManager enableVnc() ,public abstract io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager firefoxdriver() ,public io.github.bonigarcia.wdm.WebDriverManager forceDownload() ,public Optional<java.nio.file.Path> getBrowserPath() ,public java.lang.String getDockerBrowserContainerId(WebDriver) ,public java.lang.String getDockerBrowserContainerId() ,public java.net.URL getDockerNoVncUrl(WebDriver) ,public java.net.URL getDockerNoVncUrl() ,public java.nio.file.Path getDockerRecordingPath(WebDriver) ,public java.nio.file.Path getDockerRecordingPath() ,public java.net.URL getDockerSeleniumServerUrl(WebDriver) ,public java.net.URL getDockerSeleniumServerUrl() ,public synchronized io.github.bonigarcia.wdm.docker.DockerService getDockerService() ,public java.lang.String getDockerVncUrl(WebDriver) ,public java.lang.String getDockerVncUrl() ,public java.lang.String getDownloadedDriverPath() ,public java.lang.String getDownloadedDriverVersion() ,public abstract io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() ,public List<java.lang.String> getDriverVersions() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(Class<? extends WebDriver>) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance() ,public List<Map<java.lang.String,java.lang.Object>> getLogs(WebDriver) ,public List<Map<java.lang.String,java.lang.Object>> getLogs() ,public WebDriver getWebDriver() ,public List<WebDriver> getWebDriverList() ,public io.github.bonigarcia.wdm.WebDriverManager gitHubToken(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager iedriver() ,public transient io.github.bonigarcia.wdm.WebDriverManager ignoreDriverVersions(java.lang.String[]) ,public static boolean isDockerAvailable() ,public static boolean isOnline(java.lang.String) ,public static boolean isOnline(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager linux() ,public static org.w3c.dom.Document loadXML(java.io.InputStream) throws org.xml.sax.SAXException, java.io.IOException, javax.xml.parsers.ParserConfigurationException,public io.github.bonigarcia.wdm.WebDriverManager mac() ,public static void main(java.lang.String[]) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager operadriver() ,public io.github.bonigarcia.wdm.WebDriverManager operatingSystem(io.github.bonigarcia.wdm.config.OperatingSystem) ,public io.github.bonigarcia.wdm.WebDriverManager properties(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxy(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyPass(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyUser(java.lang.String) ,public synchronized void quit() ,public synchronized void quit(WebDriver) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.net.URL) ,public void reset() ,public io.github.bonigarcia.wdm.WebDriverManager resolutionCachePath(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager safaridriver() ,public synchronized void setup() ,public void startRecording(WebDriver) ,public void startRecording() ,public void startRecording(WebDriver, java.lang.String) ,public void startRecording(java.lang.String) ,public synchronized void stopDockerRecording() ,public synchronized void stopDockerRecording(WebDriver) ,public void stopRecording(WebDriver) ,public void stopRecording() ,public io.github.bonigarcia.wdm.WebDriverManager timeout(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttl(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttlBrowsers(int) ,public io.github.bonigarcia.wdm.WebDriverManager useBetaVersions() ,public io.github.bonigarcia.wdm.WebDriverManager useLocalCommandsPropertiesFirst() ,public io.github.bonigarcia.wdm.WebDriverManager useMirror() ,public io.github.bonigarcia.wdm.WebDriverManager viewOnly() ,public io.github.bonigarcia.wdm.WebDriverManager watch() ,public io.github.bonigarcia.wdm.WebDriverManager watchAndDisplay() ,public io.github.bonigarcia.wdm.WebDriverManager win() ,public static java.nio.file.Path zipFolder(java.nio.file.Path) <variables>protected static final java.lang.String BROWSER_WATCHER_ID,protected static final java.lang.String CFT_LABEL,protected static final java.lang.String CLI_DOCKER,protected static final java.lang.String CLI_RESOLVER,protected static final java.lang.String CLI_SERVER,protected static final java.lang.String DASH,protected static final java.lang.String IN_DOCKER,protected static final java.lang.String LATEST_RELEASE,protected static final javax.xml.namespace.NamespaceContext S3_NAMESPACE_CONTEXT,protected static final java.lang.String SLASH,protected boolean androidEnabled,protected io.github.bonigarcia.wdm.cache.CacheHandler cacheHandler,protected Capabilities capabilities,protected io.github.bonigarcia.wdm.config.Config config,protected boolean disableCsp,protected boolean displayEnabled,protected boolean dockerEnabled,protected io.github.bonigarcia.wdm.docker.DockerService dockerService,protected java.lang.String downloadedDriverPath,protected java.lang.String downloadedDriverVersion,protected io.github.bonigarcia.wdm.online.Downloader downloader,protected io.github.bonigarcia.wdm.online.HttpClient httpClient,protected boolean isHeadless,protected static final Logger log,protected io.github.bonigarcia.wdm.cache.ResolutionCache resolutionCache,protected java.lang.String resolvedBrowserVersion,protected int retryCount,protected boolean shutdownHook,protected io.github.bonigarcia.wdm.versions.VersionDetector versionDetector,protected boolean watchEnabled,protected io.github.bonigarcia.wdm.webdriver.WebDriverCreator webDriverCreator,protected List<io.github.bonigarcia.wdm.webdriver.WebDriverBrowser> webDriverList
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/InternetExplorerDriverManager.java
|
InternetExplorerDriverManager
|
getCurrentVersion
|
class InternetExplorerDriverManager extends WebDriverManager {
@Override
public DriverManagerType getDriverManagerType() {
return IEXPLORER;
}
protected String getDriverName() {
return "IEDriverServer";
}
@Override
protected String getDriverVersion() {
return config().getIExplorerDriverVersion();
}
@Override
protected String getBrowserVersion() {
return "";
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setIExplorerDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
// Nothing required
}
@Override
protected URL getDriverUrl() {
return config().getIExplorerDriverUrl();
}
@Override
protected Optional<URL> getMirrorUrl() {
return empty();
}
@Override
protected Optional<String> getExportParameter() {
return Optional.of(config().getIExplorerDriverExport());
}
@Override
protected void setDriverUrl(URL url) {
config().setIExplorerDriverUrl(url);
}
@Override
protected List<URL> getDriverUrls(String driverVersion) throws IOException {
List<URL> driverUrls = getDriversFromGitHub(driverVersion);
Collections.sort(driverUrls, new UrlComparator());
return driverUrls;
}
@Override
protected Optional<String> getBrowserVersionFromTheShell() {
return empty();
}
@Override
protected Optional<String> getDriverVersionFromRepository(
Optional<String> driverVersion) {
return empty();
}
@Override
protected NamespaceContext getNamespaceContext() {
return S3_NAMESPACE_CONTEXT;
}
@Override
public Optional<Path> getBrowserPath() {
throw new WebDriverManagerException("The browser path of "
+ getDriverManagerType().getBrowserName()
+ " cannot be found since it is a legacy browser and not maintained in the commands database");
}
@Override
protected Capabilities getCapabilities() {
return new InternetExplorerOptions();
}
@Override
protected String getCurrentVersion(URL url) {<FILL_FUNCTION_BODY>}
@Override
public WebDriverManager exportParameter(String exportParameter) {
config().setIExplorerDriverExport(exportParameter);
return this;
}
}
|
String currentVersion = super.getCurrentVersion(url);
String versionRegex = config().getBrowserVersionDetectionRegex();
return currentVersion.replaceAll(versionRegex, "");
| 731
| 53
| 784
|
<methods>public io.github.bonigarcia.wdm.WebDriverManager arch32() ,public io.github.bonigarcia.wdm.WebDriverManager arch64() ,public io.github.bonigarcia.wdm.WebDriverManager architecture(io.github.bonigarcia.wdm.config.Architecture) ,public io.github.bonigarcia.wdm.WebDriverManager arm64() ,public io.github.bonigarcia.wdm.WebDriverManager avoidBrowserDetection() ,public io.github.bonigarcia.wdm.WebDriverManager avoidDockerLocalFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExport() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExternalConnections() ,public io.github.bonigarcia.wdm.WebDriverManager avoidFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidOutputTree() ,public io.github.bonigarcia.wdm.WebDriverManager avoidResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager avoidShutdownHook() ,public io.github.bonigarcia.wdm.WebDriverManager avoidTmpFolder() ,public io.github.bonigarcia.wdm.WebDriverManager avoidUseChromiumDriverSnap() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDocker() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager browserVersion(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionCommand(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionRegex(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager cachePath(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager capabilities(Capabilities) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromedriver() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromiumdriver() ,public io.github.bonigarcia.wdm.WebDriverManager clearDriverCache() ,public io.github.bonigarcia.wdm.WebDriverManager clearResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager commandsPropertiesUrl(java.net.URL) ,public synchronized io.github.bonigarcia.wdm.config.Config config() ,public synchronized WebDriver create() ,public synchronized List<WebDriver> create(int) ,public io.github.bonigarcia.wdm.WebDriverManager disableCsp() ,public io.github.bonigarcia.wdm.WebDriverManager disableTracing() ,public io.github.bonigarcia.wdm.WebDriverManager dockerAvoidPulling() ,public io.github.bonigarcia.wdm.WebDriverManager dockerCustomImage(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDaemonUrl(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDefaultArgs(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerEnvVariables(java.lang.String[]) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerExtraHosts(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager dockerLang(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetwork(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetworkHost() ,public io.github.bonigarcia.wdm.WebDriverManager dockerPrivateEndpoint(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingFrameRate(int) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.nio.file.Path) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingPrefix(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerScreenResolution(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerShmSize(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerStopTimeoutSec(java.lang.Integer) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTimezone(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsMount(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsSize(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerVolumes(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager driverRepositoryUrl(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager driverVersion(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager edgedriver() ,public io.github.bonigarcia.wdm.WebDriverManager enableRecording() ,public io.github.bonigarcia.wdm.WebDriverManager enableVnc() ,public abstract io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager firefoxdriver() ,public io.github.bonigarcia.wdm.WebDriverManager forceDownload() ,public Optional<java.nio.file.Path> getBrowserPath() ,public java.lang.String getDockerBrowserContainerId(WebDriver) ,public java.lang.String getDockerBrowserContainerId() ,public java.net.URL getDockerNoVncUrl(WebDriver) ,public java.net.URL getDockerNoVncUrl() ,public java.nio.file.Path getDockerRecordingPath(WebDriver) ,public java.nio.file.Path getDockerRecordingPath() ,public java.net.URL getDockerSeleniumServerUrl(WebDriver) ,public java.net.URL getDockerSeleniumServerUrl() ,public synchronized io.github.bonigarcia.wdm.docker.DockerService getDockerService() ,public java.lang.String getDockerVncUrl(WebDriver) ,public java.lang.String getDockerVncUrl() ,public java.lang.String getDownloadedDriverPath() ,public java.lang.String getDownloadedDriverVersion() ,public abstract io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() ,public List<java.lang.String> getDriverVersions() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(Class<? extends WebDriver>) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance() ,public List<Map<java.lang.String,java.lang.Object>> getLogs(WebDriver) ,public List<Map<java.lang.String,java.lang.Object>> getLogs() ,public WebDriver getWebDriver() ,public List<WebDriver> getWebDriverList() ,public io.github.bonigarcia.wdm.WebDriverManager gitHubToken(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager iedriver() ,public transient io.github.bonigarcia.wdm.WebDriverManager ignoreDriverVersions(java.lang.String[]) ,public static boolean isDockerAvailable() ,public static boolean isOnline(java.lang.String) ,public static boolean isOnline(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager linux() ,public static org.w3c.dom.Document loadXML(java.io.InputStream) throws org.xml.sax.SAXException, java.io.IOException, javax.xml.parsers.ParserConfigurationException,public io.github.bonigarcia.wdm.WebDriverManager mac() ,public static void main(java.lang.String[]) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager operadriver() ,public io.github.bonigarcia.wdm.WebDriverManager operatingSystem(io.github.bonigarcia.wdm.config.OperatingSystem) ,public io.github.bonigarcia.wdm.WebDriverManager properties(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxy(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyPass(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyUser(java.lang.String) ,public synchronized void quit() ,public synchronized void quit(WebDriver) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.net.URL) ,public void reset() ,public io.github.bonigarcia.wdm.WebDriverManager resolutionCachePath(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager safaridriver() ,public synchronized void setup() ,public void startRecording(WebDriver) ,public void startRecording() ,public void startRecording(WebDriver, java.lang.String) ,public void startRecording(java.lang.String) ,public synchronized void stopDockerRecording() ,public synchronized void stopDockerRecording(WebDriver) ,public void stopRecording(WebDriver) ,public void stopRecording() ,public io.github.bonigarcia.wdm.WebDriverManager timeout(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttl(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttlBrowsers(int) ,public io.github.bonigarcia.wdm.WebDriverManager useBetaVersions() ,public io.github.bonigarcia.wdm.WebDriverManager useLocalCommandsPropertiesFirst() ,public io.github.bonigarcia.wdm.WebDriverManager useMirror() ,public io.github.bonigarcia.wdm.WebDriverManager viewOnly() ,public io.github.bonigarcia.wdm.WebDriverManager watch() ,public io.github.bonigarcia.wdm.WebDriverManager watchAndDisplay() ,public io.github.bonigarcia.wdm.WebDriverManager win() ,public static java.nio.file.Path zipFolder(java.nio.file.Path) <variables>protected static final java.lang.String BROWSER_WATCHER_ID,protected static final java.lang.String CFT_LABEL,protected static final java.lang.String CLI_DOCKER,protected static final java.lang.String CLI_RESOLVER,protected static final java.lang.String CLI_SERVER,protected static final java.lang.String DASH,protected static final java.lang.String IN_DOCKER,protected static final java.lang.String LATEST_RELEASE,protected static final javax.xml.namespace.NamespaceContext S3_NAMESPACE_CONTEXT,protected static final java.lang.String SLASH,protected boolean androidEnabled,protected io.github.bonigarcia.wdm.cache.CacheHandler cacheHandler,protected Capabilities capabilities,protected io.github.bonigarcia.wdm.config.Config config,protected boolean disableCsp,protected boolean displayEnabled,protected boolean dockerEnabled,protected io.github.bonigarcia.wdm.docker.DockerService dockerService,protected java.lang.String downloadedDriverPath,protected java.lang.String downloadedDriverVersion,protected io.github.bonigarcia.wdm.online.Downloader downloader,protected io.github.bonigarcia.wdm.online.HttpClient httpClient,protected boolean isHeadless,protected static final Logger log,protected io.github.bonigarcia.wdm.cache.ResolutionCache resolutionCache,protected java.lang.String resolvedBrowserVersion,protected int retryCount,protected boolean shutdownHook,protected io.github.bonigarcia.wdm.versions.VersionDetector versionDetector,protected boolean watchEnabled,protected io.github.bonigarcia.wdm.webdriver.WebDriverCreator webDriverCreator,protected List<io.github.bonigarcia.wdm.webdriver.WebDriverBrowser> webDriverList
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/OperaDriverManager.java
|
OperaDriverManager
|
getCapabilities
|
class OperaDriverManager extends WebDriverManager {
protected static final String TAG_NAME_PREFIX = "v.";
// This value is calculated since the Opera major versions are 14 below the
// corresponding operadriver version. For example: Opera 107 -> operadriver
// 121.0.6167.140, Opera 106 -> operadriver 120.0.6099.200, etc.
protected static final int RELATION_OPERA_OPERADRIVER = 14;
@Override
public DriverManagerType getDriverManagerType() {
return OPERA;
}
@Override
protected String getDriverName() {
return "operadriver";
}
@Override
protected String getDriverVersion() {
return config().getOperaDriverVersion();
}
@Override
protected String getBrowserVersion() {
return config().getOperaVersion();
}
@Override
protected void setDriverVersion(String driverVersion) {
config().setOperaDriverVersion(driverVersion);
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setOperaVersion(browserVersion);
}
@Override
protected URL getDriverUrl() {
return getDriverUrlCkeckingMirror(config().getOperaDriverUrl());
}
@Override
protected Optional<URL> getMirrorUrl() {
return Optional.of(config().getOperaDriverMirrorUrl());
}
@Override
protected Optional<String> getExportParameter() {
return Optional.of(config().getOperaDriverExport());
}
@Override
protected void setDriverUrl(URL url) {
config().setOperaDriverUrl(url);
}
@Override
protected Optional<String> getLatestDriverVersionFromRepository() {
if (config().isUseBetaVersions()) {
return empty();
} else {
return getDriverVersionFromRepository(empty());
}
}
@Override
protected String getCurrentVersion(URL url) {
String currentVersion;
if (config().isUseMirror()) {
int i = url.getFile().lastIndexOf(SLASH);
int j = url.getFile().substring(0, i).lastIndexOf(SLASH) + 1;
currentVersion = url.getFile().substring(j, i);
return currentVersion;
} else {
currentVersion = url.getFile().substring(
url.getFile().indexOf(SLASH + "v") + 2,
url.getFile().lastIndexOf(SLASH));
}
if (currentVersion.startsWith(".")) {
currentVersion = currentVersion.substring(1);
}
return currentVersion;
}
@Override
protected List<URL> getDriverUrls(String driverVersion) throws IOException {
if (isUseMirror()) {
String versionPath = driverVersion;
if (!driverVersion.isEmpty()) {
versionPath = driverVersion.startsWith("0") ? "v" + versionPath
: TAG_NAME_PREFIX + versionPath;
}
return getDriversFromMirror(getMirrorUrl().get(), versionPath);
} else {
return getDriversFromGitHub(driverVersion);
}
}
@Override
protected List<File> postDownload(File archive) {
log.trace("Post processing for Opera: {}", archive);
File extractFolder = archive.getParentFile()
.listFiles(getFolderFilter())[0];
if (!extractFolder.isFile()) {
File target;
try {
log.trace("Opera extract folder (to be deleted): {}",
extractFolder);
File[] listFiles = extractFolder.listFiles();
int i = 0;
File operadriver;
boolean isOperaDriver;
do {
if (i >= listFiles.length) {
throw new WebDriverManagerException(
"Driver for Opera not found in zip file");
}
operadriver = listFiles[i];
isOperaDriver = operadriver.getName()
.contains(getDriverName());
i++;
log.trace("{} is valid: {}", operadriver, isOperaDriver);
} while (!isOperaDriver);
log.info("Operadriver: {}", operadriver);
target = new File(archive.getParentFile().getAbsolutePath(),
operadriver.getName());
log.trace("Operadriver target: {}", target);
downloader.renameFile(operadriver, target);
} finally {
downloader.deleteFolder(extractFolder);
}
return singletonList(target);
} else {
return super.postDownload(archive);
}
}
@Override
protected Optional<String> getDriverVersionFromRepository(
Optional<String> driverVersion) {
URL operaDriverUrl = config.getOperaDriverUrl();
try {
log.debug("Reading {} to discover operadriver version",
operaDriverUrl);
GitHubApi[] versions = Parser.parseJson(httpClient,
operaDriverUrl.toString(), GitHubApi[].class);
int majorBrowserVersion = Integer.parseInt(resolvedBrowserVersion);
int majorDriverVersion = majorBrowserVersion
+ RELATION_OPERA_OPERADRIVER;
List<GitHubApi> fileteredList = Arrays.stream(versions)
.filter(r -> r.getTagName()
.startsWith(TAG_NAME_PREFIX + majorDriverVersion))
.collect(toList());
if (!fileteredList.isEmpty()) {
return Optional.of(fileteredList.get(0).getTagName()
.replace(TAG_NAME_PREFIX, ""));
}
} catch (Exception e) {
log.warn("Exception getting operadriver version from {}",
operaDriverUrl, e);
}
return empty();
}
@Override
protected Capabilities getCapabilities() {<FILL_FUNCTION_BODY>}
@Override
public WebDriverManager exportParameter(String exportParameter) {
config().setOperaDriverExport(exportParameter);
return this;
}
}
|
ChromeOptions options = new ChromeOptions();
if (!isUsingDocker()) {
Optional<Path> browserPath = getBrowserPath();
if (browserPath.isPresent()) {
options.setBinary(browserPath.get().toFile());
}
}
return options;
| 1,777
| 82
| 1,859
|
<methods>public io.github.bonigarcia.wdm.WebDriverManager arch32() ,public io.github.bonigarcia.wdm.WebDriverManager arch64() ,public io.github.bonigarcia.wdm.WebDriverManager architecture(io.github.bonigarcia.wdm.config.Architecture) ,public io.github.bonigarcia.wdm.WebDriverManager arm64() ,public io.github.bonigarcia.wdm.WebDriverManager avoidBrowserDetection() ,public io.github.bonigarcia.wdm.WebDriverManager avoidDockerLocalFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExport() ,public io.github.bonigarcia.wdm.WebDriverManager avoidExternalConnections() ,public io.github.bonigarcia.wdm.WebDriverManager avoidFallback() ,public io.github.bonigarcia.wdm.WebDriverManager avoidOutputTree() ,public io.github.bonigarcia.wdm.WebDriverManager avoidResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager avoidShutdownHook() ,public io.github.bonigarcia.wdm.WebDriverManager avoidTmpFolder() ,public io.github.bonigarcia.wdm.WebDriverManager avoidUseChromiumDriverSnap() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDocker() ,public io.github.bonigarcia.wdm.WebDriverManager browserInDockerAndroid() ,public io.github.bonigarcia.wdm.WebDriverManager browserVersion(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionCommand(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager browserVersionDetectionRegex(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager cachePath(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager capabilities(Capabilities) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromedriver() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager chromiumdriver() ,public io.github.bonigarcia.wdm.WebDriverManager clearDriverCache() ,public io.github.bonigarcia.wdm.WebDriverManager clearResolutionCache() ,public io.github.bonigarcia.wdm.WebDriverManager commandsPropertiesUrl(java.net.URL) ,public synchronized io.github.bonigarcia.wdm.config.Config config() ,public synchronized WebDriver create() ,public synchronized List<WebDriver> create(int) ,public io.github.bonigarcia.wdm.WebDriverManager disableCsp() ,public io.github.bonigarcia.wdm.WebDriverManager disableTracing() ,public io.github.bonigarcia.wdm.WebDriverManager dockerAvoidPulling() ,public io.github.bonigarcia.wdm.WebDriverManager dockerCustomImage(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDaemonUrl(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerDefaultArgs(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerEnvVariables(java.lang.String[]) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerExtraHosts(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager dockerLang(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetwork(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerNetworkHost() ,public io.github.bonigarcia.wdm.WebDriverManager dockerPrivateEndpoint(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingFrameRate(int) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingOutput(java.nio.file.Path) ,public io.github.bonigarcia.wdm.WebDriverManager dockerRecordingPrefix(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerScreenResolution(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerShmSize(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerStopTimeoutSec(java.lang.Integer) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTimezone(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsMount(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager dockerTmpfsSize(java.lang.String) ,public transient io.github.bonigarcia.wdm.WebDriverManager dockerVolumes(java.lang.String[]) ,public io.github.bonigarcia.wdm.WebDriverManager driverRepositoryUrl(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager driverVersion(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager edgedriver() ,public io.github.bonigarcia.wdm.WebDriverManager enableRecording() ,public io.github.bonigarcia.wdm.WebDriverManager enableVnc() ,public abstract io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager firefoxdriver() ,public io.github.bonigarcia.wdm.WebDriverManager forceDownload() ,public Optional<java.nio.file.Path> getBrowserPath() ,public java.lang.String getDockerBrowserContainerId(WebDriver) ,public java.lang.String getDockerBrowserContainerId() ,public java.net.URL getDockerNoVncUrl(WebDriver) ,public java.net.URL getDockerNoVncUrl() ,public java.nio.file.Path getDockerRecordingPath(WebDriver) ,public java.nio.file.Path getDockerRecordingPath() ,public java.net.URL getDockerSeleniumServerUrl(WebDriver) ,public java.net.URL getDockerSeleniumServerUrl() ,public synchronized io.github.bonigarcia.wdm.docker.DockerService getDockerService() ,public java.lang.String getDockerVncUrl(WebDriver) ,public java.lang.String getDockerVncUrl() ,public java.lang.String getDownloadedDriverPath() ,public java.lang.String getDownloadedDriverVersion() ,public abstract io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() ,public List<java.lang.String> getDriverVersions() ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(io.github.bonigarcia.wdm.config.DriverManagerType) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance(Class<? extends WebDriver>) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager getInstance() ,public List<Map<java.lang.String,java.lang.Object>> getLogs(WebDriver) ,public List<Map<java.lang.String,java.lang.Object>> getLogs() ,public WebDriver getWebDriver() ,public List<WebDriver> getWebDriverList() ,public io.github.bonigarcia.wdm.WebDriverManager gitHubToken(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager iedriver() ,public transient io.github.bonigarcia.wdm.WebDriverManager ignoreDriverVersions(java.lang.String[]) ,public static boolean isDockerAvailable() ,public static boolean isOnline(java.lang.String) ,public static boolean isOnline(java.net.URL) ,public io.github.bonigarcia.wdm.WebDriverManager linux() ,public static org.w3c.dom.Document loadXML(java.io.InputStream) throws org.xml.sax.SAXException, java.io.IOException, javax.xml.parsers.ParserConfigurationException,public io.github.bonigarcia.wdm.WebDriverManager mac() ,public static void main(java.lang.String[]) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager operadriver() ,public io.github.bonigarcia.wdm.WebDriverManager operatingSystem(io.github.bonigarcia.wdm.config.OperatingSystem) ,public io.github.bonigarcia.wdm.WebDriverManager properties(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxy(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyPass(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager proxyUser(java.lang.String) ,public synchronized void quit() ,public synchronized void quit(WebDriver) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.lang.String) ,public io.github.bonigarcia.wdm.WebDriverManager remoteAddress(java.net.URL) ,public void reset() ,public io.github.bonigarcia.wdm.WebDriverManager resolutionCachePath(java.lang.String) ,public static synchronized io.github.bonigarcia.wdm.WebDriverManager safaridriver() ,public synchronized void setup() ,public void startRecording(WebDriver) ,public void startRecording() ,public void startRecording(WebDriver, java.lang.String) ,public void startRecording(java.lang.String) ,public synchronized void stopDockerRecording() ,public synchronized void stopDockerRecording(WebDriver) ,public void stopRecording(WebDriver) ,public void stopRecording() ,public io.github.bonigarcia.wdm.WebDriverManager timeout(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttl(int) ,public io.github.bonigarcia.wdm.WebDriverManager ttlBrowsers(int) ,public io.github.bonigarcia.wdm.WebDriverManager useBetaVersions() ,public io.github.bonigarcia.wdm.WebDriverManager useLocalCommandsPropertiesFirst() ,public io.github.bonigarcia.wdm.WebDriverManager useMirror() ,public io.github.bonigarcia.wdm.WebDriverManager viewOnly() ,public io.github.bonigarcia.wdm.WebDriverManager watch() ,public io.github.bonigarcia.wdm.WebDriverManager watchAndDisplay() ,public io.github.bonigarcia.wdm.WebDriverManager win() ,public static java.nio.file.Path zipFolder(java.nio.file.Path) <variables>protected static final java.lang.String BROWSER_WATCHER_ID,protected static final java.lang.String CFT_LABEL,protected static final java.lang.String CLI_DOCKER,protected static final java.lang.String CLI_RESOLVER,protected static final java.lang.String CLI_SERVER,protected static final java.lang.String DASH,protected static final java.lang.String IN_DOCKER,protected static final java.lang.String LATEST_RELEASE,protected static final javax.xml.namespace.NamespaceContext S3_NAMESPACE_CONTEXT,protected static final java.lang.String SLASH,protected boolean androidEnabled,protected io.github.bonigarcia.wdm.cache.CacheHandler cacheHandler,protected Capabilities capabilities,protected io.github.bonigarcia.wdm.config.Config config,protected boolean disableCsp,protected boolean displayEnabled,protected boolean dockerEnabled,protected io.github.bonigarcia.wdm.docker.DockerService dockerService,protected java.lang.String downloadedDriverPath,protected java.lang.String downloadedDriverVersion,protected io.github.bonigarcia.wdm.online.Downloader downloader,protected io.github.bonigarcia.wdm.online.HttpClient httpClient,protected boolean isHeadless,protected static final Logger log,protected io.github.bonigarcia.wdm.cache.ResolutionCache resolutionCache,protected java.lang.String resolvedBrowserVersion,protected int retryCount,protected boolean shutdownHook,protected io.github.bonigarcia.wdm.versions.VersionDetector versionDetector,protected boolean watchEnabled,protected io.github.bonigarcia.wdm.webdriver.WebDriverCreator webDriverCreator,protected List<io.github.bonigarcia.wdm.webdriver.WebDriverBrowser> webDriverList
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/managers/SafariDriverManager.java
|
SafariDriverManager
|
manage
|
class SafariDriverManager extends VoidDriverManager {
protected static final Logger log = getLogger(lookup().lookupClass());
@Override
public DriverManagerType getDriverManagerType() {
return SAFARI;
}
@Override
protected String getDriverName() {
return "safaridriver";
}
@Override
protected void manage(String driverVersion) {<FILL_FUNCTION_BODY>}
@Override
protected Capabilities getCapabilities() {
return new SafariOptions();
}
@Override
protected String getBrowserVersion() {
return config().getSafariVersion();
}
@Override
protected void setBrowserVersion(String browserVersion) {
config().setSafariVersion(browserVersion);
}
}
|
log.warn(
"There is no need to manage the driver for the Safari browser (i.e., safaridriver) since it is built-in in Mac OS");
| 236
| 47
| 283
|
<methods>public non-sealed void <init>() ,public io.github.bonigarcia.wdm.WebDriverManager exportParameter(java.lang.String) ,public io.github.bonigarcia.wdm.config.DriverManagerType getDriverManagerType() <variables>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/online/Parser.java
|
Parser
|
parseJson
|
class Parser {
static final Logger log = getLogger(lookup().lookupClass());
private Parser() {
throw new IllegalStateException("Utility class");
}
public static <T> T parseJson(HttpClient client, String url, Class<T> klass)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
HttpGet get = client.createHttpGet(new URL(url));
InputStream content = client.execute(get).getEntity().getContent();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(content))) {
String lines = reader.lines().collect(Collectors.joining());
try {
return new GsonBuilder().create().fromJson(lines, klass);
} catch (JsonSyntaxException cause) {
throw new WebDriverManagerException(
"Bad JSON. First 100 chars " + lines.substring(0, 100),
cause);
}
}
| 93
| 158
| 251
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/online/S3NamespaceContext.java
|
S3NamespaceContext
|
getPrefix
|
class S3NamespaceContext implements NamespaceContext {
private static final String S3_BUCKET_LIST_NS = "http://doc.s3.amazonaws.com/2006-03-01";
private static final String S3_PREFIX = "s3";
@Override
public String getNamespaceURI(String prefix) {
if (S3_PREFIX.equals(prefix)) {
return S3_BUCKET_LIST_NS;
}
throw new IllegalArgumentException("Unsupported prefix");
}
@Override
public String getPrefix(String namespaceURI) {<FILL_FUNCTION_BODY>}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
if (S3_BUCKET_LIST_NS.equals(namespaceURI)) {
return singletonList(S3_PREFIX).iterator();
} else {
return emptyIterator();
}
}
}
|
if (S3_BUCKET_LIST_NS.equals(namespaceURI)) {
return S3_PREFIX;
}
throw new IllegalArgumentException("Unsupported namespace URI");
| 240
| 48
| 288
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/versions/Shell.java
|
Shell
|
runAndWaitArray
|
class Shell {
static final Logger log = getLogger(lookup().lookupClass());
private Shell() {
throw new IllegalStateException("Utility class");
}
public static String runAndWait(String... command) {
return runAndWait(true, command);
}
public static String runAndWait(File folder, String... command) {
return runAndWaitArray(true, folder, command);
}
public static String runAndWait(boolean logCommand, String... command) {
return runAndWaitArray(logCommand, new File("."), command);
}
public static String runAndWait(boolean logCommand, File folder,
String... command) {
return runAndWaitArray(logCommand, folder, command);
}
public static String runAndWaitArray(boolean logCommand, File folder,
String[] command) {<FILL_FUNCTION_BODY>}
public static String runAndWaitNoLog(File folder, String... command) {
String output = "";
try {
Process process = new ProcessBuilder(command).directory(folder)
.redirectErrorStream(false).start();
process.waitFor();
output = IOUtils.toString(process.getInputStream(), UTF_8);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(
"There was a problem executing command <{}> on the shell: {}",
join(" ", command), e.getMessage());
}
}
return output.trim();
}
}
|
String commandStr = Arrays.toString(command);
if (logCommand) {
log.debug("Running command on the shell: {}", commandStr);
}
String result = runAndWaitNoLog(folder, command);
if (logCommand) {
log.debug("Result: {}", result);
}
return result;
| 386
| 87
| 473
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/versions/VersionComparator.java
|
VersionComparator
|
compare
|
class VersionComparator implements Comparator<String> {
final Logger log = getLogger(lookup().lookupClass());
@Override
public int compare(String v1, String v2) {<FILL_FUNCTION_BODY>}
}
|
String[] v1split = v1.split("\\.");
String[] v2split = v2.split("\\.");
int length = max(v1split.length, v2split.length);
for (int i = 0; i < length; i++) {
try {
int v1Part = i < v1split.length ? parseInt(v1split[i]) : 0;
int v2Part = i < v2split.length ? parseInt(v2split[i]) : 0;
if (v1Part < v2Part) {
return -1;
}
if (v1Part > v2Part) {
return 1;
}
} catch (Exception e) {
log.trace("Exception comparing {} with {} ({})", v1, v2,
e.getMessage());
}
}
return 0;
| 66
| 221
| 287
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/webdriver/OptionsWithArguments.java
|
OptionsWithArguments
|
asMap
|
class OptionsWithArguments extends MutableCapabilities {
private static final long serialVersionUID = -5948442823984189597L;
private String capability;
private List<String> args = new ArrayList<>();
public OptionsWithArguments(String browserType, String capability) {
setCapability(CapabilityType.BROWSER_NAME, browserType);
this.capability = capability;
}
public OptionsWithArguments addArguments(String... arguments) {
addArguments(Collections.unmodifiableList(Arrays.asList(arguments)));
return this;
}
public OptionsWithArguments addArguments(List<String> arguments) {
args.addAll(arguments);
return this;
}
@Override
public Map<String, Object> asMap() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> toReturn = new TreeMap<>(super.asMap());
Map<String, Object> options = new TreeMap<>();
options.put("args", Collections.unmodifiableList(args));
toReturn.put(capability, options);
return Collections.unmodifiableMap(toReturn);
| 223
| 83
| 306
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/webdriver/WebDriverBrowser.java
|
WebDriverBrowser
|
getUrl
|
class WebDriverBrowser {
final Logger log = getLogger(lookup().lookupClass());
WebDriver driver;
List<DockerContainer> dockerContainerList;
String browserContainerId;
String noVncUrl;
String vncUrl;
String seleniumServerUrl;
Path recordingPath;
int identityHash;
public WebDriverBrowser() {
this.dockerContainerList = new ArrayList<>();
}
public WebDriverBrowser(WebDriver driver) {
super();
setDriver(driver);
}
public WebDriver getDriver() {
return driver;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
this.identityHash = calculateIdentityHash(driver);
}
public List<DockerContainer> getDockerContainerList() {
return dockerContainerList;
}
public void addDockerContainer(DockerContainer dockerContainer) {
dockerContainerList.add(dockerContainer);
}
public void addDockerContainer(DockerContainer dockerContainer,
int position) {
dockerContainerList.add(position, dockerContainer);
}
public String getBrowserContainerId() {
return browserContainerId;
}
public void setBrowserContainerId(String browserContainerId) {
this.browserContainerId = browserContainerId;
}
public URL getNoVncUrl() {
return getUrl(noVncUrl);
}
public void setNoVncUrl(String noVncUrl) {
this.noVncUrl = noVncUrl;
}
public String getVncUrl() {
return vncUrl;
}
public void setVncUrl(String vncUrl) {
this.vncUrl = vncUrl;
}
public URL getSeleniumServerUrl() {
return getUrl(seleniumServerUrl);
}
public void setSeleniumServerUrl(String seleniumServerUrl) {
this.seleniumServerUrl = seleniumServerUrl;
}
protected URL getUrl(String urlStr) {<FILL_FUNCTION_BODY>}
public Path getRecordingPath() {
return recordingPath;
}
public void setRecordingPath(Path recordingPath) {
this.recordingPath = recordingPath;
}
public int getIdentityHash() {
return identityHash;
}
public int calculateIdentityHash(Object object) {
return System.identityHashCode(object);
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> readLogs() {
return (List<Map<String, Object>>) readJavaScriptVariable(
"console._bwLogs");
}
public Object readJavaScriptVariable(String jsVariable) {
return executeJavaScript("return " + jsVariable + ";");
}
public Object executeJavaScript(String jsCommand) {
return ((JavascriptExecutor) driver).executeScript(jsCommand);
}
public void startRecording() {
((JavascriptExecutor) driver).executeScript(
"window.postMessage({ type: \"startRecording\" });");
}
public void startRecording(String recordingName) {
((JavascriptExecutor) driver).executeScript(
"window.postMessage({ type: \"startRecording\", name: \""
+ recordingName + "\" });");
}
public void stopRecording() {
((JavascriptExecutor) driver).executeScript(
"window.postMessage({ type: \"stopRecording\" } );");
}
}
|
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
log.error("Exception creating URL", e);
}
return url;
| 919
| 56
| 975
|
<no_super_class>
|
bonigarcia_webdrivermanager
|
webdrivermanager/src/main/java/io/github/bonigarcia/wdm/webdriver/WebDriverCreator.java
|
WebDriverCreator
|
createRemoteWebDriver
|
class WebDriverCreator {
final Logger log = getLogger(lookup().lookupClass());
static final int POLL_TIME_SEC = 1;
Config config;
public WebDriverCreator(Config config) {
this.config = config;
}
public synchronized WebDriver createLocalWebDriver(Class<?> browserClass,
Capabilities capabilities)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
WebDriver driver;
if (capabilities != null) {
driver = (WebDriver) browserClass
.getDeclaredConstructor(capabilities.getClass())
.newInstance(capabilities);
} else {
driver = (WebDriver) browserClass.getDeclaredConstructor()
.newInstance();
}
return driver;
}
public WebDriver createRemoteWebDriver(String remoteUrl,
Capabilities capabilities) {<FILL_FUNCTION_BODY>}
public String getSessionId(WebDriver webDriver) {
String sessionId = ((RemoteWebDriver) webDriver).getSessionId()
.toString();
log.debug("The sessionId is {}", sessionId);
return sessionId;
}
}
|
WebDriver webdriver = null;
int waitTimeoutSec = config.getTimeout();
long timeoutMs = System.currentTimeMillis()
+ TimeUnit.SECONDS.toMillis(waitTimeoutSec);
String browserName = capabilities.getBrowserName();
log.debug("Creating WebDriver object for {} at {} with {}", browserName,
remoteUrl, capabilities);
do {
try {
URL url = new URL(remoteUrl);
HttpURLConnection huc = (HttpURLConnection) url
.openConnection();
huc.connect();
int responseCode = huc.getResponseCode();
log.trace("Requesting {} (the response code is {})", remoteUrl,
responseCode);
if (config.getEnableTracing()) {
webdriver = new RemoteWebDriver(url, capabilities);
} else {
webdriver = new RemoteWebDriver(url, capabilities, false);
}
} catch (Exception e1) {
try {
log.trace("{} creating WebDriver object ({})",
e1.getClass().getSimpleName(), e1.getMessage());
if (System.currentTimeMillis() > timeoutMs) {
throw new WebDriverManagerException(
"Timeout of " + waitTimeoutSec
+ " seconds creating WebDriver object",
e1);
}
Thread.sleep(TimeUnit.SECONDS.toMillis(POLL_TIME_SEC));
} catch (InterruptedException e2) {
log.warn("Interrupted exception creating WebDriver object",
e2);
Thread.currentThread().interrupt();
}
}
} while (webdriver == null);
return webdriver;
| 308
| 420
| 728
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/VManageBootstrap.java
|
VManageBootstrap
|
main
|
class VManageBootstrap extends SpringBootServletInitializer {
private final static Logger logger = LoggerFactory.getLogger(VManageBootstrap.class);
private static String[] args;
private static ConfigurableApplicationContext context;
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
// 项目重启
public static void restart() {
context.close();
VManageBootstrap.context = SpringApplication.run(VManageBootstrap.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(VManageBootstrap.class);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setSessionTrackingModes(
Collections.singleton(SessionTrackingMode.COOKIE)
);
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
}
}
|
VManageBootstrap.args = args;
VManageBootstrap.context = SpringApplication.run(VManageBootstrap.class, args);
GitUtil gitUtil1 = SpringBeanFactory.getBean("gitUtil");
logger.info("构建版本: {}", gitUtil1.getBuildVersion());
logger.info("构建时间: {}", gitUtil1.getBuildDate());
logger.info("GIT最后提交时间: {}", gitUtil1.getCommitTime());
| 274
| 130
| 404
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/common/ApiSaveConstant.java
|
ApiSaveConstant
|
getVal
|
class ApiSaveConstant {
public static String getVal(String key) {<FILL_FUNCTION_BODY>}
}
|
String[] keyItemArray = key.split("/");
if (keyItemArray.length <= 1 || !"api".equals(keyItemArray[1])) {
return null;
}
if (keyItemArray.length >= 4) {
switch (keyItemArray[2]) {
case "alarm":
if ("delete".equals(keyItemArray[3])) {
return "删除报警";
}
break;
case "device":
switch (keyItemArray[3]) {
case "config":
if (keyItemArray.length >= 5 && "basicParam".equals(keyItemArray[4])) {
return "[设备配置] 基本配置设置命令";
}
break;
case "control":
switch (keyItemArray[4]) {
case "teleboot":
return "[设备控制] 远程启动";
case "record":
return "[设备控制] 录像控制";
case "guard":
return "[设备控制] 布防/撤防命令";
case "reset_alarm":
return "[设备控制] 报警复位";
case "i_frame":
return "[设备控制] 强制关键帧";
case "home_position":
return "[设备控制] 看守位控制";
default:
return "";
}
case "query":
if (keyItemArray.length <= 5) {
return null;
}
switch (keyItemArray[4]) {
case "devices":
if (keyItemArray.length < 7) {
return null;
}
switch (keyItemArray[6]) {
case "sync":
return "[设备查询] 同步设备通道";
case "delete":
return "[设备查询] 移除设备";
default:
return "";
}
case "channel":
return "[设备查询] 更新通道信息";
case "transport":
return "[设备查询] 修改数据流传输模式";
default:
return "";
}
default:
return "";
}
break;
case "gbStream":
switch (keyItemArray[3]) {
case "del":
return "移除通道与国标的关联";
case "add":
return "添加通道与国标的关联";
default:
return "";
}
case "media":
break;
case "position":
if ("subscribe".equals(keyItemArray[3])) {
return "订阅位置信息";
}
break;
case "platform":
switch (keyItemArray[3]) {
case "save":
return "添加上级平台";
case "delete":
return "移除上级平台";
case "update_channel_for_gb":
return "向上级平台添加国标通道";
case "del_channel_for_gb":
return "从上级平台移除国标通道";
default:
return "";
}
case "platform_gb_stream":
break;
case "play":
switch (keyItemArray[3]) {
case "start":
return "开始点播";
case "stop":
return "停止点播";
case "convert":
return "转码";
case "convertStop":
return "结束转码";
case "broadcast":
return "语音广播";
default:
return "";
}
case "download":
switch (keyItemArray[3]) {
case "start":
return "开始历史媒体下载";
case "stop":
return "停止历史媒体下载";
default:
return "";
}
case "playback":
switch (keyItemArray[3]) {
case "start":
return "开始视频回放";
case "stop":
return "停止视频回放";
default:
return "";
}
case "ptz":
switch (keyItemArray[3]) {
case "control":
return "云台控制";
case "front_end_command":
return "通用前端控制命令";
default:
return "";
}
case "gb_record":
break;
case "onvif":
break;
case "server":
if ("restart".equals(keyItemArray[3])) {
return "重启流媒体服务";
}
break;
case "proxy":
switch (keyItemArray[3]) {
case "save":
return "保存代理";
case "del":
return "移除代理";
case "start":
return "启用代理";
case "stop":
return "停用代理";
default:
return "";
}
case "push":
switch (keyItemArray[3]) {
case "save_to_gb":
return "将推流添加到国标";
case "remove_form_gb":
return "将推流移出到国标";
default:
return "";
}
case "user":
switch (keyItemArray[3]) {
case "login":
return "登录";
case "changePassword":
return "修改密码";
case "add":
return "添加用户";
case "delete":
return "删除用户";
default:
return "";
}
default:
return "";
}
}
return null;
| 34
| 1,373
| 1,407
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/common/CivilCodePo.java
|
CivilCodePo
|
getInstance
|
class CivilCodePo {
private String code;
private String name;
private String parentCode;
public static CivilCodePo getInstance(String[] infoArray) {<FILL_FUNCTION_BODY>}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentCode() {
return parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
}
|
CivilCodePo civilCodePo = new CivilCodePo();
civilCodePo.setCode(infoArray[0]);
civilCodePo.setName(infoArray[1]);
civilCodePo.setParentCode(infoArray[2]);
return civilCodePo;
| 185
| 67
| 252
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/common/InviteInfo.java
|
InviteInfo
|
getInviteInfo
|
class InviteInfo {
private String deviceId;
private String channelId;
private String stream;
private SSRCInfo ssrcInfo;
private String receiveIp;
private Integer receivePort;
private String streamMode;
private InviteSessionType type;
private InviteSessionStatus status;
private StreamInfo streamInfo;
public static InviteInfo getInviteInfo(String deviceId, String channelId, String stream, SSRCInfo ssrcInfo,
String receiveIp, Integer receivePort, String streamMode,
InviteSessionType type, InviteSessionStatus status) {<FILL_FUNCTION_BODY>}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public InviteSessionType getType() {
return type;
}
public void setType(InviteSessionType type) {
this.type = type;
}
public InviteSessionStatus getStatus() {
return status;
}
public void setStatus(InviteSessionStatus status) {
this.status = status;
}
public StreamInfo getStreamInfo() {
return streamInfo;
}
public void setStreamInfo(StreamInfo streamInfo) {
this.streamInfo = streamInfo;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
public SSRCInfo getSsrcInfo() {
return ssrcInfo;
}
public void setSsrcInfo(SSRCInfo ssrcInfo) {
this.ssrcInfo = ssrcInfo;
}
public String getReceiveIp() {
return receiveIp;
}
public void setReceiveIp(String receiveIp) {
this.receiveIp = receiveIp;
}
public Integer getReceivePort() {
return receivePort;
}
public void setReceivePort(Integer receivePort) {
this.receivePort = receivePort;
}
public String getStreamMode() {
return streamMode;
}
public void setStreamMode(String streamMode) {
this.streamMode = streamMode;
}
}
|
InviteInfo inviteInfo = new InviteInfo();
inviteInfo.setDeviceId(deviceId);
inviteInfo.setChannelId(channelId);
inviteInfo.setStream(stream);
inviteInfo.setSsrcInfo(ssrcInfo);
inviteInfo.setReceiveIp(receiveIp);
inviteInfo.setReceivePort(receivePort);
inviteInfo.setStreamMode(streamMode);
inviteInfo.setType(type);
inviteInfo.setStatus(status);
return inviteInfo;
| 651
| 132
| 783
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/common/StreamURL.java
|
StreamURL
|
toString
|
class StreamURL implements Serializable,Cloneable {
@Schema(description = "协议")
private String protocol;
@Schema(description = "主机地址")
private String host;
@Schema(description = "端口")
private int port = -1;
@Schema(description = "定位位置")
private String file;
@Schema(description = "拼接后的地址")
private String url;
public StreamURL() {
}
public StreamURL(String protocol, String host, int port, String file) {
this.protocol = protocol;
this.host = host;
this.port = port;
this.file = file;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getUrl() {
return this.toString();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public StreamURL clone() throws CloneNotSupportedException {
return (StreamURL) super.clone();
}
}
|
if (protocol != null && host != null && port != -1 ) {
return String.format("%s://%s:%s/%s", protocol, host, port, file);
}else {
return null;
}
| 412
| 63
| 475
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ApiAccessFilter.java
|
ApiAccessFilter
|
doFilterInternal
|
class ApiAccessFilter extends OncePerRequestFilter {
private final static Logger logger = LoggerFactory.getLogger(ApiAccessFilter.class);
@Autowired
private UserSetting userSetting;
@Autowired
private ILogService logService;
@Override
protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
/**
* 获取IP地址
*
* @param request 请求
* @return request发起客户端的IP地址
*/
private String getIP(HttpServletRequest request) {
if (request == null) {
return "0.0.0.0";
}
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
String UNKNOWN_IP = "unknown";
if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if (index != -1) {
return XFor.substring(0, index);
} else {
return XFor;
}
}
XFor = Xip;
if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
return XFor;
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}
|
String username = null;
if (SecurityUtils.getUserInfo() == null) {
username = servletRequest.getParameter("username");
}else {
username = SecurityUtils.getUserInfo().getUsername();
}
long start = System.currentTimeMillis(); // 请求进入时间
String uriName = ApiSaveConstant.getVal(servletRequest.getRequestURI());
filterChain.doFilter(servletRequest, servletResponse);
if (uriName != null && userSetting != null && userSetting.getLogInDatabase() != null && userSetting.getLogInDatabase()) {
LogDto logDto = new LogDto();
logDto.setName(uriName);
if (ObjectUtils.isEmpty(username)) {
username = "";
}
logDto.setUsername(username);
logDto.setAddress(servletRequest.getRemoteAddr());
logDto.setResult(HttpStatus.valueOf(servletResponse.getStatus()).toString());
logDto.setTiming(System.currentTimeMillis() - start);
logDto.setType(servletRequest.getMethod());
logDto.setUri(servletRequest.getRequestURI());
logDto.setCreateTime(DateUtil.getNow());
logService.add(logDto);
}
| 657
| 340
| 997
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/CivilCodeFileConf.java
|
CivilCodeFileConf
|
run
|
class CivilCodeFileConf implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(CivilCodeFileConf.class);
@Autowired
@Lazy
private UserSetting userSetting;
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (ObjectUtils.isEmpty(userSetting.getCivilCodeFile())) {
logger.warn("[行政区划] 文件未设置,可能造成目录刷新结果不完整");
return;
}
InputStream inputStream;
if (userSetting.getCivilCodeFile().startsWith("classpath:")){
String filePath = userSetting.getCivilCodeFile().substring("classpath:".length());
ClassPathResource civilCodeFile = new ClassPathResource(filePath);
if (!civilCodeFile.exists()) {
logger.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
return;
}
inputStream = civilCodeFile.getInputStream();
}else {
File civilCodeFile = new File(userSetting.getCivilCodeFile());
if (!civilCodeFile.exists()) {
logger.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
return;
}
inputStream = Files.newInputStream(civilCodeFile.toPath());
}
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream));
int index = -1;
String line;
List<CivilCodePo> civilCodePoList = new ArrayList<>();
while ((line = inputStreamReader.readLine()) != null) {
index ++;
if (index == 0) {
continue;
}
String[] infoArray = line.split(",");
CivilCodePo civilCodePo = CivilCodePo.getInstance(infoArray);
civilCodePoList.add(civilCodePo);
}
CivilCodeUtil.INSTANCE.add(civilCodePoList);
inputStreamReader.close();
inputStream.close();
if (civilCodePoList.isEmpty()) {
logger.warn("[行政区划] 文件内容为空,可能造成目录刷新结果不完整");
}else {
logger.info("[行政区划] 加载成功,共加载数据{}条", civilCodePoList.size());
}
| 88
| 547
| 635
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/CloudRecordTimer.java
|
CloudRecordTimer
|
execute
|
class CloudRecordTimer {
private final static Logger logger = LoggerFactory.getLogger(CloudRecordTimer.class);
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private CloudRecordServiceMapper cloudRecordServiceMapper;
/**
* 定时查询待删除的录像文件
*/
// @Scheduled(fixedRate = 10000) //每五秒执行一次,方便测试
@Scheduled(cron = "0 0 0 * * ?") //每天的0点执行
public void execute(){<FILL_FUNCTION_BODY>}
}
|
logger.info("[录像文件定时清理] 开始清理过期录像文件");
// 获取配置了assist的流媒体节点
List<MediaServer> mediaServerItemList = mediaServerService.getAllOnline();
if (mediaServerItemList.isEmpty()) {
return;
}
long result = 0;
for (MediaServer mediaServerItem : mediaServerItemList) {
Calendar lastCalendar = Calendar.getInstance();
if (mediaServerItem.getRecordDay() > 0) {
lastCalendar.setTime(new Date());
// 获取保存的最后截至日[期,因为每个节点都有一个日期,也就是支持每个节点设置不同的保存日期,
lastCalendar.add(Calendar.DAY_OF_MONTH, -mediaServerItem.getRecordDay());
Long lastDate = lastCalendar.getTimeInMillis();
// 获取到截至日期之前的录像文件列表,文件列表满足未被收藏和保持的。这两个字段目前共能一致,
// 为我自己业务系统相关的代码,大家使用的时候直接使用收藏(collect)这一个类型即可
List<CloudRecordItem> cloudRecordItemList = cloudRecordServiceMapper.queryRecordListForDelete(lastDate, mediaServerItem.getId());
if (cloudRecordItemList.isEmpty()) {
continue;
}
// TODO 后续可以删除空了的过期日期文件夹
for (CloudRecordItem cloudRecordItem : cloudRecordItemList) {
String date = new File(cloudRecordItem.getFilePath()).getParentFile().getName();
boolean deleteResult = mediaServerService.deleteRecordDirectory(mediaServerItem, cloudRecordItem.getApp(),
cloudRecordItem.getStream(), date, cloudRecordItem.getFileName());
if (deleteResult) {
logger.warn("[录像文件定时清理] 删除磁盘文件成功: {}", cloudRecordItem.getFilePath());
}
}
result += cloudRecordServiceMapper.deleteList(cloudRecordItemList);
}
}
logger.info("[录像文件定时清理] 共清理{}个过期录像文件", result);
| 160
| 533
| 693
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/DynamicTask.java
|
DynamicTask
|
contains
|
class DynamicTask {
private final Logger logger = LoggerFactory.getLogger(DynamicTask.class);
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
private final Map<String, Runnable> runnableMap = new ConcurrentHashMap<>();
@PostConstruct
public void DynamicTask() {
threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(300);
threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskScheduler.setAwaitTerminationSeconds(10);
threadPoolTaskScheduler.initialize();
}
/**
* 循环执行的任务
* @param key 任务ID
* @param task 任务
* @param cycleForCatalog 间隔 毫秒
* @return
*/
public void startCron(String key, Runnable task, int cycleForCatalog) {
if(ObjectUtils.isEmpty(key)) {
return;
}
ScheduledFuture<?> future = futureMap.get(key);
if (future != null) {
if (future.isCancelled()) {
logger.debug("任务【{}】已存在但是关闭状态!!!", key);
} else {
logger.debug("任务【{}】已存在且已启动!!!", key);
return;
}
}
// scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, cycleForCatalog表示执行的间隔
future = threadPoolTaskScheduler.scheduleAtFixedRate(task, new Date(System.currentTimeMillis() + cycleForCatalog), cycleForCatalog);
if (future != null){
futureMap.put(key, future);
runnableMap.put(key, task);
logger.debug("任务【{}】启动成功!!!", key);
}else {
logger.debug("任务【{}】启动失败!!!", key);
}
}
/**
* 延时任务
* @param key 任务ID
* @param task 任务
* @param delay 延时 /毫秒
* @return
*/
public void startDelay(String key, Runnable task, int delay) {
if(ObjectUtils.isEmpty(key)) {
return;
}
stop(key);
// 获取执行的时刻
Instant startInstant = Instant.now().plusMillis(TimeUnit.MILLISECONDS.toMillis(delay));
ScheduledFuture future = futureMap.get(key);
if (future != null) {
if (future.isCancelled()) {
logger.debug("任务【{}】已存在但是关闭状态!!!", key);
} else {
logger.debug("任务【{}】已存在且已启动!!!", key);
return;
}
}
// scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, cycleForCatalog表示执行的间隔
future = threadPoolTaskScheduler.schedule(task, startInstant);
if (future != null){
futureMap.put(key, future);
runnableMap.put(key, task);
logger.debug("任务【{}】启动成功!!!", key);
}else {
logger.debug("任务【{}】启动失败!!!", key);
}
}
public boolean stop(String key) {
if(ObjectUtils.isEmpty(key)) {
return false;
}
boolean result = false;
if (!ObjectUtils.isEmpty(futureMap.get(key)) && !futureMap.get(key).isCancelled() && !futureMap.get(key).isDone()) {
result = futureMap.get(key).cancel(false);
futureMap.remove(key);
runnableMap.remove(key);
}
return result;
}
public boolean contains(String key) {<FILL_FUNCTION_BODY>}
public Set<String> getAllKeys() {
return futureMap.keySet();
}
public Runnable get(String key) {
if(ObjectUtils.isEmpty(key)) {
return null;
}
return runnableMap.get(key);
}
/**
* 每五分钟检查失效的任务,并移除
*/
@Scheduled(cron="0 0/5 * * * ?")
public void execute(){
if (futureMap.size() > 0) {
for (String key : futureMap.keySet()) {
ScheduledFuture<?> future = futureMap.get(key);
if (future.isDone() || future.isCancelled()) {
futureMap.remove(key);
runnableMap.remove(key);
}
}
}
}
public boolean isAlive(String key) {
return futureMap.get(key) != null && !futureMap.get(key).isDone() && !futureMap.get(key).isCancelled();
}
}
|
if(ObjectUtils.isEmpty(key)) {
return false;
}
return futureMap.get(key) != null;
| 1,314
| 37
| 1,351
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/GlobalResponseAdvice.java
|
GlobalResponseAdvice
|
beforeBodyWrite
|
class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType, @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType, @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {<FILL_FUNCTION_BODY>}
/**
* 防止返回string时出错
* @return
*/
/*@Bean
public HttpMessageConverters custHttpMessageConverter() {
return new HttpMessageConverters(new FastJsonHttpMessageConverter());
}*/
}
|
// 排除api文档的接口,这个接口不需要统一
String[] excludePath = {"/v3/api-docs","/api/v1","/index/hook","/api/video-"};
for (String path : excludePath) {
if (request.getURI().getPath().startsWith(path)) {
return body;
}
}
if (body instanceof WVPResult) {
return body;
}
if (body instanceof ErrorCode) {
ErrorCode errorCode = (ErrorCode) body;
return new WVPResult<>(errorCode.getCode(), errorCode.getMsg(), null);
}
if (body instanceof String) {
return JSON.toJSONString(WVPResult.success(body));
}
return WVPResult.success(body);
| 197
| 207
| 404
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/MybatisConfig.java
|
MybatisConfig
|
databaseIdProvider
|
class MybatisConfig {
@Autowired
private UserSetting userSetting;
@Bean
public DatabaseIdProvider databaseIdProvider() {<FILL_FUNCTION_BODY>}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, DatabaseIdProvider databaseIdProvider) throws Exception {
final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
if (userSetting.getSqlLog()){
config.setLogImpl(StdOutImpl.class);
}
config.setMapUnderscoreToCamelCase(true);
sqlSessionFactory.setConfiguration(config);
sqlSessionFactory.setDatabaseIdProvider(databaseIdProvider);
return sqlSessionFactory.getObject();
}
}
|
VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("Oracle", "oracle");
properties.setProperty("MySQL", "mysql");
properties.setProperty("DB2", "db2");
properties.setProperty("Derby", "derby");
properties.setProperty("H2", "h2");
properties.setProperty("HSQL", "hsql");
properties.setProperty("Informix", "informix");
properties.setProperty("MS-SQL", "ms-sql");
properties.setProperty("PostgreSQL", "postgresql");
properties.setProperty("Sybase", "sybase");
properties.setProperty("Hana", "hana");
properties.setProperty("DM", "dm");
properties.setProperty("KingbaseES", "kingbase");
properties.setProperty("KingBase8", "kingbase");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
| 227
| 246
| 473
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ProxyServletConfig.java
|
RecordProxyServlet
|
rewriteUrlFromRequest
|
class RecordProxyServlet extends ProxyServlet{
@Override
protected String rewriteQueryStringFromRequest(HttpServletRequest servletRequest, String queryString) {
String queryStr = super.rewriteQueryStringFromRequest(servletRequest, queryString);
MediaServer mediaInfo = getMediaInfoByUri(servletRequest.getRequestURI());
if (mediaInfo == null) {
return null;
}
String remoteHost = String.format("http://%s:%s", mediaInfo.getStreamIp(), mediaInfo.getRecordAssistPort());
if (!ObjectUtils.isEmpty(queryStr)) {
queryStr += "&remoteHost=" + remoteHost;
}else {
queryStr = "remoteHost=" + remoteHost;
}
return queryStr;
}
@Override
protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
HttpRequest proxyRequest) throws IOException {
HttpResponse response = super.doExecute(servletRequest, servletResponse, proxyRequest);
String origin = servletRequest.getHeader("origin");
response.setHeader("Access-Control-Allow-Origin",origin);
response.setHeader("Access-Control-Allow-Credentials","true");
return response;
}
/**
* 异常处理
*/
@Override
protected void handleRequestException(HttpRequest proxyRequest, HttpResponse proxyResponse, Exception e){
try {
super.handleRequestException(proxyRequest, proxyResponse, e);
} catch (ServletException servletException) {
logger.error("录像服务 代理失败: ", e);
} catch (IOException ioException) {
if (ioException instanceof ConnectException) {
logger.error("录像服务 连接失败");
// }else if (ioException instanceof ClientAbortException) {
// /**
// * TODO 使用这个代理库实现代理在遇到代理视频文件时,如果是206结果,会遇到报错蛋市目前功能正常,
// * TODO 暂时去除异常处理。后续使用其他代理框架修改测试
// */
}else {
logger.error("录像服务 代理失败: ", e);
}
} catch (RuntimeException exception){
logger.error("录像服务 代理失败: ", e);
}
}
/**
* 对于为按照格式请求的可以直接返回404
*/
@Override
protected String getTargetUri(HttpServletRequest servletRequest) {
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
String uri = null;
if (mediaInfo != null) {
// String realRequestURI = requestURI.substring(requestURI.indexOf(mediaInfo.getId())+ mediaInfo.getId().length());
uri = String.format("http://%s:%s", mediaInfo.getIp(), mediaInfo.getRecordAssistPort());
}else {
uri = "http://127.0.0.1:" + serverPort +"/index/hook/null"; // 只是一个能返回404的请求而已, 其他的也可以
}
return uri;
}
/**
* 动态替换请求目标
*/
@Override
protected HttpHost getTargetHost(HttpServletRequest servletRequest) {
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
HttpHost host;
if (mediaInfo != null) {
host = new HttpHost(mediaInfo.getIp(), mediaInfo.getRecordAssistPort());
}else {
host = new HttpHost("127.0.0.1", serverPort);
}
return host;
}
/**
* 根据uri获取流媒体信息
*/
MediaServer getMediaInfoByUri(String uri){
String[] split = uri.split("/");
String mediaServerId = split[2];
if ("default".equalsIgnoreCase(mediaServerId)) {
return mediaServerService.getDefaultMediaServer();
}else {
return mediaServerService.getOne(mediaServerId);
}
}
/**
* 去掉url中的标志信息
*/
@Override
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {<FILL_FUNCTION_BODY>}
}
|
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
String url = super.rewriteUrlFromRequest(servletRequest);
if (mediaInfo == null) {
logger.error("[录像服务访问代理],错误:处理url信息时未找到流媒体信息=>{}", requestURI);
return url;
}
if (!ObjectUtils.isEmpty(mediaInfo.getId())) {
url = url.replace(mediaInfo.getId() + "/", "");
}
return url.replace("default/", "");
| 1,095
| 150
| 1,245
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ServiceInfo.java
|
ServiceInfo
|
onApplicationEvent
|
class ServiceInfo implements ApplicationListener<WebServerInitializedEvent> {
private final Logger logger = LoggerFactory.getLogger(ServiceInfo.class);
private static int serverPort;
public static int getServerPort() {
return serverPort;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {<FILL_FUNCTION_BODY>}
public void setServerPort(int serverPort) {
ServiceInfo.serverPort = serverPort;
}
}
|
// 项目启动获取启动的端口号
ServiceInfo.serverPort = event.getWebServer().getPort();
logger.info("项目启动获取启动的端口号: " + ServiceInfo.serverPort);
| 128
| 56
| 184
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SipConfig.java
|
SipConfig
|
getShowIp
|
class SipConfig {
private String ip;
private String showIp;
private Integer port;
private String domain;
private String id;
private String password;
Integer ptzSpeed = 50;
Integer registerTimeInterval = 120;
private boolean alarm;
public void setIp(String ip) {
this.ip = ip;
}
public void setPort(Integer port) {
this.port = port;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setId(String id) {
this.id = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setPtzSpeed(Integer ptzSpeed) {
this.ptzSpeed = ptzSpeed;
}
public void setRegisterTimeInterval(Integer registerTimeInterval) {
this.registerTimeInterval = registerTimeInterval;
}
public String getIp() {
return ip;
}
public Integer getPort() {
return port;
}
public String getDomain() {
return domain;
}
public String getId() {
return id;
}
public String getPassword() {
return password;
}
public Integer getPtzSpeed() {
return ptzSpeed;
}
public Integer getRegisterTimeInterval() {
return registerTimeInterval;
}
public boolean isAlarm() {
return alarm;
}
public void setAlarm(boolean alarm) {
this.alarm = alarm;
}
public String getShowIp() {<FILL_FUNCTION_BODY>}
public void setShowIp(String showIp) {
this.showIp = showIp;
}
}
|
if (this.showIp == null) {
return this.ip;
}
return showIp;
| 449
| 33
| 482
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SipPlatformRunner.java
|
SipPlatformRunner
|
run
|
class SipPlatformRunner implements CommandLineRunner {
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IPlatformService platformService;
@Autowired
private ISIPCommanderForPlatform sipCommanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 获取所有启用的平台
List<ParentPlatform> parentPlatforms = storager.queryEnableParentPlatformList(true);
for (ParentPlatform parentPlatform : parentPlatforms) {
ParentPlatformCatch parentPlatformCatchOld = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId());
// 更新缓存
ParentPlatformCatch parentPlatformCatch = new ParentPlatformCatch();
parentPlatformCatch.setParentPlatform(parentPlatform);
parentPlatformCatch.setId(parentPlatform.getServerGBId());
redisCatchStorage.updatePlatformCatchInfo(parentPlatformCatch);
if (parentPlatformCatchOld != null) {
// 取消订阅
try {
sipCommanderForPlatform.unregister(parentPlatform, parentPlatformCatchOld.getSipTransactionInfo(), null, (eventResult)->{
platformService.login(parentPlatform);
});
} catch (Exception e) {
logger.error("[命令发送失败] 国标级联 注销: {}", e.getMessage());
platformService.offline(parentPlatform, true);
continue;
}
}
// 设置所有平台离线
platformService.offline(parentPlatform, false);
}
| 145
| 318
| 463
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SpringDocConfig.java
|
SpringDocConfig
|
springShopOpenApi
|
class SpringDocConfig {
@Value("${doc.enabled: true}")
private boolean enable;
@Bean
public OpenAPI springShopOpenApi() {<FILL_FUNCTION_BODY>}
/**
* 添加分组
* @return
*/
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("1. 全部")
.packagesToScan("com.genersoft.iot.vmp.vmanager")
.build();
}
@Bean
public GroupedOpenApi publicApi2() {
return GroupedOpenApi.builder()
.group("2. 国标28181")
.packagesToScan("com.genersoft.iot.vmp.vmanager.gb28181")
.build();
}
@Bean
public GroupedOpenApi publicApi3() {
return GroupedOpenApi.builder()
.group("3. 拉流转发")
.packagesToScan("com.genersoft.iot.vmp.vmanager.streamProxy")
.build();
}
@Bean
public GroupedOpenApi publicApi4() {
return GroupedOpenApi.builder()
.group("4. 推流管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.streamPush")
.build();
}
@Bean
public GroupedOpenApi publicApi5() {
return GroupedOpenApi.builder()
.group("4. 服务管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.server")
.build();
}
@Bean
public GroupedOpenApi publicApi6() {
return GroupedOpenApi.builder()
.group("5. 用户管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.user")
.build();
}
}
|
Contact contact = new Contact();
contact.setName("pan");
contact.setEmail("648540858@qq.com");
return new OpenAPI()
.components(new Components()
.addSecuritySchemes(JwtUtils.HEADER, new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.bearerFormat("JWT")))
.info(new Info().title("WVP-PRO 接口文档")
.contact(contact)
.description("开箱即用的28181协议视频平台")
.version("v3.1.0")
.license(new License().name("Apache 2.0").url("http://springdoc.org")));
| 501
| 186
| 687
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SystemInfoTimerTask.java
|
SystemInfoTimerTask
|
execute
|
class SystemInfoTimerTask {
private Logger logger = LoggerFactory.getLogger(SystemInfoTimerTask.class);
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Scheduled(fixedRate = 2000) //每1秒执行一次
public void execute(){<FILL_FUNCTION_BODY>}
}
|
try {
double cpuInfo = SystemInfoUtils.getCpuInfo();
redisCatchStorage.addCpuInfo(cpuInfo);
double memInfo = SystemInfoUtils.getMemInfo();
redisCatchStorage.addMemInfo(memInfo);
Map<String, Double> networkInterfaces = SystemInfoUtils.getNetworkInterfaces();
redisCatchStorage.addNetInfo(networkInterfaces);
List<Map<String, Object>> diskInfo =SystemInfoUtils.getDiskInfo();
redisCatchStorage.addDiskInfo(diskInfo);
} catch (InterruptedException e) {
logger.error("[获取系统信息失败] {}", e.getMessage());
}
| 95
| 174
| 269
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ThreadPoolTaskConfig.java
|
ThreadPoolTaskConfig
|
taskExecutor
|
class ThreadPoolTaskConfig {
public static final int cpuNum = Runtime.getRuntime().availableProcessors();
/**
* 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
* 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
* 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
*/
/**
* 核心线程数(默认线程数)
*/
private static final int corePoolSize = cpuNum;
/**
* 最大线程数
*/
private static final int maxPoolSize = cpuNum*2;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int keepAliveTime = 30;
/**
* 缓冲队列大小
*/
private static final int queueCapacity = 10000;
/**
* 线程池名前缀
*/
private static final String threadNamePrefix = "wvp-";
/**
*
* @return
*/
@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
public ThreadPoolTaskExecutor taskExecutor() {<FILL_FUNCTION_BODY>}
}
|
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
| 380
| 176
| 556
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/VersionInfo.java
|
VersionInfo
|
getVersion
|
class VersionInfo {
@Autowired
GitUtil gitUtil;
public VersionPo getVersion() {<FILL_FUNCTION_BODY>}
}
|
VersionPo versionPo = new VersionPo();
versionPo.setGIT_Revision(gitUtil.getGitCommitId());
versionPo.setGIT_BRANCH(gitUtil.getBranch());
versionPo.setGIT_URL(gitUtil.getGitUrl());
versionPo.setBUILD_DATE(gitUtil.getBuildDate());
versionPo.setGIT_Revision_SHORT(gitUtil.getCommitIdShort());
versionPo.setVersion(gitUtil.getBuildVersion());
versionPo.setGIT_DATE(gitUtil.getCommitTime());
return versionPo;
| 43
| 158
| 201
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/WVPTimerTask.java
|
WVPTimerTask
|
execute
|
class WVPTimerTask {
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Value("${server.port}")
private int serverPort;
@Autowired
private SipConfig sipConfig;
@Scheduled(fixedRate = 2 * 1000) //每3秒执行一次
public void execute(){<FILL_FUNCTION_BODY>}
}
|
JSONObject jsonObject = new JSONObject();
jsonObject.put("ip", sipConfig.getIp());
jsonObject.put("port", serverPort);
redisCatchStorage.updateWVPInfo(jsonObject, 3);
| 112
| 62
| 174
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/exception/SsrcTransactionNotFoundException.java
|
SsrcTransactionNotFoundException
|
getMessage
|
class SsrcTransactionNotFoundException extends Exception{
private String deviceId;
private String channelId;
private String callId;
private String stream;
public SsrcTransactionNotFoundException(String deviceId, String channelId, String callId, String stream) {
this.deviceId = deviceId;
this.channelId = channelId;
this.callId = callId;
this.stream = stream;
}
public String getDeviceId() {
return deviceId;
}
public String getChannelId() {
return channelId;
}
public String getCallId() {
return callId;
}
public String getStream() {
return stream;
}
@Override
public String getMessage() {<FILL_FUNCTION_BODY>}
}
|
StringBuffer msg = new StringBuffer();
msg.append(String.format("缓存事务信息未找到,device:%s channel: %s ", deviceId, channelId));
if (callId != null) {
msg.append(",callId: " + callId);
}
if (stream != null) {
msg.append(",stream: " + stream);
}
return msg.toString();
| 207
| 110
| 317
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/redis/RedisMsgListenConfig.java
|
RedisMsgListenConfig
|
container
|
class RedisMsgListenConfig {
@Autowired
private RedisGpsMsgListener redisGPSMsgListener;
@Autowired
private RedisAlarmMsgListener redisAlarmMsgListener;
@Autowired
private RedisStreamMsgListener redisStreamMsgListener;
@Autowired
private RedisGbPlayMsgListener redisGbPlayMsgListener;
@Autowired
private RedisPushStreamStatusMsgListener redisPushStreamStatusMsgListener;
@Autowired
private RedisPushStreamStatusListMsgListener redisPushStreamListMsgListener;
@Autowired
private RedisPushStreamResponseListener redisPushStreamResponseListener;
@Autowired
private RedisCloseStreamMsgListener redisCloseStreamMsgListener;
@Autowired
private RedisPushStreamCloseResponseListener redisPushStreamCloseResponseListener;
/**
* redis消息监听器容器 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
* 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
*
* @param connectionFactory
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>}
}
|
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(redisGPSMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_GPS));
container.addMessageListener(redisAlarmMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_SUBSCRIBE_ALARM_RECEIVE));
container.addMessageListener(redisStreamMsgListener, new PatternTopic(VideoManagerConstants.WVP_MSG_STREAM_CHANGE_PREFIX + "PUSH"));
container.addMessageListener(redisGbPlayMsgListener, new PatternTopic(RedisGbPlayMsgListener.WVP_PUSH_STREAM_KEY));
container.addMessageListener(redisPushStreamStatusMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_PUSH_STREAM_STATUS_CHANGE));
container.addMessageListener(redisPushStreamListMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_PUSH_STREAM_LIST_CHANGE));
container.addMessageListener(redisPushStreamResponseListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_RESPONSE));
container.addMessageListener(redisCloseStreamMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE));
container.addMessageListener(redisPushStreamCloseResponseListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED));
return container;
| 342
| 432
| 774
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/redis/RedisTemplateConfig.java
|
RedisTemplateConfig
|
redisTemplate
|
class RedisTemplateConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {<FILL_FUNCTION_BODY>}
}
|
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
// 使用fastJson序列化
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
// value值的序列化采用fastJsonRedisSerializer
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
| 51
| 174
| 225
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/AnonymousAuthenticationEntryPoint.java
|
AnonymousAuthenticationEntryPoint
|
commence
|
class AnonymousAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {<FILL_FUNCTION_BODY>}
}
|
String jwt = request.getHeader(JwtUtils.getHeader());
JwtUser jwtUser = JwtUtils.verifyToken(jwt);
String username = jwtUser.getUserName();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, jwtUser.getPassword() );
SecurityContextHolder.getContext().setAuthentication(token);
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", ErrorCode.ERROR401.getCode());
jsonObject.put("msg", ErrorCode.ERROR401.getMsg());
String logUri = "api/user/login";
if (request.getRequestURI().contains(logUri)){
jsonObject.put("msg", e.getMessage());
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try {
response.getWriter().print(jsonObject.toJSONString());
} catch (IOException ioException) {
ioException.printStackTrace();
}
| 55
| 288
| 343
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/DefaultUserDetailsServiceImpl.java
|
DefaultUserDetailsServiceImpl
|
loadUserByUsername
|
class DefaultUserDetailsServiceImpl implements UserDetailsService {
private final static Logger logger = LoggerFactory.getLogger(DefaultUserDetailsServiceImpl.class);
@Autowired
private IUserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isBlank(username)) {
logger.info("登录用户:{} 不存在", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
// 查出密码
User user = userService.getUserByUsername(username);
if (user == null) {
logger.info("登录用户:{} 不存在", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
String password = SecurityUtils.encryptPassword(user.getPassword());
user.setPassword(password);
return new LoginUser(user, LocalDateTime.now());
| 98
| 179
| 277
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java
|
JwtAuthenticationFilter
|
doFilterInternal
|
class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserSetting userSetting;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
}
|
// 忽略登录请求的token验证
String requestURI = request.getRequestURI();
if (requestURI.equalsIgnoreCase("/api/user/login")) {
chain.doFilter(request, response);
return;
}
if (!userSetting.isInterfaceAuthentication()) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, null, new ArrayList<>() );
SecurityContextHolder.getContext().setAuthentication(token);
chain.doFilter(request, response);
return;
}
String jwt = request.getHeader(JwtUtils.getHeader());
// 这里如果没有jwt,继续往后走,因为后面还有鉴权管理器等去判断是否拥有身份凭证,所以是可以放行的
// 没有jwt相当于匿名访问,若有一些接口是需要权限的,则不能访问这些接口
if (StringUtils.isBlank(jwt)) {
jwt = request.getParameter(JwtUtils.getHeader());
if (StringUtils.isBlank(jwt)) {
jwt = request.getHeader(JwtUtils.getApiKeyHeader());
if (StringUtils.isBlank(jwt)) {
chain.doFilter(request, response);
return;
}
}
}
JwtUser jwtUser = JwtUtils.verifyToken(jwt);
String username = jwtUser.getUserName();
// TODO 处理各个状态
switch (jwtUser.getStatus()){
case EXPIRED:
response.setStatus(400);
chain.doFilter(request, response);
// 异常
return;
case EXCEPTION:
// 过期
response.setStatus(400);
chain.doFilter(request, response);
return;
case EXPIRING_SOON:
// 即将过期
// return;
default:
}
// 构建UsernamePasswordAuthenticationToken,这里密码为null,是因为提供了正确的JWT,实现自动登录
User user = new User();
user.setId(jwtUser.getUserId());
user.setUsername(jwtUser.getUserName());
user.setPassword(jwtUser.getPassword());
Role role = new Role();
role.setId(jwtUser.getRoleId());
user.setRole(role);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, jwtUser.getPassword(), new ArrayList<>() );
SecurityContextHolder.getContext().setAuthentication(token);
chain.doFilter(request, response);
| 78
| 658
| 736
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java
|
JwtUtils
|
verifyToken
|
class JwtUtils implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
public static final String HEADER = "access-token";
public static final String API_KEY_HEADER = "api-key";
private static final String AUDIENCE = "Audience";
private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae";
/**
* token过期时间(分钟)
*/
public static final long EXPIRATION_TIME = 30 * 24 * 60;
private static RsaJsonWebKey rsaJsonWebKey;
private static IUserService userService;
private static IUserApiKeyService userApiKeyService;
public static String getApiKeyHeader() {
return API_KEY_HEADER;
}
@Resource
public void setUserService(IUserService userService) {
JwtUtils.userService = userService;
}
@Resource
public void setUserApiKeyService(IUserApiKeyService userApiKeyService) {
JwtUtils.userApiKeyService = userApiKeyService;
}
@Override
public void afterPropertiesSet() {
try {
rsaJsonWebKey = generateRsaJsonWebKey();
} catch (JoseException e) {
logger.error("生成RsaJsonWebKey报错。", e);
}
}
/**
* 创建密钥对
*
* @throws JoseException JoseException
*/
private RsaJsonWebKey generateRsaJsonWebKey() throws JoseException {
RsaJsonWebKey rsaJsonWebKey = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/jwk.json"), StandardCharsets.UTF_8))) {
String jwkJson = reader.readLine();
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwkJson);
List<JsonWebKey> jsonWebKeys = jsonWebKeySet.getJsonWebKeys();
if (!jsonWebKeys.isEmpty()) {
JsonWebKey jsonWebKey = jsonWebKeys.get(0);
if (jsonWebKey instanceof RsaJsonWebKey) {
rsaJsonWebKey = (RsaJsonWebKey) jsonWebKey;
}
}
} catch (Exception e) {
// ignored
}
if (rsaJsonWebKey == null) {
// 生成一个RSA密钥对,该密钥对将用于JWT的签名和验证,包装在JWK中
rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
// 给JWK一个密钥ID
rsaJsonWebKey.setKeyId(keyId);
}
return rsaJsonWebKey;
}
public static String createToken(String username, Long expirationTime, Map<String, Object> extra) {
try {
/*
* “iss” (issuer) 发行人
* “sub” (subject) 主题
* “aud” (audience) 接收方 用户
* “exp” (expiration time) 到期时间
* “nbf” (not before) 在此之前不可用
* “iat” (issued at) jwt的签发时间
*/
JwtClaims claims = new JwtClaims();
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
// 令牌将过期的时间 分钟
if (expirationTime != null) {
claims.setExpirationTimeMinutesInTheFuture(expirationTime);
}
claims.setNotBeforeMinutesInThePast(0);
claims.setSubject("login");
claims.setAudience(AUDIENCE);
//添加自定义参数,必须是字符串类型
claims.setClaim("userName", username);
if (extra != null) {
extra.forEach(claims::setClaim);
}
//jws
JsonWebSignature jws = new JsonWebSignature();
//签名算法RS256
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jws.setKeyIdHeaderValue(keyId);
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getPrivateKey());
//get token
return jws.getCompactSerialization();
} catch (JoseException e) {
logger.error("[Token生成失败]: {}", e.getMessage());
}
return null;
}
public static String createToken(String username, Long expirationTime) {
return createToken(username, expirationTime, null);
}
public static String createToken(String username) {
return createToken(username, EXPIRATION_TIME);
}
public static String getHeader() {
return HEADER;
}
public static JwtUser verifyToken(String token) {<FILL_FUNCTION_BODY>}
}
|
JwtUser jwtUser = new JwtUser();
try {
JwtConsumer consumer = new JwtConsumerBuilder()
//.setRequireExpirationTime()
//.setMaxFutureValidityInMinutes(5256000)
.setAllowedClockSkewInSeconds(30)
.setRequireSubject()
//.setExpectedIssuer("")
.setExpectedAudience(AUDIENCE)
.setVerificationKey(rsaJsonWebKey.getPublicKey())
.build();
JwtClaims claims = consumer.processToClaims(token);
NumericDate expirationTime = claims.getExpirationTime();
if (expirationTime != null) {
// 判断是否即将过期, 默认剩余时间小于5分钟未即将过期
// 剩余时间 (秒)
long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue();
if (timeRemaining < 5 * 60) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON);
} else {
jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
}
} else {
jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
}
Long apiKeyId = claims.getClaimValue("apiKeyId", Long.class);
if (apiKeyId != null) {
UserApiKey userApiKey = userApiKeyService.getUserApiKeyById(apiKeyId.intValue());
if (userApiKey == null || !userApiKey.isEnable()) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
}
}
String username = (String) claims.getClaimValue("userName");
User user = userService.getUserByUsername(username);
jwtUser.setUserName(username);
jwtUser.setPassword(user.getPassword());
jwtUser.setRoleId(user.getRole().getId());
jwtUser.setUserId(user.getId());
return jwtUser;
} catch (InvalidJwtException e) {
if (e.hasErrorCode(ErrorCodes.EXPIRED)) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
} else {
jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION);
}
return jwtUser;
} catch (Exception e) {
logger.error("[Token解析失败]: {}", e.getMessage());
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
return jwtUser;
}
| 1,333
| 704
| 2,037
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java
|
SecurityUtils
|
login
|
class SecurityUtils {
/**
* 描述根据账号密码进行调用security进行认证授权 主动调
* 用AuthenticationManager的authenticate方法实现
* 授权成功后将用户信息存入SecurityContext当中
* @param username 用户名
* @param password 密码
* @param authenticationManager 认证授权管理器,
* @see AuthenticationManager
* @return UserInfo 用户信息
*/
public static LoginUser login(String username, String password, AuthenticationManager authenticationManager) throws AuthenticationException {<FILL_FUNCTION_BODY>}
/**
* 获取当前登录的所有认证信息
* @return
*/
public static Authentication getAuthentication(){
SecurityContext context = SecurityContextHolder.getContext();
return context.getAuthentication();
}
/**
* 获取当前登录用户信息
* @return
*/
public static LoginUser getUserInfo(){
Authentication authentication = getAuthentication();
if(authentication!=null){
Object principal = authentication.getPrincipal();
if(principal!=null && !"anonymousUser".equals(principal.toString())){
User user = (User) principal;
return new LoginUser(user, LocalDateTime.now());
}
}
return null;
}
/**
* 获取当前登录用户ID
* @return
*/
public static int getUserId(){
LoginUser user = getUserInfo();
return user.getId();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
}
|
//使用security框架自带的验证token生成器 也可以自定义。
UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(username,password);
//认证 如果失败,这里会自动异常后返回,所以这里不需要判断返回值是否为空,确定是否登录成功
Authentication authenticate = authenticationManager.authenticate(token);
LoginUser user = (LoginUser) authenticate.getPrincipal();
SecurityContextHolder.getContext().setAuthentication(token);
return user;
| 475
| 132
| 607
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java
|
WebSecurityConfig
|
configure
|
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired
private UserSetting userSetting;
@Autowired
private DefaultUserDetailsServiceImpl userDetailsService;
/**
* 登出成功的处理
*/
@Autowired
private LogoutHandler logoutHandler;
/**
* 未登录的处理
*/
@Autowired
private AnonymousAuthenticationEntryPoint anonymousAuthenticationEntryPoint;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
/**
* 描述: 静态资源放行,这里的放行,是不走 Spring Security 过滤器链
**/
@Override
public void configure(WebSecurity web) {
if (userSetting.isInterfaceAuthentication()) {
ArrayList<String> matchers = new ArrayList<>();
matchers.add("/");
matchers.add("/#/**");
matchers.add("/static/**");
matchers.add("/swagger-ui.html");
matchers.add("/swagger-ui/");
matchers.add("/index.html");
matchers.add("/doc.html");
matchers.add("/webjars/**");
matchers.add("/swagger-resources/**");
matchers.add("/v3/api-docs/**");
matchers.add("/js/**");
matchers.add("/api/device/query/snap/**");
matchers.add("/record_proxy/*/**");
matchers.add("/api/emit");
matchers.add("/favicon.ico");
// 可以直接访问的静态数据
web.ignoring().antMatchers(matchers.toArray(new String[0]));
}
}
/**
* 配置认证方式
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().contentTypeOptions().disable()
.and().cors().configurationSource(configurationSource())
.and().csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 配置拦截规则
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(userSetting.getInterfaceAuthenticationExcludes().toArray(new String[0])).permitAll()
.antMatchers("/api/user/login", "/index/hook/**","/index/hook/abl/**", "/swagger-ui/**", "/doc.html").permitAll()
.anyRequest().authenticated()
// 异常处理器
.and()
.exceptionHandling()
.authenticationEntryPoint(anonymousAuthenticationEntryPoint)
.and().logout().logoutUrl("/api/user/logout").permitAll()
.logoutSuccessHandler(logoutHandler)
;
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
CorsConfigurationSource configurationSource() {
// 配置跨域
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setMaxAge(3600L);
if (userSetting.getAllowedOrigins() != null && !userSetting.getAllowedOrigins().isEmpty()) {
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(userSetting.getAllowedOrigins());
}else {
corsConfiguration.setAllowCredentials(false);
corsConfiguration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
}
corsConfiguration.setExposedHeaders(Arrays.asList(JwtUtils.getHeader()));
UrlBasedCorsConfigurationSource url = new UrlBasedCorsConfigurationSource();
url.registerCorsConfiguration("/**", corsConfiguration);
return url;
}
/**
* 描述: 密码加密算法 BCrypt 推荐使用
**/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 描述: 注入AuthenticationManager管理器
**/
@Override
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
|
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
// 设置不隐藏 未找到用户异常
provider.setHideUserNotFoundExceptions(true);
// 用户认证service - 查询数据库的逻辑
provider.setUserDetailsService(userDetailsService);
// 设置密码加密算法
provider.setPasswordEncoder(passwordEncoder());
auth.authenticationProvider(provider);
| 1,186
| 106
| 1,292
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/SipLayer.java
|
SipLayer
|
getUdpSipProvider
|
class SipLayer implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(SipLayer.class);
@Autowired
private SipConfig sipConfig;
@Autowired
private ISIPProcessorObserver sipProcessorObserver;
@Autowired
private UserSetting userSetting;
private final Map<String, SipProviderImpl> tcpSipProviderMap = new ConcurrentHashMap<>();
private final Map<String, SipProviderImpl> udpSipProviderMap = new ConcurrentHashMap<>();
@Override
public void run(String... args) {
List<String> monitorIps = new ArrayList<>();
// 使用逗号分割多个ip
String separator = ",";
if (sipConfig.getIp().indexOf(separator) > 0) {
String[] split = sipConfig.getIp().split(separator);
monitorIps.addAll(Arrays.asList(split));
}else {
monitorIps.add(sipConfig.getIp());
}
SipFactory.getInstance().setPathName("gov.nist");
if (monitorIps.size() > 0) {
for (String monitorIp : monitorIps) {
addListeningPoint(monitorIp, sipConfig.getPort());
}
if (udpSipProviderMap.size() + tcpSipProviderMap.size() == 0) {
System.exit(1);
}
}
}
private void addListeningPoint(String monitorIp, int port){
SipStackImpl sipStack;
try {
sipStack = (SipStackImpl)SipFactory.getInstance().createSipStack(DefaultProperties.getProperties("GB28181_SIP", userSetting.getSipLog()));
sipStack.setMessageParserFactory(new GbStringMsgParserFactory());
} catch (PeerUnavailableException e) {
logger.error("[SIP SERVER] SIP服务启动失败, 监听地址{}失败,请检查ip是否正确", monitorIp);
return;
}
try {
ListeningPoint tcpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "TCP");
SipProviderImpl tcpSipProvider = (SipProviderImpl)sipStack.createSipProvider(tcpListeningPoint);
tcpSipProvider.setDialogErrorsAutomaticallyHandled();
tcpSipProvider.addSipListener(sipProcessorObserver);
tcpSipProviderMap.put(monitorIp, tcpSipProvider);
logger.info("[SIP SERVER] tcp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException
| TooManyListenersException
| ObjectInUseException
| InvalidArgumentException e) {
logger.error("[SIP SERVER] tcp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port);
}
try {
ListeningPoint udpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "UDP");
SipProviderImpl udpSipProvider = (SipProviderImpl)sipStack.createSipProvider(udpListeningPoint);
udpSipProvider.addSipListener(sipProcessorObserver);
udpSipProviderMap.put(monitorIp, udpSipProvider);
logger.info("[SIP SERVER] udp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException
| TooManyListenersException
| ObjectInUseException
| InvalidArgumentException e) {
logger.error("[SIP SERVER] udp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port);
}
}
public SipProviderImpl getUdpSipProvider(String ip) {
if (ObjectUtils.isEmpty(ip)) {
return null;
}
return udpSipProviderMap.get(ip);
}
public SipProviderImpl getUdpSipProvider() {<FILL_FUNCTION_BODY>}
public SipProviderImpl getTcpSipProvider() {
if (tcpSipProviderMap.size() != 1) {
return null;
}
return tcpSipProviderMap.values().stream().findFirst().get();
}
public SipProviderImpl getTcpSipProvider(String ip) {
if (ObjectUtils.isEmpty(ip)) {
return null;
}
return tcpSipProviderMap.get(ip);
}
public String getLocalIp(String deviceLocalIp) {
if (!ObjectUtils.isEmpty(deviceLocalIp)) {
return deviceLocalIp;
}
return getUdpSipProvider().getListeningPoint().getIPAddress();
}
}
|
if (udpSipProviderMap.size() != 1) {
return null;
}
return udpSipProviderMap.values().stream().findFirst().get();
| 1,269
| 49
| 1,318
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/auth/DigestServerAuthenticationHelper.java
|
DigestServerAuthenticationHelper
|
doAuthenticatePlainTextPassword
|
class DigestServerAuthenticationHelper {
private Logger logger = LoggerFactory.getLogger(DigestServerAuthenticationHelper.class);
private MessageDigest messageDigest;
public static final String DEFAULT_ALGORITHM = "MD5";
public static final String DEFAULT_SCHEME = "Digest";
/** to hex converter */
private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* Default constructor.
* @throws NoSuchAlgorithmException
*/
public DigestServerAuthenticationHelper()
throws NoSuchAlgorithmException {
messageDigest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
}
public static String toHexString(byte b[]) {
int pos = 0;
char[] c = new char[b.length * 2];
for (int i = 0; i < b.length; i++) {
c[pos++] = toHex[(b[i] >> 4) & 0x0F];
c[pos++] = toHex[b[i] & 0x0f];
}
return new String(c);
}
/**
* Generate the challenge string.
*
* @return a generated nonce.
*/
private String generateNonce() {
long time = Instant.now().toEpochMilli();
Random rand = new Random();
long pad = rand.nextLong();
String nonceString = Long.valueOf(time).toString()
+ Long.valueOf(pad).toString();
byte mdbytes[] = messageDigest.digest(nonceString.getBytes());
return toHexString(mdbytes);
}
public Response generateChallenge(HeaderFactory headerFactory, Response response, String realm) {
try {
WWWAuthenticateHeader proxyAuthenticate = headerFactory
.createWWWAuthenticateHeader(DEFAULT_SCHEME);
proxyAuthenticate.setParameter("realm", realm);
proxyAuthenticate.setParameter("qop", "auth");
proxyAuthenticate.setParameter("nonce", generateNonce());
proxyAuthenticate.setParameter("algorithm", DEFAULT_ALGORITHM);
response.setHeader(proxyAuthenticate);
} catch (Exception ex) {
InternalErrorHandler.handleException(ex);
}
return response;
}
/**
* Authenticate the inbound request.
*
* @param request - the request to authenticate.
* @param hashedPassword -- the MD5 hashed string of username:realm:plaintext password.
*
* @return true if authentication succeded and false otherwise.
*/
public boolean doAuthenticateHashedPassword(Request request, String hashedPassword) {
AuthorizationHeader authHeader = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
if ( authHeader == null ) {
return false;
}
String realm = authHeader.getRealm();
String username = authHeader.getUsername();
if ( username == null || realm == null ) {
return false;
}
String nonce = authHeader.getNonce();
URI uri = authHeader.getURI();
if (uri == null) {
return false;
}
String A2 = request.getMethod().toUpperCase() + ":" + uri.toString();
String HA1 = hashedPassword;
byte[] mdbytes = messageDigest.digest(A2.getBytes());
String HA2 = toHexString(mdbytes);
String cnonce = authHeader.getCNonce();
String KD = HA1 + ":" + nonce;
if (cnonce != null) {
KD += ":" + cnonce;
}
KD += ":" + HA2;
mdbytes = messageDigest.digest(KD.getBytes());
String mdString = toHexString(mdbytes);
String response = authHeader.getResponse();
return mdString.equals(response);
}
/**
* Authenticate the inbound request given plain text password.
*
* @param request - the request to authenticate.
* @param pass -- the plain text password.
*
* @return true if authentication succeded and false otherwise.
*/
public boolean doAuthenticatePlainTextPassword(Request request, String pass) {<FILL_FUNCTION_BODY>}
}
|
AuthorizationHeader authHeader = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
if ( authHeader == null || authHeader.getRealm() == null) {
return false;
}
String realm = authHeader.getRealm().trim();
String username = authHeader.getUsername().trim();
if ( username == null || realm == null ) {
return false;
}
String nonce = authHeader.getNonce();
URI uri = authHeader.getURI();
if (uri == null) {
return false;
}
// qop 保护质量 包含auth(默认的)和auth-int(增加了报文完整性检测)两种策略
String qop = authHeader.getQop();
// 客户端随机数,这是一个不透明的字符串值,由客户端提供,并且客户端和服务器都会使用,以避免用明文文本。
// 这使得双方都可以查验对方的身份,并对消息的完整性提供一些保护
String cnonce = authHeader.getCNonce();
// nonce计数器,是一个16进制的数值,表示同一nonce下客户端发送出请求的数量
int nc = authHeader.getNonceCount();
String ncStr = String.format("%08x", nc).toUpperCase();
// String ncStr = new DecimalFormat("00000000").format(nc);
// String ncStr = new DecimalFormat("00000000").format(Integer.parseInt(nc + "", 16));
String A1 = username + ":" + realm + ":" + pass;
String A2 = request.getMethod().toUpperCase() + ":" + uri.toString();
byte mdbytes[] = messageDigest.digest(A1.getBytes());
String HA1 = toHexString(mdbytes);
logger.debug("A1: " + A1);
logger.debug("A2: " + A2);
mdbytes = messageDigest.digest(A2.getBytes());
String HA2 = toHexString(mdbytes);
logger.debug("HA1: " + HA1);
logger.debug("HA2: " + HA2);
// String cnonce = authHeader.getCNonce();
logger.debug("nonce: " + nonce);
logger.debug("nc: " + ncStr);
logger.debug("cnonce: " + cnonce);
logger.debug("qop: " + qop);
String KD = HA1 + ":" + nonce;
if (qop != null && qop.equalsIgnoreCase("auth") ) {
if (nc != -1) {
KD += ":" + ncStr;
}
if (cnonce != null) {
KD += ":" + cnonce;
}
KD += ":" + qop;
}
KD += ":" + HA2;
logger.debug("KD: " + KD);
mdbytes = messageDigest.digest(KD.getBytes());
String mdString = toHexString(mdbytes);
logger.debug("mdString: " + mdString);
String response = authHeader.getResponse();
logger.debug("response: " + response);
return mdString.equals(response);
| 1,179
| 864
| 2,043
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/Gb28181Sdp.java
|
Gb28181Sdp
|
getInstance
|
class Gb28181Sdp {
private SessionDescription baseSdb;
private String ssrc;
private String mediaDescription;
public static Gb28181Sdp getInstance(SessionDescription baseSdb, String ssrc, String mediaDescription) {<FILL_FUNCTION_BODY>}
public SessionDescription getBaseSdb() {
return baseSdb;
}
public void setBaseSdb(SessionDescription baseSdb) {
this.baseSdb = baseSdb;
}
public String getSsrc() {
return ssrc;
}
public void setSsrc(String ssrc) {
this.ssrc = ssrc;
}
public String getMediaDescription() {
return mediaDescription;
}
public void setMediaDescription(String mediaDescription) {
this.mediaDescription = mediaDescription;
}
}
|
Gb28181Sdp gb28181Sdp = new Gb28181Sdp();
gb28181Sdp.setBaseSdb(baseSdb);
gb28181Sdp.setSsrc(ssrc);
gb28181Sdp.setMediaDescription(mediaDescription);
return gb28181Sdp;
| 230
| 107
| 337
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/GbSipDate.java
|
GbSipDate
|
encode
|
class GbSipDate extends SIPDate {
/**
*
*/
private static final long serialVersionUID = 1L;
private Calendar javaCal;
public GbSipDate(long timeMillis) {
this.javaCal = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
Date date = new Date(timeMillis);
this.javaCal.setTime(date);
this.wkday = this.javaCal.get(7);
switch(this.wkday) {
case 1:
this.sipWkDay = "Sun";
break;
case 2:
this.sipWkDay = "Mon";
break;
case 3:
this.sipWkDay = "Tue";
break;
case 4:
this.sipWkDay = "Wed";
break;
case 5:
this.sipWkDay = "Thu";
break;
case 6:
this.sipWkDay = "Fri";
break;
case 7:
this.sipWkDay = "Sat";
break;
default:
InternalErrorHandler.handleException("No date map for wkday " + this.wkday);
}
this.day = this.javaCal.get(5);
this.month = this.javaCal.get(2);
switch(this.month) {
case 0:
this.sipMonth = "Jan";
break;
case 1:
this.sipMonth = "Feb";
break;
case 2:
this.sipMonth = "Mar";
break;
case 3:
this.sipMonth = "Apr";
break;
case 4:
this.sipMonth = "May";
break;
case 5:
this.sipMonth = "Jun";
break;
case 6:
this.sipMonth = "Jul";
break;
case 7:
this.sipMonth = "Aug";
break;
case 8:
this.sipMonth = "Sep";
break;
case 9:
this.sipMonth = "Oct";
break;
case 10:
this.sipMonth = "Nov";
break;
case 11:
this.sipMonth = "Dec";
break;
default:
InternalErrorHandler.handleException("No date map for month " + this.month);
}
this.year = this.javaCal.get(1);
this.hour = this.javaCal.get(11);
this.minute = this.javaCal.get(12);
this.second = this.javaCal.get(13);
}
@Override
public StringBuilder encode(StringBuilder var1) {<FILL_FUNCTION_BODY>}
}
|
String var2;
if (this.month < 9) {
var2 = "0" + (this.month + 1);
} else {
var2 = "" + (this.month + 1);
}
String var3;
if (this.day < 10) {
var3 = "0" + this.day;
} else {
var3 = "" + this.day;
}
String var4;
if (this.hour < 10) {
var4 = "0" + this.hour;
} else {
var4 = "" + this.hour;
}
String var5;
if (this.minute < 10) {
var5 = "0" + this.minute;
} else {
var5 = "" + this.minute;
}
String var6;
if (this.second < 10) {
var6 = "0" + this.second;
} else {
var6 = "" + this.second;
}
int var8 = this.javaCal.get(14);
String var7;
if (var8 < 10) {
var7 = "00" + var8;
} else if (var8 < 100) {
var7 = "0" + var8;
} else {
var7 = "" + var8;
}
return var1.append(this.year).append("-").append(var2).append("-").append(var3).append("T").append(var4).append(":").append(var5).append(":").append(var6).append(".").append(var7);
| 752
| 420
| 1,172
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/RecordItem.java
|
RecordItem
|
compareTo
|
class RecordItem implements Comparable<RecordItem>{
@Schema(description = "设备编号")
private String deviceId;
@Schema(description = "名称")
private String name;
@Schema(description = "文件路径名 (可选)")
private String filePath;
@Schema(description = "录像文件大小,单位:Byte(可选)")
private String fileSize;
@Schema(description = "录像地址(可选)")
private String address;
@Schema(description = "录像开始时间(可选)")
private String startTime;
@Schema(description = "录像结束时间(可选)")
private String endTime;
@Schema(description = "保密属性(必选)缺省为0;0:不涉密,1:涉密")
private int secrecy;
@Schema(description = "录像产生类型(可选)time或alarm 或 manua")
private String type;
@Schema(description = "录像触发者ID(可选)")
private String recorderId;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getSecrecy() {
return secrecy;
}
public void setSecrecy(int secrecy) {
this.secrecy = secrecy;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRecorderId() {
return recorderId;
}
public void setRecorderId(String recorderId) {
this.recorderId = recorderId;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
@Override
public int compareTo(@NotNull RecordItem recordItem) {<FILL_FUNCTION_BODY>}
}
|
TemporalAccessor startTimeNow = DateUtil.formatter.parse(startTime);
TemporalAccessor startTimeParam = DateUtil.formatter.parse(recordItem.getStartTime());
Instant startTimeParamInstant = Instant.from(startTimeParam);
Instant startTimeNowInstant = Instant.from(startTimeNow);
if (startTimeNowInstant.equals(startTimeParamInstant)) {
return 0;
}else if (Instant.from(startTimeParam).isAfter(Instant.from(startTimeNow)) ) {
return -1;
}else {
return 1;
}
| 701
| 168
| 869
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/SubscribeHolder.java
|
SubscribeHolder
|
putCatalogSubscribe
|
class SubscribeHolder {
@Autowired
private DynamicTask dynamicTask;
@Autowired
private UserSetting userSetting;
private final String taskOverduePrefix = "subscribe_overdue_";
private static ConcurrentHashMap<String, SubscribeInfo> catalogMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, SubscribeInfo> mobilePositionMap = new ConcurrentHashMap<>();
public void putCatalogSubscribe(String platformId, SubscribeInfo subscribeInfo) {<FILL_FUNCTION_BODY>}
public SubscribeInfo getCatalogSubscribe(String platformId) {
return catalogMap.get(platformId);
}
public void removeCatalogSubscribe(String platformId) {
catalogMap.remove(platformId);
String taskOverdueKey = taskOverduePrefix + "catalog_" + platformId;
Runnable runnable = dynamicTask.get(taskOverdueKey);
if (runnable instanceof ISubscribeTask) {
ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
subscribeTask.stop(null);
}
// 添加任务处理订阅过期
dynamicTask.stop(taskOverdueKey);
}
public void putMobilePositionSubscribe(String platformId, SubscribeInfo subscribeInfo) {
mobilePositionMap.put(platformId, subscribeInfo);
String key = VideoManagerConstants.SIP_SUBSCRIBE_PREFIX + userSetting.getServerId() + "MobilePosition_" + platformId;
// 添加任务处理GPS定时推送
dynamicTask.startCron(key, new MobilePositionSubscribeHandlerTask(platformId),
subscribeInfo.getGpsInterval() * 1000);
String taskOverdueKey = taskOverduePrefix + "MobilePosition_" + platformId;
if (subscribeInfo.getExpires() > 0) {
// 添加任务处理订阅过期
dynamicTask.startDelay(taskOverdueKey, () -> {
removeMobilePositionSubscribe(subscribeInfo.getId());
},
subscribeInfo.getExpires() * 1000);
}
}
public SubscribeInfo getMobilePositionSubscribe(String platformId) {
return mobilePositionMap.get(platformId);
}
public void removeMobilePositionSubscribe(String platformId) {
mobilePositionMap.remove(platformId);
String key = VideoManagerConstants.SIP_SUBSCRIBE_PREFIX + userSetting.getServerId() + "MobilePosition_" + platformId;
// 结束任务处理GPS定时推送
dynamicTask.stop(key);
String taskOverdueKey = taskOverduePrefix + "MobilePosition_" + platformId;
Runnable runnable = dynamicTask.get(taskOverdueKey);
if (runnable instanceof ISubscribeTask) {
ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
subscribeTask.stop(null);
}
// 添加任务处理订阅过期
dynamicTask.stop(taskOverdueKey);
}
public List<String> getAllCatalogSubscribePlatform() {
List<String> platforms = new ArrayList<>();
if(catalogMap.size() > 0) {
for (String key : catalogMap.keySet()) {
platforms.add(catalogMap.get(key).getId());
}
}
return platforms;
}
public List<String> getAllMobilePositionSubscribePlatform() {
List<String> platforms = new ArrayList<>();
if(!mobilePositionMap.isEmpty()) {
for (String key : mobilePositionMap.keySet()) {
platforms.add(mobilePositionMap.get(key).getId());
}
}
return platforms;
}
public void removeAllSubscribe(String platformId) {
removeMobilePositionSubscribe(platformId);
removeCatalogSubscribe(platformId);
}
}
|
catalogMap.put(platformId, subscribeInfo);
if (subscribeInfo.getExpires() > 0) {
// 添加订阅到期
String taskOverdueKey = taskOverduePrefix + "catalog_" + platformId;
// 添加任务处理订阅过期
dynamicTask.startDelay(taskOverdueKey, () -> removeCatalogSubscribe(subscribeInfo.getId()),
subscribeInfo.getExpires() * 1000);
}
| 981
| 118
| 1,099
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/DefaultProperties.java
|
DefaultProperties
|
getProperties
|
class DefaultProperties {
public static Properties getProperties(String name, boolean sipLog) {<FILL_FUNCTION_BODY>}
}
|
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", name);
// properties.setProperty("javax.sip.IP_ADDRESS", ip);
// 关闭自动会话
properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
/**
* 完整配置参考 gov.nist.javax.sip.SipStackImpl,需要下载源码
* gov/nist/javax/sip/SipStackImpl.class
* sip消息的解析在 gov.nist.javax.sip.stack.UDPMessageChannel的processIncomingDataPacket方法
*/
// * gov/nist/javax/sip/SipStackImpl.class
// 接收所有notify请求,即使没有订阅
properties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true");
properties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false");
properties.setProperty("gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED", "true");
// 为_NULL _对话框传递_终止的_事件
properties.setProperty("gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG", "true");
// 是否自动计算content length的实际长度,默认不计算
properties.setProperty("gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY", "true");
// 会话清理策略
properties.setProperty("gov.nist.javax.sip.RELEASE_REFERENCES_STRATEGY", "Normal");
// 处理由该服务器处理的基于底层TCP的保持生存超时
properties.setProperty("gov.nist.javax.sip.RELIABLE_CONNECTION_KEEP_ALIVE_TIMEOUT", "60");
// 获取实际内容长度,不使用header中的长度信息
properties.setProperty("gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY", "true");
// 线程可重入
properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true");
// 定义应用程序打算多久审计一次 SIP 堆栈,了解其内部线程的健康状况(该属性指定连续审计之间的时间(以毫秒为单位))
properties.setProperty("gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS", "30000");
// properties.setProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", "gov.nist.javax.sip.stack.NioMessageProcessorFactory");
/**
* sip_server_log.log 和 sip_debug_log.log ERROR, INFO, WARNING, OFF, DEBUG, TRACE
*/
Logger logger = LoggerFactory.getLogger(AlarmNotifyMessageHandler.class);
if (sipLog) {
properties.setProperty("gov.nist.javax.sip.STACK_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.StackLoggerImpl");
properties.setProperty("gov.nist.javax.sip.SERVER_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.ServerLoggerImpl");
properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true");
logger.info("[SIP日志]已开启");
}else {
logger.info("[SIP日志]已关闭");
}
return properties;
| 37
| 1,041
| 1,078
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/ServerLoggerImpl.java
|
ServerLoggerImpl
|
setSipStack
|
class ServerLoggerImpl implements ServerLogger {
private boolean showLog = true;
private SIPTransactionStack sipStack;
protected StackLogger stackLogger;
@Override
public void closeLogFile() {
}
@Override
public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送:目标--->" + from:"接收:来自--->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender, long time) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送: 目标->" + from :"接收:来自->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送: 目标->" + from :"接收:来自->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logException(Exception ex) {
if (!showLog) {
return;
}
this.stackLogger.logException(ex);
}
@Override
public void setStackProperties(Properties stackProperties) {
if (!showLog) {
return;
}
String TRACE_LEVEL = stackProperties.getProperty("gov.nist.javax.sip.TRACE_LEVEL");
if (TRACE_LEVEL != null) {
showLog = true;
}
}
@Override
public void setSipStack(SipStack sipStack) {<FILL_FUNCTION_BODY>}
}
|
if (!showLog) {
return;
}
if(sipStack instanceof SIPTransactionStack) {
this.sipStack = (SIPTransactionStack)sipStack;
this.stackLogger = CommonLogger.getLogger(SIPTransactionStack.class);
}
| 609
| 73
| 682
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/StackLoggerImpl.java
|
StackLoggerImpl
|
log
|
class StackLoggerImpl implements StackLogger {
/**
* 完全限定类名(Fully Qualified Class Name),用于定位日志位置
*/
private static final String FQCN = StackLoggerImpl.class.getName();
/**
* 获取栈中类信息(以便底层日志记录系统能够提取正确的位置信息(方法名、行号))
* @return LocationAwareLogger
*/
private static LocationAwareLogger getLocationAwareLogger() {
return (LocationAwareLogger) LoggerFactory.getLogger(new Throwable().getStackTrace()[4].getClassName());
}
/**
* 封装打印日志的位置信息
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message) {<FILL_FUNCTION_BODY>}
/**
* 封装打印日志的位置信息
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message, Throwable throwable) {
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, throwable);
}
@Override
public void logStackTrace() {
}
@Override
public void logStackTrace(int traceLevel) {
System.out.println("traceLevel: " + traceLevel);
}
@Override
public int getLineCount() {
return 0;
}
@Override
public void logException(Throwable ex) {
}
@Override
public void logDebug(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logDebug(String message, Exception ex) {
log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logTrace(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logFatalError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public boolean isLoggingEnabled() {
return true;
}
@Override
public boolean isLoggingEnabled(int logLevel) {
return true;
}
@Override
public void logError(String message, Exception ex) {
log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logWarning(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logInfo(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void disableLogging() {
}
@Override
public void enableLogging() {
}
@Override
public void setBuildTimeStamp(String buildTimeStamp) {
}
@Override
public void setStackProperties(Properties stackProperties) {
}
@Override
public String getLoggerName() {
return null;
}
}
|
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, null);
| 815
| 45
| 860
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/EventPublisher.java
|
EventPublisher
|
catalogEventPublish
|
class EventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
/**
* 设备报警事件
* @param deviceAlarm
*/
public void deviceAlarmEventPublish(DeviceAlarm deviceAlarm) {
AlarmEvent alarmEvent = new AlarmEvent(this);
alarmEvent.setAlarmInfo(deviceAlarm);
applicationEventPublisher.publishEvent(alarmEvent);
}
public void mediaServerOfflineEventPublish(String mediaServerId){
MediaServerOfflineEvent outEvent = new MediaServerOfflineEvent(this);
outEvent.setMediaServerId(mediaServerId);
applicationEventPublisher.publishEvent(outEvent);
}
public void mediaServerOnlineEventPublish(String mediaServerId) {
MediaServerOnlineEvent outEvent = new MediaServerOnlineEvent(this);
outEvent.setMediaServerId(mediaServerId);
applicationEventPublisher.publishEvent(outEvent);
}
public void catalogEventPublish(String platformId, DeviceChannel deviceChannel, String type) {<FILL_FUNCTION_BODY>}
public void requestTimeOut(TimeoutEvent timeoutEvent) {
RequestTimeoutEvent requestTimeoutEvent = new RequestTimeoutEvent(this);
requestTimeoutEvent.setTimeoutEvent(timeoutEvent);
applicationEventPublisher.publishEvent(requestTimeoutEvent);
}
/**
*
* @param platformId
* @param deviceChannels
* @param type
*/
public void catalogEventPublish(String platformId, List<DeviceChannel> deviceChannels, String type) {
CatalogEvent outEvent = new CatalogEvent(this);
List<DeviceChannel> channels = new ArrayList<>();
if (deviceChannels.size() > 1) {
// 数据去重
Set<String> gbIdSet = new HashSet<>();
for (DeviceChannel deviceChannel : deviceChannels) {
if (!gbIdSet.contains(deviceChannel.getChannelId())) {
gbIdSet.add(deviceChannel.getChannelId());
channels.add(deviceChannel);
}
}
}else {
channels = deviceChannels;
}
outEvent.setDeviceChannels(channels);
outEvent.setType(type);
outEvent.setPlatformId(platformId);
applicationEventPublisher.publishEvent(outEvent);
}
public void mobilePositionEventPublish(MobilePosition mobilePosition) {
MobilePositionEvent event = new MobilePositionEvent(this);
event.setMobilePosition(mobilePosition);
applicationEventPublisher.publishEvent(event);
}
public void catalogEventPublishForStream(String platformId, List<GbStream> gbStreams, String type) {
CatalogEvent outEvent = new CatalogEvent(this);
outEvent.setGbStreams(gbStreams);
outEvent.setType(type);
outEvent.setPlatformId(platformId);
applicationEventPublisher.publishEvent(outEvent);
}
public void catalogEventPublishForStream(String platformId, GbStream gbStream, String type) {
List<GbStream> gbStreamList = new ArrayList<>();
gbStreamList.add(gbStream);
catalogEventPublishForStream(platformId, gbStreamList, type);
}
public void recordEndEventPush(RecordInfo recordInfo) {
RecordEndEvent outEvent = new RecordEndEvent(this);
outEvent.setRecordInfo(recordInfo);
applicationEventPublisher.publishEvent(outEvent);
}
}
|
List<DeviceChannel> deviceChannelList = new ArrayList<>();
deviceChannelList.add(deviceChannel);
catalogEventPublish(platformId, deviceChannelList, type);
| 920
| 48
| 968
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/SipSubscribe.java
|
SipSubscribe
|
execute
|
class SipSubscribe {
private final Logger logger = LoggerFactory.getLogger(SipSubscribe.class);
private Map<String, SipSubscribe.Event> errorSubscribes = new ConcurrentHashMap<>();
private Map<String, SipSubscribe.Event> okSubscribes = new ConcurrentHashMap<>();
private Map<String, Instant> okTimeSubscribes = new ConcurrentHashMap<>();
private Map<String, Instant> errorTimeSubscribes = new ConcurrentHashMap<>();
// @Scheduled(cron="*/5 * * * * ?") //每五秒执行一次
// @Scheduled(fixedRate= 100 * 60 * 60 )
@Scheduled(cron="0 0/5 * * * ?") //每5分钟执行一次
public void execute(){<FILL_FUNCTION_BODY>}
public interface Event { void response(EventResult eventResult);
}
/**
*
*/
public enum EventResultType{
// 超时
timeout,
// 回复
response,
// 事务已结束
transactionTerminated,
// 会话已结束
dialogTerminated,
// 设备未找到
deviceNotFoundEvent,
// 消息发送失败
cmdSendFailEvent,
// 消息发送失败
failedToGetPort
}
public static class EventResult<EventObject>{
public int statusCode;
public EventResultType type;
public String msg;
public String callId;
public EventObject event;
public EventResult() {
}
public EventResult(EventObject event) {
this.event = event;
if (event instanceof ResponseEvent) {
ResponseEvent responseEvent = (ResponseEvent)event;
SIPResponse response = (SIPResponse)responseEvent.getResponse();
this.type = EventResultType.response;
if (response != null) {
WarningHeader warningHeader = (WarningHeader)response.getHeader(WarningHeader.NAME);
if (warningHeader != null && !ObjectUtils.isEmpty(warningHeader.getText())) {
this.msg = "";
if (warningHeader.getCode() > 0) {
this.msg += warningHeader.getCode() + ":";
}
if (warningHeader.getAgent() != null) {
this.msg += warningHeader.getCode() + ":";
}
if (warningHeader.getText() != null) {
this.msg += warningHeader.getText();
}
}else {
this.msg = response.getReasonPhrase();
}
this.statusCode = response.getStatusCode();
this.callId = response.getCallIdHeader().getCallId();
}
}else if (event instanceof TimeoutEvent) {
TimeoutEvent timeoutEvent = (TimeoutEvent)event;
this.type = EventResultType.timeout;
this.msg = "消息超时未回复";
this.statusCode = -1024;
if (timeoutEvent.isServerTransaction()) {
this.callId = ((SIPRequest)timeoutEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId();
}else {
this.callId = ((SIPRequest)timeoutEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();
}
}else if (event instanceof TransactionTerminatedEvent) {
TransactionTerminatedEvent transactionTerminatedEvent = (TransactionTerminatedEvent)event;
this.type = EventResultType.transactionTerminated;
this.msg = "事务已结束";
this.statusCode = -1024;
if (transactionTerminatedEvent.isServerTransaction()) {
this.callId = ((SIPRequest)transactionTerminatedEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId();
}else {
this.callId = ((SIPRequest)transactionTerminatedEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();
}
}else if (event instanceof DialogTerminatedEvent) {
DialogTerminatedEvent dialogTerminatedEvent = (DialogTerminatedEvent)event;
this.type = EventResultType.dialogTerminated;
this.msg = "会话已结束";
this.statusCode = -1024;
this.callId = dialogTerminatedEvent.getDialog().getCallId().getCallId();
}else if (event instanceof DeviceNotFoundEvent) {
this.type = EventResultType.deviceNotFoundEvent;
this.msg = "设备未找到";
this.statusCode = -1024;
this.callId = ((DeviceNotFoundEvent) event).getCallId();
}
}
}
public void addErrorSubscribe(String key, SipSubscribe.Event event) {
errorSubscribes.put(key, event);
errorTimeSubscribes.put(key, Instant.now());
}
public void addOkSubscribe(String key, SipSubscribe.Event event) {
okSubscribes.put(key, event);
okTimeSubscribes.put(key, Instant.now());
}
public SipSubscribe.Event getErrorSubscribe(String key) {
return errorSubscribes.get(key);
}
public void removeErrorSubscribe(String key) {
if(key == null){
return;
}
errorSubscribes.remove(key);
errorTimeSubscribes.remove(key);
}
public SipSubscribe.Event getOkSubscribe(String key) {
return okSubscribes.get(key);
}
public void removeOkSubscribe(String key) {
if(key == null){
return;
}
okSubscribes.remove(key);
okTimeSubscribes.remove(key);
}
public int getErrorSubscribesSize(){
return errorSubscribes.size();
}
public int getOkSubscribesSize(){
return okSubscribes.size();
}
}
|
logger.info("[定时任务] 清理过期的SIP订阅信息");
Instant instant = Instant.now().minusMillis(TimeUnit.MINUTES.toMillis(5));
for (String key : okTimeSubscribes.keySet()) {
if (okTimeSubscribes.get(key).isBefore(instant)){
okSubscribes.remove(key);
okTimeSubscribes.remove(key);
}
}
for (String key : errorTimeSubscribes.keySet()) {
if (errorTimeSubscribes.get(key).isBefore(instant)){
errorSubscribes.remove(key);
errorTimeSubscribes.remove(key);
}
}
logger.debug("okTimeSubscribes.size:{}",okTimeSubscribes.size());
logger.debug("okSubscribes.size:{}",okSubscribes.size());
logger.debug("errorTimeSubscribes.size:{}",errorTimeSubscribes.size());
logger.debug("errorSubscribes.size:{}",errorSubscribes.size());
| 1,543
| 294
| 1,837
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/alarm/AlarmEventListener.java
|
AlarmEventListener
|
onApplicationEvent
|
class AlarmEventListener implements ApplicationListener<AlarmEvent> {
private static final Logger logger = LoggerFactory.getLogger(AlarmEventListener.class);
private static final Map<String, PrintWriter> SSE_CACHE = new ConcurrentHashMap<>();
public void addSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.put(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size());
}
public void removeSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.remove(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size());
}
@Override
public void onApplicationEvent(@NotNull AlarmEvent event) {<FILL_FUNCTION_BODY>}
}
|
if (logger.isDebugEnabled()) {
logger.debug("设备报警事件触发, deviceId: {}, {}", event.getAlarmInfo().getDeviceId(), event.getAlarmInfo().getAlarmDescription());
}
String msg = "<strong>设备编号:</strong> <i>" + event.getAlarmInfo().getDeviceId() + "</i>"
+ "<br><strong>通道编号:</strong> <i>" + event.getAlarmInfo().getChannelId() + "</i>"
+ "<br><strong>报警描述:</strong> <i>" + event.getAlarmInfo().getAlarmDescription() + "</i>"
+ "<br><strong>报警时间:</strong> <i>" + event.getAlarmInfo().getAlarmTime() + "</i>";
for (Iterator<Map.Entry<String, PrintWriter>> it = SSE_CACHE.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, PrintWriter> response = it.next();
logger.info("推送到 SSE 连接, 浏览器 ID: {}", response.getKey());
try {
PrintWriter writer = response.getValue();
if (writer.checkError()) {
it.remove();
continue;
}
String sseMsg = "event:message\n" +
"data:" + msg + "\n" +
"\n";
writer.write(sseMsg);
writer.flush();
} catch (Exception e) {
it.remove();
}
}
| 224
| 413
| 637
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/device/RequestTimeoutEventImpl.java
|
RequestTimeoutEventImpl
|
onApplicationEvent
|
class RequestTimeoutEventImpl implements ApplicationListener<RequestTimeoutEvent> {
@Autowired
private IDeviceService deviceService;
@Override
public void onApplicationEvent(RequestTimeoutEvent event) {<FILL_FUNCTION_BODY>}
}
|
ClientTransaction clientTransaction = event.getTimeoutEvent().getClientTransaction();
if (clientTransaction != null) {
Request request = clientTransaction.getRequest();
if (request != null) {
String host = ((SipURI) request.getRequestURI()).getHost();
int port = ((SipURI) request.getRequestURI()).getPort();
Device device = deviceService.getDeviceByHostAndPort(host, port);
if (device == null) {
return;
}
deviceService.offline(device.getDeviceId(), "等待消息超时");
}
}
| 65
| 152
| 217
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/record/RecordEndEventListener.java
|
RecordEndEventListener
|
onApplicationEvent
|
class RecordEndEventListener implements ApplicationListener<RecordEndEvent> {
private final static Logger logger = LoggerFactory.getLogger(RecordEndEventListener.class);
private Map<String, RecordEndEventHandler> handlerMap = new ConcurrentHashMap<>();
public interface RecordEndEventHandler{
void handler(RecordInfo recordInfo);
}
@Override
public void onApplicationEvent(RecordEndEvent event) {<FILL_FUNCTION_BODY>}
/**
* 添加
* @param device
* @param channelId
* @param recordEndEventHandler
*/
public void addEndEventHandler(String device, String channelId, RecordEndEventHandler recordEndEventHandler) {
logger.info("录像查询事件添加监听,deviceId:{}, channelId: {}", device, channelId);
handlerMap.put(device + channelId, recordEndEventHandler);
}
/**
* 添加
* @param device
* @param channelId
*/
public void delEndEventHandler(String device, String channelId) {
logger.info("录像查询事件移除监听,deviceId:{}, channelId: {}", device, channelId);
handlerMap.remove(device + channelId);
}
}
|
String deviceId = event.getRecordInfo().getDeviceId();
String channelId = event.getRecordInfo().getChannelId();
int count = event.getRecordInfo().getCount();
int sumNum = event.getRecordInfo().getSumNum();
logger.info("录像查询完成事件触发,deviceId:{}, channelId: {}, 录像数量{}/{}条", event.getRecordInfo().getDeviceId(),
event.getRecordInfo().getChannelId(), count,sumNum);
if (!handlerMap.isEmpty()) {
RecordEndEventHandler handler = handlerMap.get(deviceId + channelId);
logger.info("录像查询完成事件触发, 发送订阅,deviceId:{}, channelId: {}",
event.getRecordInfo().getDeviceId(), event.getRecordInfo().getChannelId());
if (handler !=null){
handler.handler(event.getRecordInfo());
if (count ==sumNum){
handlerMap.remove(deviceId + channelId);
}
}
}
| 316
| 261
| 577
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/subscribe/mobilePosition/MobilePositionEventLister.java
|
MobilePositionEventLister
|
onApplicationEvent
|
class MobilePositionEventLister implements ApplicationListener<MobilePositionEvent> {
private final static Logger logger = LoggerFactory.getLogger(MobilePositionEventLister.class);
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform sipCommanderFroPlatform;
@Autowired
private SubscribeHolder subscribeHolder;
@Override
public void onApplicationEvent(MobilePositionEvent event) {<FILL_FUNCTION_BODY>}
}
|
// 获取所用订阅
List<String> platforms = subscribeHolder.getAllMobilePositionSubscribePlatform();
if (platforms.isEmpty()) {
return;
}
List<ParentPlatform> parentPlatformsForGB = storager.queryPlatFormListForGBWithGBId(event.getMobilePosition().getChannelId(), platforms);
for (ParentPlatform platform : parentPlatformsForGB) {
logger.info("[向上级发送MobilePosition] 通道:{},平台:{}, 位置: {}:{}", event.getMobilePosition().getChannelId(),
platform.getServerGBId(), event.getMobilePosition().getLongitude(), event.getMobilePosition().getLatitude());
SubscribeInfo subscribe = subscribeHolder.getMobilePositionSubscribe(platform.getServerGBId());
try {
sipCommanderFroPlatform.sendNotifyMobilePosition(platform, GPSMsgInfo.getInstance(event.getMobilePosition()),
subscribe);
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 Catalog通知: {}", e.getMessage());
}
}
| 133
| 301
| 434
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/AudioBroadcastManager.java
|
AudioBroadcastManager
|
exit
|
class AudioBroadcastManager {
private final static Logger logger = LoggerFactory.getLogger(AudioBroadcastManager.class);
@Autowired
private SipConfig config;
public static Map<String, AudioBroadcastCatch> data = new ConcurrentHashMap<>();
public void update(AudioBroadcastCatch audioBroadcastCatch) {
if (SipUtils.isFrontEnd(audioBroadcastCatch.getDeviceId())) {
audioBroadcastCatch.setChannelId(audioBroadcastCatch.getDeviceId());
data.put(audioBroadcastCatch.getDeviceId(), audioBroadcastCatch);
}else {
data.put(audioBroadcastCatch.getDeviceId() + audioBroadcastCatch.getChannelId(), audioBroadcastCatch);
}
}
public void del(String deviceId, String channelId) {
if (SipUtils.isFrontEnd(deviceId)) {
data.remove(deviceId);
}else {
data.remove(deviceId + channelId);
}
}
public void delByDeviceId(String deviceId) {
for (String key : data.keySet()) {
if (key.startsWith(deviceId)) {
data.remove(key);
}
}
}
public List<AudioBroadcastCatch> getAll(){
Collection<AudioBroadcastCatch> values = data.values();
return new ArrayList<>(values);
}
public boolean exit(String deviceId, String channelId) {<FILL_FUNCTION_BODY>}
public AudioBroadcastCatch get(String deviceId, String channelId) {
AudioBroadcastCatch audioBroadcastCatch;
if (SipUtils.isFrontEnd(deviceId)) {
audioBroadcastCatch = data.get(deviceId);
}else {
audioBroadcastCatch = data.get(deviceId + channelId);
}
if (audioBroadcastCatch == null) {
Stream<AudioBroadcastCatch> allAudioBroadcastCatchStreamForDevice = data.values().stream().filter(
audioBroadcastCatchItem -> Objects.equals(audioBroadcastCatchItem.getDeviceId(), deviceId));
List<AudioBroadcastCatch> audioBroadcastCatchList = allAudioBroadcastCatchStreamForDevice.collect(Collectors.toList());
if (audioBroadcastCatchList.size() == 1 && Objects.equals(config.getId(), channelId)) {
audioBroadcastCatch = audioBroadcastCatchList.get(0);
}
}
return audioBroadcastCatch;
}
public List<AudioBroadcastCatch> get(String deviceId) {
List<AudioBroadcastCatch> audioBroadcastCatchList= new ArrayList<>();
if (SipUtils.isFrontEnd(deviceId)) {
if (data.get(deviceId) != null) {
audioBroadcastCatchList.add(data.get(deviceId));
}
}else {
for (String key : data.keySet()) {
if (key.startsWith(deviceId)) {
audioBroadcastCatchList.add(data.get(key));
}
}
}
return audioBroadcastCatchList;
}
}
|
for (String key : data.keySet()) {
if (SipUtils.isFrontEnd(deviceId)) {
return key.equals(deviceId);
}else {
return key.equals(deviceId + channelId);
}
}
return false;
| 868
| 72
| 940
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/CatalogDataCatch.java
|
CatalogDataCatch
|
timerTask
|
class CatalogDataCatch {
public static Map<String, CatalogData> data = new ConcurrentHashMap<>();
@Autowired
private IVideoManagerStorage storager;
public void addReady(Device device, int sn ) {
CatalogData catalogData = data.get(device.getDeviceId());
if (catalogData == null || catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end)) {
catalogData = new CatalogData();
catalogData.setChannelList(Collections.synchronizedList(new ArrayList<>()));
catalogData.setDevice(device);
catalogData.setSn(sn);
catalogData.setStatus(CatalogData.CatalogDataStatus.ready);
catalogData.setLastTime(Instant.now());
data.put(device.getDeviceId(), catalogData);
}
}
public void put(String deviceId, int sn, int total, Device device, List<DeviceChannel> deviceChannelList) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
catalogData = new CatalogData();
catalogData.setSn(sn);
catalogData.setTotal(total);
catalogData.setDevice(device);
catalogData.setChannelList(deviceChannelList);
catalogData.setStatus(CatalogData.CatalogDataStatus.runIng);
catalogData.setLastTime(Instant.now());
data.put(deviceId, catalogData);
}else {
// 同一个设备的通道同步请求只考虑一个,其他的直接忽略
if (catalogData.getSn() != sn) {
return;
}
catalogData.setTotal(total);
catalogData.setDevice(device);
catalogData.setStatus(CatalogData.CatalogDataStatus.runIng);
catalogData.getChannelList().addAll(deviceChannelList);
catalogData.setLastTime(Instant.now());
}
}
public List<DeviceChannel> get(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return null;
}
return catalogData.getChannelList();
}
public int getTotal(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return 0;
}
return catalogData.getTotal();
}
public SyncStatus getSyncStatus(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return null;
}
SyncStatus syncStatus = new SyncStatus();
syncStatus.setCurrent(catalogData.getChannelList().size());
syncStatus.setTotal(catalogData.getTotal());
syncStatus.setErrorMsg(catalogData.getErrorMsg());
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end)) {
syncStatus.setSyncIng(false);
}else {
syncStatus.setSyncIng(true);
}
return syncStatus;
}
public boolean isSyncRunning(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return false;
}
return !catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end);
}
@Scheduled(fixedRate = 5 * 1000) //每5秒执行一次, 发现数据5秒未更新则移除数据并认为数据接收超时
private void timerTask(){<FILL_FUNCTION_BODY>}
public void setChannelSyncEnd(String deviceId, String errorMsg) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return;
}
catalogData.setStatus(CatalogData.CatalogDataStatus.end);
catalogData.setErrorMsg(errorMsg);
}
}
|
Set<String> keys = data.keySet();
Instant instantBefore5S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(5));
Instant instantBefore30S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(30));
for (String deviceId : keys) {
CatalogData catalogData = data.get(deviceId);
if ( catalogData.getLastTime().isBefore(instantBefore5S)) {
// 超过五秒收不到消息任务超时, 只更新这一部分数据, 收到数据与声明的总数一致,则重置通道数据,数据不全则只对收到的数据做更新操作
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.runIng)) {
if (catalogData.getTotal() == catalogData.getChannelList().size()) {
storager.resetChannels(catalogData.getDevice().getDeviceId(), catalogData.getChannelList());
}else {
storager.updateChannels(catalogData.getDevice().getDeviceId(), catalogData.getChannelList());
}
String errorMsg = "更新成功,共" + catalogData.getTotal() + "条,已更新" + catalogData.getChannelList().size() + "条";
catalogData.setErrorMsg(errorMsg);
if (catalogData.getTotal() != catalogData.getChannelList().size()) {
}
}else if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.ready)) {
String errorMsg = "同步失败,等待回复超时";
catalogData.setErrorMsg(errorMsg);
}
catalogData.setStatus(CatalogData.CatalogDataStatus.end);
}
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end) && catalogData.getLastTime().isBefore(instantBefore30S)) { // 超过三十秒,如果标记为end则删除
data.remove(deviceId);
}
}
| 1,026
| 523
| 1,549
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/CommonSessionManager.java
|
CommonSession
|
add
|
class CommonSession{
public String session;
public long createTime;
public int timeout;
public CommonCallback<Object> callback;
public CommonCallback<String> timeoutCallback;
}
/**
* 添加回调
* @param sessionId 唯一标识
* @param callback 回调
* @param timeout 超时时间, 单位分钟
*/
public void add(String sessionId, CommonCallback<Object> callback, CommonCallback<String> timeoutCallback,
Integer timeout) {<FILL_FUNCTION_BODY>
|
CommonSession commonSession = new CommonSession();
commonSession.session = sessionId;
commonSession.callback = callback;
commonSession.createTime = System.currentTimeMillis();
if (timeoutCallback != null) {
commonSession.timeoutCallback = timeoutCallback;
}
if (timeout != null) {
commonSession.timeout = timeout;
}
callbackMap.put(sessionId, commonSession);
| 139
| 108
| 247
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/RecordDataCatch.java
|
RecordDataCatch
|
put
|
class RecordDataCatch {
public static Map<String, RecordInfo> data = new ConcurrentHashMap<>();
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private RecordEndEventListener recordEndEventListener;
public int put(String deviceId,String channelId, String sn, int sumNum, List<RecordItem> recordItems) {<FILL_FUNCTION_BODY>}
@Scheduled(fixedRate = 5 * 1000) //每5秒执行一次, 发现数据5秒未更新则移除数据并认为数据接收超时
private void timerTask(){
Set<String> keys = data.keySet();
// 获取五秒前的时刻
Instant instantBefore5S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(5));
for (String key : keys) {
RecordInfo recordInfo = data.get(key);
// 超过五秒收不到消息任务超时, 只更新这一部分数据
if ( recordInfo.getLastTime().isBefore(instantBefore5S)) {
// 处理录像数据, 返回给前端
String msgKey = DeferredResultHolder.CALLBACK_CMD_RECORDINFO + recordInfo.getDeviceId() + recordInfo.getSn();
// 对数据进行排序
Collections.sort(recordInfo.getRecordList());
RequestMessage msg = new RequestMessage();
msg.setKey(msgKey);
msg.setData(recordInfo);
deferredResultHolder.invokeAllResult(msg);
recordEndEventListener.delEndEventHandler(recordInfo.getDeviceId(),recordInfo.getChannelId());
data.remove(key);
}
}
}
public boolean isComplete(String deviceId, String sn) {
RecordInfo recordInfo = data.get(deviceId + sn);
return recordInfo != null && recordInfo.getRecordList().size() == recordInfo.getSumNum();
}
public RecordInfo getRecordInfo(String deviceId, String sn) {
return data.get(deviceId + sn);
}
public void remove(String deviceId, String sn) {
data.remove(deviceId + sn);
}
}
|
String key = deviceId + sn;
RecordInfo recordInfo = data.get(key);
if (recordInfo == null) {
recordInfo = new RecordInfo();
recordInfo.setDeviceId(deviceId);
recordInfo.setChannelId(channelId);
recordInfo.setSn(sn.trim());
recordInfo.setSumNum(sumNum);
recordInfo.setRecordList(Collections.synchronizedList(new ArrayList<>()));
recordInfo.setLastTime(Instant.now());
recordInfo.getRecordList().addAll(recordItems);
data.put(key, recordInfo);
}else {
// 同一个设备的通道同步请求只考虑一个,其他的直接忽略
if (!Objects.equals(sn.trim(), recordInfo.getSn())) {
return 0;
}
recordInfo.getRecordList().addAll(recordItems);
recordInfo.setLastTime(Instant.now());
}
return recordInfo.getRecordList().size();
| 561
| 251
| 812
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/SSRCFactory.java
|
SSRCFactory
|
initMediaServerSSRC
|
class SSRCFactory {
/**
* 播流最大并发个数
*/
private static final Integer MAX_STREAM_COUNT = 10000;
/**
* 播流最大并发个数
*/
private static final String SSRC_INFO_KEY = "VMP_SSRC_INFO_";
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private SipConfig sipConfig;
@Autowired
private UserSetting userSetting;
public void initMediaServerSSRC(String mediaServerId, Set<String> usedSet) {<FILL_FUNCTION_BODY>}
/**
* 获取视频预览的SSRC值,第一位固定为0
*
* @return ssrc
*/
public String getPlaySsrc(String mediaServerId) {
return "0" + getSN(mediaServerId);
}
/**
* 获取录像回放的SSRC值,第一位固定为1
*/
public String getPlayBackSsrc(String mediaServerId) {
return "1" + getSN(mediaServerId);
}
/**
* 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
*
* @param ssrc 需要重置的ssrc
*/
public void releaseSsrc(String mediaServerId, String ssrc) {
if (ssrc == null) {
return;
}
String sn = ssrc.substring(1);
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
redisTemplate.opsForSet().add(redisKey, sn);
}
/**
* 获取后四位数SN,随机数
*/
private String getSN(String mediaServerId) {
String sn = null;
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
Long size = redisTemplate.opsForSet().size(redisKey);
if (size == null || size == 0) {
throw new RuntimeException("ssrc已经用完");
} else {
// 在集合中移除并返回一个随机成员。
sn = (String) redisTemplate.opsForSet().pop(redisKey);
redisTemplate.opsForSet().remove(redisKey, sn);
}
return sn;
}
/**
* 重置一个流媒体服务的所有ssrc
*
* @param mediaServerId 流媒体服务ID
*/
public void reset(String mediaServerId) {
this.initMediaServerSSRC(mediaServerId, null);
}
/**
* 是否已经存在了某个MediaServer的SSRC信息
*
* @param mediaServerId 流媒体服务ID
*/
public boolean hasMediaServerSSRC(String mediaServerId) {
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
}
}
|
String sipDomain = sipConfig.getDomain();
String ssrcPrefix = sipDomain.length() >= 8 ? sipDomain.substring(3, 8) : sipDomain;
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
List<String> ssrcList = new ArrayList<>();
for (int i = 1; i < MAX_STREAM_COUNT; i++) {
String ssrc = String.format("%s%04d", ssrcPrefix, i);
if (null == usedSet || !usedSet.contains(ssrc)) {
ssrcList.add(ssrc);
}
}
if (redisTemplate.opsForSet().size(redisKey) != null) {
redisTemplate.delete(redisKey);
}
redisTemplate.opsForSet().add(redisKey, ssrcList.toArray(new String[0]));
| 808
| 243
| 1,051
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/VideoStreamSessionManager.java
|
VideoStreamSessionManager
|
getSSRC
|
class VideoStreamSessionManager {
@Autowired
private UserSetting userSetting;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
/**
* 添加一个点播/回放的事务信息
* 后续可以通过流Id/callID
* @param deviceId 设备ID
* @param channelId 通道ID
* @param callId 一次请求的CallID
* @param stream 流名称
* @param mediaServerId 所使用的流媒体ID
* @param response 回复
*/
public void put(String deviceId, String channelId, String callId, String stream, String ssrc, String mediaServerId, SIPResponse response, InviteSessionType type){
SsrcTransaction ssrcTransaction = new SsrcTransaction();
ssrcTransaction.setDeviceId(deviceId);
ssrcTransaction.setChannelId(channelId);
ssrcTransaction.setStream(stream);
ssrcTransaction.setSipTransactionInfo(new SipTransactionInfo(response));
ssrcTransaction.setCallId(callId);
ssrcTransaction.setSsrc(ssrc);
ssrcTransaction.setMediaServerId(mediaServerId);
ssrcTransaction.setType(type);
redisTemplate.opsForValue().set(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId()
+ ":" + deviceId + ":" + channelId + ":" + callId + ":" + stream, ssrcTransaction);
}
public SsrcTransaction getSsrcTransaction(String deviceId, String channelId, String callId, String stream){
if (ObjectUtils.isEmpty(deviceId)) {
deviceId ="*";
}
if (ObjectUtils.isEmpty(channelId)) {
channelId ="*";
}
if (ObjectUtils.isEmpty(callId)) {
callId ="*";
}
if (ObjectUtils.isEmpty(stream)) {
stream ="*";
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":" + deviceId + ":" + channelId + ":" + callId+ ":" + stream;
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.size() == 0) {
return null;
}
return (SsrcTransaction)redisTemplate.opsForValue().get(scanResult.get(0));
}
public SsrcTransaction getSsrcTransactionByCallId(String callId){
if (ObjectUtils.isEmpty(callId)) {
return null;
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":*:*:" + callId+ ":*";
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (!scanResult.isEmpty()) {
return (SsrcTransaction)redisTemplate.opsForValue().get(scanResult.get(0));
}else {
key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":*:*:play:*";
scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.isEmpty()) {
return null;
}
for (Object keyObj : scanResult) {
SsrcTransaction ssrcTransaction = (SsrcTransaction)redisTemplate.opsForValue().get(keyObj);
if (ssrcTransaction.getSipTransactionInfo() != null &&
ssrcTransaction.getSipTransactionInfo().getCallId().equals(callId)) {
return ssrcTransaction;
}
}
return null;
}
}
public List<SsrcTransaction> getSsrcTransactionForAll(String deviceId, String channelId, String callId, String stream){
if (ObjectUtils.isEmpty(deviceId)) {
deviceId ="*";
}
if (ObjectUtils.isEmpty(channelId)) {
channelId ="*";
}
if (ObjectUtils.isEmpty(callId)) {
callId ="*";
}
if (ObjectUtils.isEmpty(stream)) {
stream ="*";
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":" + deviceId + ":" + channelId + ":" + callId+ ":" + stream;
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.size() == 0) {
return null;
}
List<SsrcTransaction> result = new ArrayList<>();
for (Object keyObj : scanResult) {
result.add((SsrcTransaction)redisTemplate.opsForValue().get(keyObj));
}
return result;
}
public String getMediaServerId(String deviceId, String channelId, String stream){
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, null, stream);
if (ssrcTransaction == null) {
return null;
}
return ssrcTransaction.getMediaServerId();
}
public String getSSRC(String deviceId, String channelId, String stream){<FILL_FUNCTION_BODY>}
public void remove(String deviceId, String channelId, String stream) {
List<SsrcTransaction> ssrcTransactionList = getSsrcTransactionForAll(deviceId, channelId, null, stream);
if (ssrcTransactionList == null || ssrcTransactionList.isEmpty()) {
return;
}
for (SsrcTransaction ssrcTransaction : ssrcTransactionList) {
redisTemplate.delete(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":"
+ deviceId + ":" + channelId + ":" + ssrcTransaction.getCallId() + ":" + ssrcTransaction.getStream());
}
}
public void removeByCallId(String deviceId, String channelId, String callId) {
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, callId, null);
if (ssrcTransaction == null ) {
return;
}
redisTemplate.delete(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":"
+ deviceId + ":" + channelId + ":" + ssrcTransaction.getCallId() + ":" + ssrcTransaction.getStream());
}
public List<SsrcTransaction> getAllSsrc() {
List<Object> ssrcTransactionKeys = RedisUtil.scan(redisTemplate, String.format("%s_*_*_*_*", VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX+ userSetting.getServerId()));
List<SsrcTransaction> result= new ArrayList<>();
for (Object ssrcTransactionKey : ssrcTransactionKeys) {
String key = (String) ssrcTransactionKey;
SsrcTransaction ssrcTransaction = JsonUtil.redisJsonToObject(redisTemplate, key, SsrcTransaction.class);
result.add(ssrcTransaction);
}
return result;
}
}
|
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, null, stream);
if (ssrcTransaction == null) {
return null;
}
return ssrcTransaction.getSsrc();
| 1,844
| 58
| 1,902
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/SipRunner.java
|
SipRunner
|
run
|
class SipRunner implements CommandLineRunner {
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private SSRCFactory ssrcFactory;
@Autowired
private UserSetting userSetting;
@Autowired
private IDeviceService deviceService;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private IPlatformService platformService;
@Autowired
private ISIPCommanderForPlatform commanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
List<Device> deviceList = deviceService.getAllOnlineDevice();
for (Device device : deviceList) {
if (deviceService.expire(device)){
deviceService.offline(device.getDeviceId(), "注册已过期");
}else {
deviceService.online(device, null);
}
}
// 重置cseq计数
redisCatchStorage.resetAllCSEQ();
// 清理redis
// 清理数据库不存在但是redis中存在的数据
List<Device> devicesInDb = deviceService.getAll();
if (devicesInDb.size() == 0) {
redisCatchStorage.removeAllDevice();
}else {
List<Device> devicesInRedis = redisCatchStorage.getAllDevices();
if (devicesInRedis.size() > 0) {
Map<String, Device> deviceMapInDb = new HashMap<>();
devicesInDb.parallelStream().forEach(device -> {
deviceMapInDb.put(device.getDeviceId(), device);
});
devicesInRedis.parallelStream().forEach(device -> {
if (deviceMapInDb.get(device.getDeviceId()) == null) {
redisCatchStorage.removeDevice(device.getDeviceId());
}
});
}
}
// 查找国标推流
List<SendRtpItem> sendRtpItems = redisCatchStorage.queryAllSendRTPServer();
if (sendRtpItems.size() > 0) {
for (SendRtpItem sendRtpItem : sendRtpItems) {
MediaServer mediaServerItem = mediaServerService.getOne(sendRtpItem.getMediaServerId());
redisCatchStorage.deleteSendRTPServer(sendRtpItem.getPlatformId(),sendRtpItem.getChannelId(), sendRtpItem.getCallId(),sendRtpItem.getStream());
if (mediaServerItem != null) {
ssrcFactory.releaseSsrc(sendRtpItem.getMediaServerId(), sendRtpItem.getSsrc());
boolean stopResult = mediaServerService.stopSendRtp(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getSsrc());
if (stopResult) {
ParentPlatform platform = platformService.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
if (platform != null) {
try {
commanderForPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
}
}
}
}
}
}
| 210
| 703
| 913
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/impl/CatalogSubscribeTask.java
|
CatalogSubscribeTask
|
run
|
class CatalogSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(CatalogSubscribeTask.class);
private Device device;
private final ISIPCommander sipCommander;
private SIPRequest request;
private DynamicTask dynamicTask;
private String taskKey = "catalog-subscribe-timeout";
public CatalogSubscribeTask(Device device, ISIPCommander sipCommander, DynamicTask dynamicTask) {
this.device = device;
this.sipCommander = sipCommander;
this.dynamicTask = dynamicTask;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public void stop(CommonCallback<Boolean> callback) {
/**
* dialog 的各个状态
* EARLY-> Early state状态-初始请求发送以后,收到了一个临时响应消息
* CONFIRMED-> Confirmed Dialog状态-已确认
* COMPLETED-> Completed Dialog状态-已完成
* TERMINATED-> Terminated Dialog状态-终止
*/
logger.info("取消目录订阅时dialog状态为{}", DialogState.CONFIRMED);
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
device.setSubscribeCycleForCatalog(0);
try {
sipCommander.catalogSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) {
// 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId());
}else {
// 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId());
}
if (callback != null) {
callback.run(event.getResponse().getRawContent() != null);
}
},eventResult -> {
// 失败
logger.warn("[取消目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消目录订阅: {}", e.getMessage());
}
}
}
|
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
SIPRequest sipRequest = null;
try {
sipRequest = sipCommander.catalogSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
// 成功
logger.info("[目录订阅]成功: {}", device.getDeviceId());
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try {
this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) {
logger.info("[目录订阅]成功: 但为request设置ToTag失败");
this.request = null;
}
},eventResult -> {
this.request = null;
// 失败
logger.warn("[目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, CatalogSubscribeTask.this, 2000);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 目录订阅: {}", e.getMessage());
}
if (sipRequest != null) {
this.request = sipRequest;
}
| 622
| 365
| 987
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/impl/MobilePositionSubscribeTask.java
|
MobilePositionSubscribeTask
|
run
|
class MobilePositionSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(MobilePositionSubscribeTask.class);
private Device device;
private ISIPCommander sipCommander;
private SIPRequest request;
private DynamicTask dynamicTask;
private String taskKey = "mobile-position-subscribe-timeout";
public MobilePositionSubscribeTask(Device device, ISIPCommander sipCommander, DynamicTask dynamicTask) {
this.device = device;
this.sipCommander = sipCommander;
this.dynamicTask = dynamicTask;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public void stop(CommonCallback<Boolean> callback) {
/**
* dialog 的各个状态
* EARLY-> Early state状态-初始请求发送以后,收到了一个临时响应消息
* CONFIRMED-> Confirmed Dialog状态-已确认
* COMPLETED-> Completed Dialog状态-已完成
* TERMINATED-> Terminated Dialog状态-终止
*/
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
device.setSubscribeCycleForMobilePosition(0);
try {
sipCommander.mobilePositionSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) {
// 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
}else {
// 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
}
if (callback != null) {
callback.run(event.getResponse().getRawContent() != null);
}
},eventResult -> {
// 失败
logger.warn("[取消移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消移动位置订阅: {}", e.getMessage());
}
}
}
|
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
SIPRequest sipRequest = null;
try {
sipRequest = sipCommander.mobilePositionSubscribe(device, request, eventResult -> {
// 成功
logger.info("[移动位置订阅]成功: {}", device.getDeviceId());
ResponseEvent event = (ResponseEvent) eventResult.event;
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try {
this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) {
logger.info("[移动位置订阅]成功: 为request设置ToTag失败");
this.request = null;
}
},eventResult -> {
this.request = null;
// 失败
logger.warn("[移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, MobilePositionSubscribeTask.this, 2000);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 移动位置订阅: {}", e.getMessage());
}
if (sipRequest != null) {
this.request = sipRequest;
}
| 593
| 364
| 957
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/SIPProcessorObserver.java
|
SIPProcessorObserver
|
processResponse
|
class SIPProcessorObserver implements ISIPProcessorObserver {
private final static Logger logger = LoggerFactory.getLogger(SIPProcessorObserver.class);
private static Map<String, ISIPRequestProcessor> requestProcessorMap = new ConcurrentHashMap<>();
private static Map<String, ISIPResponseProcessor> responseProcessorMap = new ConcurrentHashMap<>();
private static ITimeoutProcessor timeoutProcessor;
@Autowired
private SipSubscribe sipSubscribe;
@Autowired
private EventPublisher eventPublisher;
/**
* 添加 request订阅
* @param method 方法名
* @param processor 处理程序
*/
public void addRequestProcessor(String method, ISIPRequestProcessor processor) {
requestProcessorMap.put(method, processor);
}
/**
* 添加 response订阅
* @param method 方法名
* @param processor 处理程序
*/
public void addResponseProcessor(String method, ISIPResponseProcessor processor) {
responseProcessorMap.put(method, processor);
}
/**
* 添加 超时事件订阅
* @param processor 处理程序
*/
public void addTimeoutProcessor(ITimeoutProcessor processor) {
timeoutProcessor = processor;
}
/**
* 分发RequestEvent事件
* @param requestEvent RequestEvent事件
*/
@Override
@Async("taskExecutor")
public void processRequest(RequestEvent requestEvent) {
String method = requestEvent.getRequest().getMethod();
ISIPRequestProcessor sipRequestProcessor = requestProcessorMap.get(method);
if (sipRequestProcessor == null) {
logger.warn("不支持方法{}的request", method);
// TODO 回复错误玛
return;
}
requestProcessorMap.get(method).process(requestEvent);
}
/**
* 分发ResponseEvent事件
* @param responseEvent responseEvent事件
*/
@Override
@Async("taskExecutor")
public void processResponse(ResponseEvent responseEvent) {<FILL_FUNCTION_BODY>}
/**
* 向超时订阅发送消息
* @param timeoutEvent timeoutEvent事件
*/
@Override
public void processTimeout(TimeoutEvent timeoutEvent) {
logger.info("[消息发送超时]");
ClientTransaction clientTransaction = timeoutEvent.getClientTransaction();
if (clientTransaction != null) {
logger.info("[发送错误订阅] clientTransaction != null");
Request request = clientTransaction.getRequest();
if (request != null) {
logger.info("[发送错误订阅] request != null");
CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
logger.info("[发送错误订阅]");
SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(timeoutEvent);
if (subscribe != null){
subscribe.response(eventResult);
}
sipSubscribe.removeOkSubscribe(callIdHeader.getCallId());
sipSubscribe.removeErrorSubscribe(callIdHeader.getCallId());
}
}
}
eventPublisher.requestTimeOut(timeoutEvent);
}
@Override
public void processIOException(IOExceptionEvent exceptionEvent) {
System.out.println("processIOException");
}
@Override
public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
// if (transactionTerminatedEvent.isServerTransaction()) {
// ServerTransaction serverTransaction = transactionTerminatedEvent.getServerTransaction();
// serverTransaction.get
// }
// Transaction transaction = null;
// System.out.println("processTransactionTerminated");
// if (transactionTerminatedEvent.isServerTransaction()) {
// transaction = transactionTerminatedEvent.getServerTransaction();
// }else {
// transaction = transactionTerminatedEvent.getClientTransaction();
// }
//
// System.out.println(transaction.getBranchId());
// System.out.println(transaction.getState());
// System.out.println(transaction.getRequest().getMethod());
// CallIdHeader header = (CallIdHeader)transaction.getRequest().getHeader(CallIdHeader.NAME);
// SipSubscribe.EventResult<TransactionTerminatedEvent> terminatedEventEventResult = new SipSubscribe.EventResult<>(transactionTerminatedEvent);
// sipSubscribe.getErrorSubscribe(header.getCallId()).response(terminatedEventEventResult);
}
@Override
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
CallIdHeader callId = dialogTerminatedEvent.getDialog().getCallId();
}
}
|
Response response = responseEvent.getResponse();
int status = response.getStatusCode();
// Success
if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
CSeqHeader cseqHeader = (CSeqHeader) responseEvent.getResponse().getHeader(CSeqHeader.NAME);
String method = cseqHeader.getMethod();
ISIPResponseProcessor sipRequestProcessor = responseProcessorMap.get(method);
if (sipRequestProcessor != null) {
sipRequestProcessor.process(responseEvent);
}
if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && sipSubscribe.getOkSubscribesSize() > 0 ) {
CallIdHeader callIdHeader = (CallIdHeader)responseEvent.getResponse().getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
SipSubscribe.Event subscribe = sipSubscribe.getOkSubscribe(callIdHeader.getCallId());
if (subscribe != null) {
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(responseEvent);
sipSubscribe.removeOkSubscribe(callIdHeader.getCallId());
subscribe.response(eventResult);
}
}
}
} else if ((status >= Response.TRYING) && (status < Response.OK)) {
// 增加其它无需回复的响应,如101、180等
} else {
logger.warn("接收到失败的response响应!status:" + status + ",message:" + response.getReasonPhrase());
if (responseEvent.getResponse() != null && sipSubscribe.getErrorSubscribesSize() > 0 ) {
CallIdHeader callIdHeader = (CallIdHeader)responseEvent.getResponse().getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
if (subscribe != null) {
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(responseEvent);
subscribe.response(eventResult);
sipSubscribe.removeErrorSubscribe(callIdHeader.getCallId());
}
}
}
if (responseEvent.getDialog() != null) {
responseEvent.getDialog().delete();
}
}
| 1,230
| 629
| 1,859
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/SIPSender.java
|
SIPSender
|
transmitRequest
|
class SIPSender {
private final Logger logger = LoggerFactory.getLogger(SIPSender.class);
@Autowired
private SipLayer sipLayer;
@Autowired
private GitUtil gitUtil;
@Autowired
private SipSubscribe sipSubscribe;
public void transmitRequest(String ip, Message message) throws SipException, ParseException {
transmitRequest(ip, message, null, null);
}
public void transmitRequest(String ip, Message message, SipSubscribe.Event errorEvent) throws SipException, ParseException {
transmitRequest(ip, message, errorEvent, null);
}
public void transmitRequest(String ip, Message message, SipSubscribe.Event errorEvent, SipSubscribe.Event okEvent) throws SipException {<FILL_FUNCTION_BODY>}
public CallIdHeader getNewCallIdHeader(String ip, String transport){
if (ObjectUtils.isEmpty(transport)) {
return sipLayer.getUdpSipProvider().getNewCallId();
}
SipProviderImpl sipProvider;
if (ObjectUtils.isEmpty(ip)) {
sipProvider = transport.equalsIgnoreCase("TCP") ? sipLayer.getTcpSipProvider()
: sipLayer.getUdpSipProvider();
}else {
sipProvider = transport.equalsIgnoreCase("TCP") ? sipLayer.getTcpSipProvider(ip)
: sipLayer.getUdpSipProvider(ip);
}
if (sipProvider == null) {
sipProvider = sipLayer.getUdpSipProvider();
}
if (sipProvider != null) {
return sipProvider.getNewCallId();
}else {
logger.warn("[新建CallIdHeader失败], ip={}, transport={}", ip, transport);
return null;
}
}
}
|
ViaHeader viaHeader = (ViaHeader)message.getHeader(ViaHeader.NAME);
String transport = "UDP";
if (viaHeader == null) {
logger.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据");
}else {
transport = viaHeader.getTransport();
}
if (message.getHeader(UserAgentHeader.NAME) == null) {
try {
message.addHeader(SipUtils.createUserAgentHeader(gitUtil));
} catch (ParseException e) {
logger.error("添加UserAgentHeader失败", e);
}
}
CallIdHeader callIdHeader = (CallIdHeader) message.getHeader(CallIdHeader.NAME);
// 添加错误订阅
if (errorEvent != null) {
sipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (eventResult -> {
sipSubscribe.removeErrorSubscribe(eventResult.callId);
sipSubscribe.removeOkSubscribe(eventResult.callId);
errorEvent.response(eventResult);
}));
}
// 添加订阅
if (okEvent != null) {
sipSubscribe.addOkSubscribe(callIdHeader.getCallId(), eventResult -> {
sipSubscribe.removeOkSubscribe(eventResult.callId);
sipSubscribe.removeErrorSubscribe(eventResult.callId);
okEvent.response(eventResult);
});
}
if ("TCP".equals(transport)) {
SipProviderImpl tcpSipProvider = sipLayer.getTcpSipProvider(ip);
if (tcpSipProvider == null) {
logger.error("[发送信息失败] 未找到tcp://{}的监听信息", ip);
return;
}
if (message instanceof Request) {
tcpSipProvider.sendRequest((Request)message);
}else if (message instanceof Response) {
tcpSipProvider.sendResponse((Response)message);
}
} else if ("UDP".equals(transport)) {
SipProviderImpl sipProvider = sipLayer.getUdpSipProvider(ip);
if (sipProvider == null) {
logger.error("[发送信息失败] 未找到udp://{}的监听信息", ip);
return;
}
if (message instanceof Request) {
sipProvider.sendRequest((Request)message);
}else if (message instanceof Response) {
sipProvider.sendResponse((Response)message);
}
}
| 487
| 652
| 1,139
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/callback/DeferredResultHolder.java
|
DeferredResultHolder
|
put
|
class DeferredResultHolder {
public static final String CALLBACK_CMD_DEVICESTATUS = "CALLBACK_DEVICESTATUS";
public static final String CALLBACK_CMD_DEVICEINFO = "CALLBACK_DEVICEINFO";
public static final String CALLBACK_CMD_DEVICECONTROL = "CALLBACK_DEVICECONTROL";
public static final String CALLBACK_CMD_DEVICECONFIG = "CALLBACK_DEVICECONFIG";
public static final String CALLBACK_CMD_CONFIGDOWNLOAD = "CALLBACK_CONFIGDOWNLOAD";
public static final String CALLBACK_CMD_CATALOG = "CALLBACK_CATALOG";
public static final String CALLBACK_CMD_RECORDINFO = "CALLBACK_RECORDINFO";
public static final String CALLBACK_CMD_PLAY = "CALLBACK_PLAY";
public static final String CALLBACK_CMD_PLAYBACK = "CALLBACK_PLAYBACK";
public static final String CALLBACK_CMD_DOWNLOAD = "CALLBACK_DOWNLOAD";
public static final String CALLBACK_CMD_PROXY = "CALLBACK_PROXY";
public static final String CALLBACK_CMD_STOP = "CALLBACK_STOP";
public static final String UPLOAD_FILE_CHANNEL = "UPLOAD_FILE_CHANNEL";
public static final String CALLBACK_CMD_MOBILE_POSITION = "CALLBACK_CMD_MOBILE_POSITION";
public static final String CALLBACK_CMD_PRESETQUERY = "CALLBACK_PRESETQUERY";
public static final String CALLBACK_CMD_ALARM = "CALLBACK_ALARM";
public static final String CALLBACK_CMD_BROADCAST = "CALLBACK_BROADCAST";
public static final String CALLBACK_CMD_SNAP= "CALLBACK_SNAP";
private Map<String, Map<String, DeferredResultEx>> map = new ConcurrentHashMap<>();
public void put(String key, String id, DeferredResultEx result) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
deferredResultMap = new ConcurrentHashMap<>();
map.put(key, deferredResultMap);
}
deferredResultMap.put(id, result);
}
public void put(String key, String id, DeferredResult result) {<FILL_FUNCTION_BODY>}
public DeferredResultEx get(String key, String id) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null || ObjectUtils.isEmpty(id)) {
return null;
}
return deferredResultMap.get(id);
}
public Collection<DeferredResultEx> getAllByKey(String key) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
return null;
}
return deferredResultMap.values();
}
public boolean exist(String key, String id){
if (key == null) {
return false;
}
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (id == null) {
return deferredResultMap != null;
}else {
return deferredResultMap != null && deferredResultMap.get(id) != null;
}
}
/**
* 释放单个请求
* @param msg
*/
public void invokeResult(RequestMessage msg) {
Map<String, DeferredResultEx> deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
DeferredResultEx result = deferredResultMap.get(msg.getId());
if (result == null) {
return;
}
result.getDeferredResult().setResult(msg.getData());
deferredResultMap.remove(msg.getId());
if (deferredResultMap.size() == 0) {
map.remove(msg.getKey());
}
}
/**
* 释放所有的请求
* @param msg
*/
public void invokeAllResult(RequestMessage msg) {
Map<String, DeferredResultEx> deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
synchronized (this) {
deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
Set<String> ids = deferredResultMap.keySet();
for (String id : ids) {
DeferredResultEx result = deferredResultMap.get(id);
if (result == null) {
return;
}
if (result.getFilter() != null) {
Object handler = result.getFilter().handler(msg.getData());
result.getDeferredResult().setResult(handler);
}else {
result.getDeferredResult().setResult(msg.getData());
}
}
map.remove(msg.getKey());
}
}
}
|
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
deferredResultMap = new ConcurrentHashMap<>();
map.put(key, deferredResultMap);
}
deferredResultMap.put(id, new DeferredResultEx(result));
| 1,359
| 90
| 1,449
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/AckRequestProcessor.java
|
AckRequestProcessor
|
process
|
class AckRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final Logger logger = LoggerFactory.getLogger(AckRequestProcessor.class);
private final String method = "ACK";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private UserSetting userSetting;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IDeviceService deviceService;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private DynamicTask dynamicTask;
@Autowired
private RedisGbPlayMsgListener redisGbPlayMsgListener;
@Autowired
private IPlayService playService;
/**
* 处理 ACK请求
*/
@Override
public void process(RequestEvent evt) {<FILL_FUNCTION_BODY>}
}
|
CallIdHeader callIdHeader = (CallIdHeader)evt.getRequest().getHeader(CallIdHeader.NAME);
dynamicTask.stop(callIdHeader.getCallId());
String fromUserId = ((SipURI) ((HeaderAddress) evt.getRequest().getHeader(FromHeader.NAME)).getAddress().getURI()).getUser();
String toUserId = ((SipURI) ((HeaderAddress) evt.getRequest().getHeader(ToHeader.NAME)).getAddress().getURI()).getUser();
logger.info("[收到ACK]: 来自->{}", fromUserId);
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, null, null, callIdHeader.getCallId());
if (sendRtpItem == null) {
logger.warn("[收到ACK]:未找到来自{},目标为({})的推流信息",fromUserId, toUserId);
return;
}
// tcp主动时,此时是级联下级平台,在回复200ok时,本地已经请求zlm开启监听,跳过下面步骤
if (sendRtpItem.isTcpActive()) {
logger.info("收到ACK,rtp/{} TCP主动方式后续处理", sendRtpItem.getStream());
return;
}
MediaServer mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
logger.info("收到ACK,rtp/{}开始向上级推流, 目标={}:{},SSRC={}, 协议:{}",
sendRtpItem.getStream(),
sendRtpItem.getIp(),
sendRtpItem.getPort(),
sendRtpItem.getSsrc(),
sendRtpItem.isTcp()?(sendRtpItem.isTcpActive()?"TCP主动":"TCP被动"):"UDP"
);
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(fromUserId);
if (parentPlatform != null) {
if (!userSetting.getServerId().equals(sendRtpItem.getServerId())) {
RequestPushStreamMsg requestPushStreamMsg = RequestPushStreamMsg.getInstance(sendRtpItem);
redisGbPlayMsgListener.sendMsgForStartSendRtpStream(sendRtpItem.getServerId(), requestPushStreamMsg, () -> {
playService.startSendRtpStreamFailHand(sendRtpItem, parentPlatform, callIdHeader);
});
} else {
try {
if (sendRtpItem.isTcpActive()) {
mediaServerService.startSendRtpPassive(mediaInfo, parentPlatform, sendRtpItem, null);
} else {
mediaServerService.startSendRtp(mediaInfo, parentPlatform, sendRtpItem);
}
}catch (ControllerException e) {
logger.error("RTP推流失败: {}", e.getMessage());
playService.startSendRtpStreamFailHand(sendRtpItem, parentPlatform, callIdHeader);
}
}
}else {
Device device = deviceService.getDevice(fromUserId);
if (device == null) {
logger.warn("[收到ACK]:来自{},目标为({})的推流信息为找到流体服务[{}]信息",fromUserId, toUserId, sendRtpItem.getMediaServerId());
return;
}
// 设置为收到ACK后发送语音的设备已经在发送200OK开始发流了
if (!device.isBroadcastPushAfterAck()) {
return;
}
if (mediaInfo == null) {
logger.warn("[收到ACK]:来自{},目标为({})的推流信息为找到流体服务[{}]信息",fromUserId, toUserId, sendRtpItem.getMediaServerId());
return;
}
try {
if (sendRtpItem.isTcpActive()) {
mediaServerService.startSendRtpPassive(mediaInfo, null, sendRtpItem, null);
} else {
mediaServerService.startSendRtp(mediaInfo, null, sendRtpItem);
}
}catch (ControllerException e) {
logger.error("RTP推流失败: {}", e.getMessage());
playService.startSendRtpStreamFailHand(sendRtpItem, null, callIdHeader);
}
}
| 290
| 1,128
| 1,418
|
<methods>public non-sealed void <init>() ,public HeaderFactory getHeaderFactory() ,public MessageFactory getMessageFactory() ,public Element getRootElement(RequestEvent) throws DocumentException,public Element getRootElement(RequestEvent, java.lang.String) throws DocumentException,public SIPResponse responseAck(SIPRequest, int) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String, com.genersoft.iot.vmp.gb28181.transmit.event.request.SIPRequestProcessorParent.ResponseAckExtraParam) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseSdpAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseXmlAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform, java.lang.Integer) throws SipException, InvalidArgumentException, java.text.ParseException<variables>private static final Logger logger,private com.genersoft.iot.vmp.gb28181.transmit.SIPSender sipSender
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/SubscribeRequestProcessor.java
|
SubscribeRequestProcessor
|
processNotifyCatalogList
|
class SubscribeRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final Logger logger = LoggerFactory.getLogger(SubscribeRequestProcessor.class);
private final String method = "SUBSCRIBE";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SubscribeHolder subscribeHolder;
@Autowired
private SIPSender sipSender;
@Autowired
private IPlatformService platformService;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
/**
* 处理SUBSCRIBE请求
*
* @param evt 事件
*/
@Override
public void process(RequestEvent evt) {
SIPRequest request = (SIPRequest) evt.getRequest();
try {
Element rootElement = getRootElement(evt);
if (rootElement == null) {
logger.error("处理SUBSCRIBE请求 未获取到消息体{}", evt.getRequest());
return;
}
String cmd = XmlUtil.getText(rootElement, "CmdType");
if (CmdType.MOBILE_POSITION.equals(cmd)) {
processNotifyMobilePosition(request, rootElement);
// } else if (CmdType.ALARM.equals(cmd)) {
// logger.info("接收到Alarm订阅");
// processNotifyAlarm(serverTransaction, rootElement);
} else if (CmdType.CATALOG.equals(cmd)) {
processNotifyCatalogList(request, rootElement);
} else {
logger.info("接收到消息:" + cmd);
Response response = getMessageFactory().createResponse(200, request);
if (response != null) {
ExpiresHeader expireHeader = getHeaderFactory().createExpiresHeader(30);
response.setExpires(expireHeader);
}
logger.info("response : " + response);
sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
}
} catch (ParseException | SipException | InvalidArgumentException | DocumentException e) {
logger.error("未处理的异常 ", e);
}
}
/**
* 处理移动位置订阅消息
*/
private void processNotifyMobilePosition(SIPRequest request, Element rootElement) throws SipException {
if (request == null) {
return;
}
String platformId = SipUtils.getUserIdFromFromHeader(request);
String deviceId = XmlUtil.getText(rootElement, "DeviceID");
ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
if (platform == null) {
return;
}
String sn = XmlUtil.getText(rootElement, "SN");
logger.info("[回复上级的移动位置订阅请求]: {}", platformId);
StringBuilder resultXml = new StringBuilder(200);
resultXml.append("<?xml version=\"1.0\" ?>\r\n")
.append("<Response>\r\n")
.append("<CmdType>MobilePosition</CmdType>\r\n")
.append("<SN>").append(sn).append("</SN>\r\n")
.append("<DeviceID>").append(deviceId).append("</DeviceID>\r\n")
.append("<Result>OK</Result>\r\n")
.append("</Response>\r\n");
if (subscribeInfo.getExpires() > 0) {
// GPS上报时间间隔
String interval = XmlUtil.getText(rootElement, "Interval");
if (interval == null) {
subscribeInfo.setGpsInterval(5);
}else {
subscribeInfo.setGpsInterval(Integer.parseInt(interval));
}
subscribeInfo.setSn(sn);
}
try {
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(platformId);
SIPResponse response = responseXmlAck(request, resultXml.toString(), parentPlatform, subscribeInfo.getExpires());
if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeMobilePositionSubscribe(platformId);
}else {
subscribeInfo.setResponse(response);
subscribeHolder.putMobilePositionSubscribe(platformId, subscribeInfo);
}
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("未处理的异常 ", e);
}
}
private void processNotifyAlarm(RequestEvent evt, Element rootElement) {
}
private void processNotifyCatalogList(SIPRequest request, Element rootElement) throws SipException {<FILL_FUNCTION_BODY>}
}
|
if (request == null) {
return;
}
String platformId = SipUtils.getUserIdFromFromHeader(request);
String deviceId = XmlUtil.getText(rootElement, "DeviceID");
ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
if (platform == null){
return;
}
SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
String sn = XmlUtil.getText(rootElement, "SN");
logger.info("[回复上级的目录订阅请求]: {}/{}", platformId, deviceId);
StringBuilder resultXml = new StringBuilder(200);
resultXml.append("<?xml version=\"1.0\" ?>\r\n")
.append("<Response>\r\n")
.append("<CmdType>Catalog</CmdType>\r\n")
.append("<SN>").append(sn).append("</SN>\r\n")
.append("<DeviceID>").append(deviceId).append("</DeviceID>\r\n")
.append("<Result>OK</Result>\r\n")
.append("</Response>\r\n");
if (subscribeInfo.getExpires() > 0) {
subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
}else if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeCatalogSubscribe(platformId);
}
try {
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(platformId);
SIPResponse response = responseXmlAck(request, resultXml.toString(), parentPlatform, subscribeInfo.getExpires());
if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeCatalogSubscribe(platformId);
}else {
subscribeInfo.setResponse(response);
subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
}
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("未处理的异常 ", e);
}
if (subscribeHolder.getCatalogSubscribe(platformId) == null && platform.isAutoPushChannel()) {
platformService.addSimulatedSubscribeInfo(platform);
}
| 1,286
| 593
| 1,879
|
<methods>public non-sealed void <init>() ,public HeaderFactory getHeaderFactory() ,public MessageFactory getMessageFactory() ,public Element getRootElement(RequestEvent) throws DocumentException,public Element getRootElement(RequestEvent, java.lang.String) throws DocumentException,public SIPResponse responseAck(SIPRequest, int) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String, com.genersoft.iot.vmp.gb28181.transmit.event.request.SIPRequestProcessorParent.ResponseAckExtraParam) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseSdpAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseXmlAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform, java.lang.Integer) throws SipException, InvalidArgumentException, java.text.ParseException<variables>private static final Logger logger,private com.genersoft.iot.vmp.gb28181.transmit.SIPSender sipSender
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/info/InfoRequestProcessor.java
|
InfoRequestProcessor
|
process
|
class InfoRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final static Logger logger = LoggerFactory.getLogger(InfoRequestProcessor.class);
private final String method = "INFO";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private IVideoManagerStorage storage;
@Autowired
private SipSubscribe sipSubscribe;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IInviteStreamService inviteStreamService;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommander cmder;
@Autowired
private VideoStreamSessionManager sessionManager;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
@Override
public void process(RequestEvent evt) {<FILL_FUNCTION_BODY>}
}
|
logger.debug("接收到消息:" + evt.getRequest());
SIPRequest request = (SIPRequest) evt.getRequest();
String deviceId = SipUtils.getUserIdFromFromHeader(request);
CallIdHeader callIdHeader = request.getCallIdHeader();
// 先从会话内查找
SsrcTransaction ssrcTransaction = sessionManager.getSsrcTransaction(null, null, callIdHeader.getCallId(), null);
// 兼容海康 媒体通知 消息from字段不是设备ID的问题
if (ssrcTransaction != null) {
deviceId = ssrcTransaction.getDeviceId();
}
// 查询设备是否存在
Device device = redisCatchStorage.getDevice(deviceId);
// 查询上级平台是否存在
ParentPlatform parentPlatform = storage.queryParentPlatByServerGBId(deviceId);
try {
if (device != null && parentPlatform != null) {
logger.warn("[重复]平台与设备编号重复:{}", deviceId);
String hostAddress = request.getRemoteAddress().getHostAddress();
int remotePort = request.getRemotePort();
if (device.getHostAddress().equals(hostAddress + ":" + remotePort)) {
parentPlatform = null;
}else {
device = null;
}
}
if (device == null && parentPlatform == null) {
// 不存在则回复404
responseAck(request, Response.NOT_FOUND, "device "+ deviceId +" not found");
logger.warn("[设备未找到 ]: {}", deviceId);
if (sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()) != null){
DeviceNotFoundEvent deviceNotFoundEvent = new DeviceNotFoundEvent(evt.getDialog());
deviceNotFoundEvent.setCallId(callIdHeader.getCallId());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(deviceNotFoundEvent);
sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()).response(eventResult);
};
}else {
ContentTypeHeader header = (ContentTypeHeader)evt.getRequest().getHeader(ContentTypeHeader.NAME);
String contentType = header.getContentType();
String contentSubType = header.getContentSubType();
if ("Application".equalsIgnoreCase(contentType) && "MANSRTSP".equalsIgnoreCase(contentSubType)) {
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, null, null, callIdHeader.getCallId());
String streamId = sendRtpItem.getStream();
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo) {
responseAck(request, Response.NOT_FOUND, "stream " + streamId + " not found");
return;
}
Device device1 = storager.queryVideoDevice(inviteInfo.getDeviceId());
if (inviteInfo.getStreamInfo() != null) {
cmder.playbackControlCmd(device1,inviteInfo.getStreamInfo(),new String(evt.getRequest().getRawContent()),eventResult -> {
// 失败的回复
try {
responseAck(request, eventResult.statusCode, eventResult.msg);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像控制: {}", e.getMessage());
}
}, eventResult -> {
// 成功的回复
try {
responseAck(request, eventResult.statusCode);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像控制: {}", e.getMessage());
}
});
}
}
}
} catch (SipException e) {
logger.warn("SIP 回复错误", e);
} catch (InvalidArgumentException e) {
logger.warn("参数无效", e);
} catch (ParseException e) {
logger.warn("SIP回复时解析异常", e);
}
| 279
| 1,074
| 1,353
|
<methods>public non-sealed void <init>() ,public HeaderFactory getHeaderFactory() ,public MessageFactory getMessageFactory() ,public Element getRootElement(RequestEvent) throws DocumentException,public Element getRootElement(RequestEvent, java.lang.String) throws DocumentException,public SIPResponse responseAck(SIPRequest, int) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseAck(SIPRequest, int, java.lang.String, com.genersoft.iot.vmp.gb28181.transmit.event.request.SIPRequestProcessorParent.ResponseAckExtraParam) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseSdpAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform) throws SipException, InvalidArgumentException, java.text.ParseException,public SIPResponse responseXmlAck(SIPRequest, java.lang.String, com.genersoft.iot.vmp.gb28181.bean.ParentPlatform, java.lang.Integer) throws SipException, InvalidArgumentException, java.text.ParseException<variables>private static final Logger logger,private com.genersoft.iot.vmp.gb28181.transmit.SIPSender sipSender
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.