index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/PodSequence.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.6: The values for the pod sequence field, for use in audio and
* video content streams with one or more ad pods.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.PodSequence}
*/
public enum PodSequence
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* Any pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_ANY = 0;</code>
*/
POD_SEQUENCE_ANY(0),
/**
* <pre>
* Last pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_LAST = -1;</code>
*/
POD_SEQUENCE_LAST(-1),
/**
* <pre>
* First pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_FIRST = 1;</code>
*/
POD_SEQUENCE_FIRST(1),
;
/**
* <pre>
* Any pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_ANY = 0;</code>
*/
public static final int POD_SEQUENCE_ANY_VALUE = 0;
/**
* <pre>
* Last pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_LAST = -1;</code>
*/
public static final int POD_SEQUENCE_LAST_VALUE = -1;
/**
* <pre>
* First pod in the content stream
* </pre>
*
* <code>POD_SEQUENCE_FIRST = 1;</code>
*/
public static final int POD_SEQUENCE_FIRST_VALUE = 1;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static PodSequence valueOf(int value) {
return forNumber(value);
}
public static PodSequence forNumber(int value) {
switch (value) {
case 0: return POD_SEQUENCE_ANY;
case -1: return POD_SEQUENCE_LAST;
case 1: return POD_SEQUENCE_FIRST;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<PodSequence>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
PodSequence> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<PodSequence>() {
@java.lang.Override
public PodSequence findValueByNumber(int number) {
return PodSequence.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return PodSequenceVerifier.INSTANCE;
}
private static final class PodSequenceVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new PodSequenceVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return PodSequence.forNumber(number) != null;
}
};
private final int value;
private PodSequence(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.PodSequence)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/ProductionQuality.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.0: The following table lists the options for content quality.
* These values are defined by the IAB -
* https://github.com/InteractiveAdvertisingBureau/AdCOM/blob/main/AdCOM%20v1.0%20FINAL.md#list--production-qualities-.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.ProductionQuality}
*/
public enum ProductionQuality
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>QUALITY_UNKNOWN = 0;</code>
*/
QUALITY_UNKNOWN(0),
/**
* <pre>
* Content that is usually created or produced by media and entertainment
* companies using professional-grade equipment, talent, and production
* crews that hold or maintain the rights for distribution and syndication.
* </pre>
*
* <code>PROFESSIONAL = 1;</code>
*/
PROFESSIONAL(1),
/**
* <pre>
* Consumer or user-generated content that has professional or industrial
* qualities (e.g. shot with professional-grade equipment, using
* professional talent, etc.).
* </pre>
*
* <code>PROSUMER = 2;</code>
*/
PROSUMER(2),
/**
* <pre>
* Publicly available video content that is created or produced by
* end users.
* </pre>
*
* <code>USER_GENERATED = 3;</code>
*/
USER_GENERATED(3),
;
/**
* <code>QUALITY_UNKNOWN = 0;</code>
*/
public static final int QUALITY_UNKNOWN_VALUE = 0;
/**
* <pre>
* Content that is usually created or produced by media and entertainment
* companies using professional-grade equipment, talent, and production
* crews that hold or maintain the rights for distribution and syndication.
* </pre>
*
* <code>PROFESSIONAL = 1;</code>
*/
public static final int PROFESSIONAL_VALUE = 1;
/**
* <pre>
* Consumer or user-generated content that has professional or industrial
* qualities (e.g. shot with professional-grade equipment, using
* professional talent, etc.).
* </pre>
*
* <code>PROSUMER = 2;</code>
*/
public static final int PROSUMER_VALUE = 2;
/**
* <pre>
* Publicly available video content that is created or produced by
* end users.
* </pre>
*
* <code>USER_GENERATED = 3;</code>
*/
public static final int USER_GENERATED_VALUE = 3;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ProductionQuality valueOf(int value) {
return forNumber(value);
}
public static ProductionQuality forNumber(int value) {
switch (value) {
case 0: return QUALITY_UNKNOWN;
case 1: return PROFESSIONAL;
case 2: return PROSUMER;
case 3: return USER_GENERATED;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ProductionQuality>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ProductionQuality> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ProductionQuality>() {
@java.lang.Override
public ProductionQuality findValueByNumber(int number) {
return ProductionQuality.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return ProductionQualityVerifier.INSTANCE;
}
private static final class ProductionQualityVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new ProductionQualityVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return ProductionQuality.forNumber(number) != null;
}
};
private final int value;
private ProductionQuality(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.ProductionQuality)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/Protocol.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.0: The following table lists the options for the various
* bid response protocols that could be supported by an exchange.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.Protocol}
*/
public enum Protocol
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>VAST_1_0 = 1;</code>
*/
VAST_1_0(1),
/**
* <code>VAST_2_0 = 2;</code>
*/
VAST_2_0(2),
/**
* <code>VAST_3_0 = 3;</code>
*/
VAST_3_0(3),
/**
* <code>VAST_1_0_WRAPPER = 4;</code>
*/
VAST_1_0_WRAPPER(4),
/**
* <code>VAST_2_0_WRAPPER = 5;</code>
*/
VAST_2_0_WRAPPER(5),
/**
* <code>VAST_3_0_WRAPPER = 6;</code>
*/
VAST_3_0_WRAPPER(6),
/**
* <code>VAST_4_0 = 7;</code>
*/
VAST_4_0(7),
/**
* <code>VAST_4_0_WRAPPER = 8;</code>
*/
VAST_4_0_WRAPPER(8),
/**
* <code>DAAST_1_0 = 9;</code>
*/
DAAST_1_0(9),
/**
* <code>DAAST_1_0_WRAPPER = 10;</code>
*/
DAAST_1_0_WRAPPER(10),
/**
* <code>VAST_4_1 = 11;</code>
*/
VAST_4_1(11),
/**
* <code>VAST_4_1_WRAPPER = 12;</code>
*/
VAST_4_1_WRAPPER(12),
/**
* <code>VAST_4_2 = 13;</code>
*/
VAST_4_2(13),
/**
* <code>VAST_4_2_WRAPPER = 14;</code>
*/
VAST_4_2_WRAPPER(14),
;
/**
* <code>VAST_1_0 = 1;</code>
*/
public static final int VAST_1_0_VALUE = 1;
/**
* <code>VAST_2_0 = 2;</code>
*/
public static final int VAST_2_0_VALUE = 2;
/**
* <code>VAST_3_0 = 3;</code>
*/
public static final int VAST_3_0_VALUE = 3;
/**
* <code>VAST_1_0_WRAPPER = 4;</code>
*/
public static final int VAST_1_0_WRAPPER_VALUE = 4;
/**
* <code>VAST_2_0_WRAPPER = 5;</code>
*/
public static final int VAST_2_0_WRAPPER_VALUE = 5;
/**
* <code>VAST_3_0_WRAPPER = 6;</code>
*/
public static final int VAST_3_0_WRAPPER_VALUE = 6;
/**
* <code>VAST_4_0 = 7;</code>
*/
public static final int VAST_4_0_VALUE = 7;
/**
* <code>VAST_4_0_WRAPPER = 8;</code>
*/
public static final int VAST_4_0_WRAPPER_VALUE = 8;
/**
* <code>DAAST_1_0 = 9;</code>
*/
public static final int DAAST_1_0_VALUE = 9;
/**
* <code>DAAST_1_0_WRAPPER = 10;</code>
*/
public static final int DAAST_1_0_WRAPPER_VALUE = 10;
/**
* <code>VAST_4_1 = 11;</code>
*/
public static final int VAST_4_1_VALUE = 11;
/**
* <code>VAST_4_1_WRAPPER = 12;</code>
*/
public static final int VAST_4_1_WRAPPER_VALUE = 12;
/**
* <code>VAST_4_2 = 13;</code>
*/
public static final int VAST_4_2_VALUE = 13;
/**
* <code>VAST_4_2_WRAPPER = 14;</code>
*/
public static final int VAST_4_2_WRAPPER_VALUE = 14;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static Protocol valueOf(int value) {
return forNumber(value);
}
public static Protocol forNumber(int value) {
switch (value) {
case 1: return VAST_1_0;
case 2: return VAST_2_0;
case 3: return VAST_3_0;
case 4: return VAST_1_0_WRAPPER;
case 5: return VAST_2_0_WRAPPER;
case 6: return VAST_3_0_WRAPPER;
case 7: return VAST_4_0;
case 8: return VAST_4_0_WRAPPER;
case 9: return DAAST_1_0;
case 10: return DAAST_1_0_WRAPPER;
case 11: return VAST_4_1;
case 12: return VAST_4_1_WRAPPER;
case 13: return VAST_4_2;
case 14: return VAST_4_2_WRAPPER;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Protocol>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
Protocol> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Protocol>() {
@java.lang.Override
public Protocol findValueByNumber(int number) {
return Protocol.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return ProtocolVerifier.INSTANCE;
}
private static final class ProtocolVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new ProtocolVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return Protocol.forNumber(number) != null;
}
};
private final int value;
private Protocol(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.Protocol)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/QAGMediaRating.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.1: The following table lists the media ratings used in
* describing content based on the QAG categorization.
* Refer to http://www.iab.net/ne_guidelines for more information.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.QAGMediaRating}
*/
public enum QAGMediaRating
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>ALL_AUDIENCES = 1;</code>
*/
ALL_AUDIENCES(1),
/**
* <code>EVERYONE_OVER_12 = 2;</code>
*/
EVERYONE_OVER_12(2),
/**
* <code>MATURE = 3;</code>
*/
MATURE(3),
;
/**
* <code>ALL_AUDIENCES = 1;</code>
*/
public static final int ALL_AUDIENCES_VALUE = 1;
/**
* <code>EVERYONE_OVER_12 = 2;</code>
*/
public static final int EVERYONE_OVER_12_VALUE = 2;
/**
* <code>MATURE = 3;</code>
*/
public static final int MATURE_VALUE = 3;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static QAGMediaRating valueOf(int value) {
return forNumber(value);
}
public static QAGMediaRating forNumber(int value) {
switch (value) {
case 1: return ALL_AUDIENCES;
case 2: return EVERYONE_OVER_12;
case 3: return MATURE;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<QAGMediaRating>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
QAGMediaRating> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<QAGMediaRating>() {
@java.lang.Override
public QAGMediaRating findValueByNumber(int number) {
return QAGMediaRating.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return QAGMediaRatingVerifier.INSTANCE;
}
private static final class QAGMediaRatingVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new QAGMediaRatingVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return QAGMediaRating.forNumber(number) != null;
}
};
private final int value;
private QAGMediaRating(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.QAGMediaRating)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/ServerSideAdInsertionType.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.6: Server-side ad insertion type.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.ServerSideAdInsertionType}
*/
public enum ServerSideAdInsertionType
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* Status unknown.
* </pre>
*
* <code>SERVER_SIDE_AD_INSERTION_TYPE_UNKNOWN = 0;</code>
*/
SERVER_SIDE_AD_INSERTION_TYPE_UNKNOWN(0),
/**
* <pre>
* All clientside (not server-side).
* </pre>
*
* <code>CLIENT_SIDE_ONLY = 1;</code>
*/
CLIENT_SIDE_ONLY(1),
/**
* <pre>
* Assets stitched server-side but tracking pixels fired client-side.
* </pre>
*
* <code>SERVER_SIDE_STITCHED_CLIENT_TRACKER = 2;</code>
*/
SERVER_SIDE_STITCHED_CLIENT_TRACKER(2),
/**
* <pre>
* All server-side.
* </pre>
*
* <code>SERVER_SIDE_ONLY = 3;</code>
*/
SERVER_SIDE_ONLY(3),
;
/**
* <pre>
* Status unknown.
* </pre>
*
* <code>SERVER_SIDE_AD_INSERTION_TYPE_UNKNOWN = 0;</code>
*/
public static final int SERVER_SIDE_AD_INSERTION_TYPE_UNKNOWN_VALUE = 0;
/**
* <pre>
* All clientside (not server-side).
* </pre>
*
* <code>CLIENT_SIDE_ONLY = 1;</code>
*/
public static final int CLIENT_SIDE_ONLY_VALUE = 1;
/**
* <pre>
* Assets stitched server-side but tracking pixels fired client-side.
* </pre>
*
* <code>SERVER_SIDE_STITCHED_CLIENT_TRACKER = 2;</code>
*/
public static final int SERVER_SIDE_STITCHED_CLIENT_TRACKER_VALUE = 2;
/**
* <pre>
* All server-side.
* </pre>
*
* <code>SERVER_SIDE_ONLY = 3;</code>
*/
public static final int SERVER_SIDE_ONLY_VALUE = 3;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ServerSideAdInsertionType valueOf(int value) {
return forNumber(value);
}
public static ServerSideAdInsertionType forNumber(int value) {
switch (value) {
case 0: return SERVER_SIDE_AD_INSERTION_TYPE_UNKNOWN;
case 1: return CLIENT_SIDE_ONLY;
case 2: return SERVER_SIDE_STITCHED_CLIENT_TRACKER;
case 3: return SERVER_SIDE_ONLY;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ServerSideAdInsertionType>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ServerSideAdInsertionType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ServerSideAdInsertionType>() {
@java.lang.Override
public ServerSideAdInsertionType findValueByNumber(int number) {
return ServerSideAdInsertionType.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return ServerSideAdInsertionTypeVerifier.INSTANCE;
}
private static final class ServerSideAdInsertionTypeVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new ServerSideAdInsertionTypeVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return ServerSideAdInsertionType.forNumber(number) != null;
}
};
private final int value;
private ServerSideAdInsertionType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.ServerSideAdInsertionType)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/SlotPositionInPod.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.6: Slot Position in Pod.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.SlotPositionInPod}
*/
public enum SlotPositionInPod
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* Any position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_ANY = 0;</code>
*/
SLOT_POSITION_POD_ANY(0),
/**
* <pre>
* Last position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_LAST = -1;</code>
*/
SLOT_POSITION_POD_LAST(-1),
/**
* <pre>
* First position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_FIRST = 1;</code>
*/
SLOT_POSITION_POD_FIRST(1),
/**
* <pre>
* First or last position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_FIRST_OR_LAST = 2;</code>
*/
SLOT_POSITION_POD_FIRST_OR_LAST(2),
;
/**
* <pre>
* Any position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_ANY = 0;</code>
*/
public static final int SLOT_POSITION_POD_ANY_VALUE = 0;
/**
* <pre>
* Last position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_LAST = -1;</code>
*/
public static final int SLOT_POSITION_POD_LAST_VALUE = -1;
/**
* <pre>
* First position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_FIRST = 1;</code>
*/
public static final int SLOT_POSITION_POD_FIRST_VALUE = 1;
/**
* <pre>
* First or last position in the pod.
* </pre>
*
* <code>SLOT_POSITION_POD_FIRST_OR_LAST = 2;</code>
*/
public static final int SLOT_POSITION_POD_FIRST_OR_LAST_VALUE = 2;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SlotPositionInPod valueOf(int value) {
return forNumber(value);
}
public static SlotPositionInPod forNumber(int value) {
switch (value) {
case 0: return SLOT_POSITION_POD_ANY;
case -1: return SLOT_POSITION_POD_LAST;
case 1: return SLOT_POSITION_POD_FIRST;
case 2: return SLOT_POSITION_POD_FIRST_OR_LAST;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<SlotPositionInPod>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
SlotPositionInPod> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<SlotPositionInPod>() {
@java.lang.Override
public SlotPositionInPod findValueByNumber(int number) {
return SlotPositionInPod.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return SlotPositionInPodVerifier.INSTANCE;
}
private static final class SlotPositionInPodVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new SlotPositionInPodVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return SlotPositionInPod.forNumber(number) != null;
}
};
private final int value;
private SlotPositionInPod(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.SlotPositionInPod)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/StartDelay.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.0: The following table lists the various options for the
* audio/video start delay. If the start delay value is greater than 0,
* then the position is mid-roll and the value indicates the start delay.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.StartDelay}
*/
public enum StartDelay
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>PRE_ROLL = 0;</code>
*/
PRE_ROLL(0),
/**
* <code>GENERIC_MID_ROLL = -1;</code>
*/
GENERIC_MID_ROLL(-1),
/**
* <code>GENERIC_POST_ROLL = -2;</code>
*/
GENERIC_POST_ROLL(-2),
;
/**
* <code>PRE_ROLL = 0;</code>
*/
public static final int PRE_ROLL_VALUE = 0;
/**
* <code>GENERIC_MID_ROLL = -1;</code>
*/
public static final int GENERIC_MID_ROLL_VALUE = -1;
/**
* <code>GENERIC_POST_ROLL = -2;</code>
*/
public static final int GENERIC_POST_ROLL_VALUE = -2;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static StartDelay valueOf(int value) {
return forNumber(value);
}
public static StartDelay forNumber(int value) {
switch (value) {
case 0: return PRE_ROLL;
case -1: return GENERIC_MID_ROLL;
case -2: return GENERIC_POST_ROLL;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<StartDelay>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
StartDelay> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<StartDelay>() {
@java.lang.Override
public StartDelay findValueByNumber(int number) {
return StartDelay.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return StartDelayVerifier.INSTANCE;
}
private static final class StartDelayVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new StartDelayVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return StartDelay.forNumber(number) != null;
}
};
private final int value;
private StartDelay(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.StartDelay)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/UserAgentSource.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* Possible sources for User-Agent data.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.UserAgentSource}
*/
public enum UserAgentSource
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>UNKNOWN_SOURCE = 0;</code>
*/
UNKNOWN_SOURCE(0),
/**
* <pre>
* User-Agent Client Hints (only low-entropy headers were available).
* </pre>
*
* <code>CLIENT_HINTS_LOW_ENTROPY = 1;</code>
*/
CLIENT_HINTS_LOW_ENTROPY(1),
/**
* <pre>
* User-Agent Client Hints (with high-entropy headers available).
* </pre>
*
* <code>CLIENT_HINTS_HIGH_ENTROPY = 2;</code>
*/
CLIENT_HINTS_HIGH_ENTROPY(2),
/**
* <pre>
* Parsed from User-Agent header.
* </pre>
*
* <code>USER_AGENT_STRING = 3;</code>
*/
USER_AGENT_STRING(3),
;
/**
* <code>UNKNOWN_SOURCE = 0;</code>
*/
public static final int UNKNOWN_SOURCE_VALUE = 0;
/**
* <pre>
* User-Agent Client Hints (only low-entropy headers were available).
* </pre>
*
* <code>CLIENT_HINTS_LOW_ENTROPY = 1;</code>
*/
public static final int CLIENT_HINTS_LOW_ENTROPY_VALUE = 1;
/**
* <pre>
* User-Agent Client Hints (with high-entropy headers available).
* </pre>
*
* <code>CLIENT_HINTS_HIGH_ENTROPY = 2;</code>
*/
public static final int CLIENT_HINTS_HIGH_ENTROPY_VALUE = 2;
/**
* <pre>
* Parsed from User-Agent header.
* </pre>
*
* <code>USER_AGENT_STRING = 3;</code>
*/
public static final int USER_AGENT_STRING_VALUE = 3;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static UserAgentSource valueOf(int value) {
return forNumber(value);
}
public static UserAgentSource forNumber(int value) {
switch (value) {
case 0: return UNKNOWN_SOURCE;
case 1: return CLIENT_HINTS_LOW_ENTROPY;
case 2: return CLIENT_HINTS_HIGH_ENTROPY;
case 3: return USER_AGENT_STRING;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<UserAgentSource>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
UserAgentSource> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<UserAgentSource>() {
@java.lang.Override
public UserAgentSource findValueByNumber(int number) {
return UserAgentSource.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return UserAgentSourceVerifier.INSTANCE;
}
private static final class UserAgentSourceVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new UserAgentSourceVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return UserAgentSource.forNumber(number) != null;
}
};
private final int value;
private UserAgentSource(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.UserAgentSource)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/VideoLinearity.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.0: The following table indicates the options for video
* linearity. "In-stream" or "linear" video refers to pre-roll, post-roll,
* or mid-roll video ads where the user is forced to watch ad in order to
* see the video content. "Overlay" or "non-linear" refer to ads that are
* shown on top of the video content.
* This field is optional. The following is the interpretation of the
* bidder based upon presence or absence of the field in the bid request:
* - If no value is set, any ad (linear or not) can be present
* in the response.
* - If a value is set, only ads of the corresponding type can be present
* in the response.
* This OpenRTB table has values derived from the IAB Quality Assurance
* Guidelines (QAG). Practitioners should keep in sync with updates to the
* QAG values as published on IAB.net.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.VideoLinearity}
*/
public enum VideoLinearity
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* Linear/In-stream
* </pre>
*
* <code>LINEAR = 1;</code>
*/
LINEAR(1),
/**
* <pre>
* Non-linear/Overlay
* </pre>
*
* <code>NON_LINEAR = 2;</code>
*/
NON_LINEAR(2),
;
/**
* <pre>
* Linear/In-stream
* </pre>
*
* <code>LINEAR = 1;</code>
*/
public static final int LINEAR_VALUE = 1;
/**
* <pre>
* Non-linear/Overlay
* </pre>
*
* <code>NON_LINEAR = 2;</code>
*/
public static final int NON_LINEAR_VALUE = 2;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static VideoLinearity valueOf(int value) {
return forNumber(value);
}
public static VideoLinearity forNumber(int value) {
switch (value) {
case 1: return LINEAR;
case 2: return NON_LINEAR;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<VideoLinearity>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
VideoLinearity> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<VideoLinearity>() {
@java.lang.Override
public VideoLinearity findValueByNumber(int number) {
return VideoLinearity.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return VideoLinearityVerifier.INSTANCE;
}
private static final class VideoLinearityVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new VideoLinearityVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return VideoLinearity.forNumber(number) != null;
}
};
private final int value;
private VideoLinearity(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.VideoLinearity)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/VideoPlacementType.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.5: The following table lists the various types of video placements
* derived largely from the IAB Digital Video Guidelines.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.VideoPlacementType}
*/
public enum VideoPlacementType
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* The video placement is not defined.
* Default value.
* </pre>
*
* <code>UNDEFINED_VIDEO_PLACEMENT = 0;</code>
*/
UNDEFINED_VIDEO_PLACEMENT(0),
/**
* <pre>
* Played before, during or after the streaming video content
* that the consumer has requested.
* For example: Pre-roll, Mid-roll, Post-roll.
* </pre>
*
* <code>IN_STREAM_PLACEMENT = 1;</code>
*/
IN_STREAM_PLACEMENT(1),
/**
* <pre>
* Exists within a web banner that leverages the banner space
* to deliver a video experience as opposed to another static
* or rich media format.
* The format relies on the existence of display ad inventory
* on the page for its delivery.
* </pre>
*
* <code>IN_BANNER_PLACEMENT = 2;</code>
*/
IN_BANNER_PLACEMENT(2),
/**
* <pre>
* Loads and plays dynamically between paragraphs of editorial content;
* existing as a standalone branded message.
* </pre>
*
* <code>IN_ARTICLE_PLACEMENT = 3;</code>
*/
IN_ARTICLE_PLACEMENT(3),
/**
* <pre>
* In-Feed - Found in content, social, or product feeds.
* </pre>
*
* <code>IN_FEED_PLACEMENT = 4;</code>
*/
IN_FEED_PLACEMENT(4),
/**
* <pre>
* Interstitial/Slider/Floating.
* Covers the entire or a portion of screen area,
* but is always on screen while displayed
* (for example, cannot be scrolled out of view).
* Note that a full-screen interstitial (for example, in mobile)
* can be distinguished from a floating/slider unit by the imp.instl field.
* </pre>
*
* <code>FLOATING_PLACEMENT = 5;</code>
*/
FLOATING_PLACEMENT(5),
;
/**
* <pre>
* The video placement is not defined.
* Default value.
* </pre>
*
* <code>UNDEFINED_VIDEO_PLACEMENT = 0;</code>
*/
public static final int UNDEFINED_VIDEO_PLACEMENT_VALUE = 0;
/**
* <pre>
* Played before, during or after the streaming video content
* that the consumer has requested.
* For example: Pre-roll, Mid-roll, Post-roll.
* </pre>
*
* <code>IN_STREAM_PLACEMENT = 1;</code>
*/
public static final int IN_STREAM_PLACEMENT_VALUE = 1;
/**
* <pre>
* Exists within a web banner that leverages the banner space
* to deliver a video experience as opposed to another static
* or rich media format.
* The format relies on the existence of display ad inventory
* on the page for its delivery.
* </pre>
*
* <code>IN_BANNER_PLACEMENT = 2;</code>
*/
public static final int IN_BANNER_PLACEMENT_VALUE = 2;
/**
* <pre>
* Loads and plays dynamically between paragraphs of editorial content;
* existing as a standalone branded message.
* </pre>
*
* <code>IN_ARTICLE_PLACEMENT = 3;</code>
*/
public static final int IN_ARTICLE_PLACEMENT_VALUE = 3;
/**
* <pre>
* In-Feed - Found in content, social, or product feeds.
* </pre>
*
* <code>IN_FEED_PLACEMENT = 4;</code>
*/
public static final int IN_FEED_PLACEMENT_VALUE = 4;
/**
* <pre>
* Interstitial/Slider/Floating.
* Covers the entire or a portion of screen area,
* but is always on screen while displayed
* (for example, cannot be scrolled out of view).
* Note that a full-screen interstitial (for example, in mobile)
* can be distinguished from a floating/slider unit by the imp.instl field.
* </pre>
*
* <code>FLOATING_PLACEMENT = 5;</code>
*/
public static final int FLOATING_PLACEMENT_VALUE = 5;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static VideoPlacementType valueOf(int value) {
return forNumber(value);
}
public static VideoPlacementType forNumber(int value) {
switch (value) {
case 0: return UNDEFINED_VIDEO_PLACEMENT;
case 1: return IN_STREAM_PLACEMENT;
case 2: return IN_BANNER_PLACEMENT;
case 3: return IN_ARTICLE_PLACEMENT;
case 4: return IN_FEED_PLACEMENT;
case 5: return FLOATING_PLACEMENT;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<VideoPlacementType>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
VideoPlacementType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<VideoPlacementType>() {
@java.lang.Override
public VideoPlacementType findValueByNumber(int number) {
return VideoPlacementType.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return VideoPlacementTypeVerifier.INSTANCE;
}
private static final class VideoPlacementTypeVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new VideoPlacementTypeVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return VideoPlacementType.forNumber(number) != null;
}
};
private final int value;
private VideoPlacementType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.VideoPlacementType)
}
|
0 | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos | java-sources/ai/themsp/mes-android-sdk/0.15.0/main/com/particles/mes/protos/openrtb/VolumeNormalizationMode.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: openrtb/openrtb-v26.proto
package com.particles.mes.protos.openrtb;
/**
* <pre>
* OpenRTB 2.4: The following table lists the types of volume normalization
* modes, typically for audio.
* </pre>
*
* Protobuf enum {@code com.google.openrtb.VolumeNormalizationMode}
*/
public enum VolumeNormalizationMode
implements com.google.protobuf.Internal.EnumLite {
/**
* <code>NONE = 0;</code>
*/
NONE(0),
/**
* <code>AVERAGE_VOLUME = 1;</code>
*/
AVERAGE_VOLUME(1),
/**
* <code>PEAK_VOLUME = 2;</code>
*/
PEAK_VOLUME(2),
/**
* <code>LOUDNESS = 3;</code>
*/
LOUDNESS(3),
/**
* <code>CUSTOM_VOLUME = 4;</code>
*/
CUSTOM_VOLUME(4),
;
/**
* <code>NONE = 0;</code>
*/
public static final int NONE_VALUE = 0;
/**
* <code>AVERAGE_VOLUME = 1;</code>
*/
public static final int AVERAGE_VOLUME_VALUE = 1;
/**
* <code>PEAK_VOLUME = 2;</code>
*/
public static final int PEAK_VOLUME_VALUE = 2;
/**
* <code>LOUDNESS = 3;</code>
*/
public static final int LOUDNESS_VALUE = 3;
/**
* <code>CUSTOM_VOLUME = 4;</code>
*/
public static final int CUSTOM_VOLUME_VALUE = 4;
@java.lang.Override
public final int getNumber() {
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static VolumeNormalizationMode valueOf(int value) {
return forNumber(value);
}
public static VolumeNormalizationMode forNumber(int value) {
switch (value) {
case 0: return NONE;
case 1: return AVERAGE_VOLUME;
case 2: return PEAK_VOLUME;
case 3: return LOUDNESS;
case 4: return CUSTOM_VOLUME;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<VolumeNormalizationMode>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
VolumeNormalizationMode> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<VolumeNormalizationMode>() {
@java.lang.Override
public VolumeNormalizationMode findValueByNumber(int number) {
return VolumeNormalizationMode.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return VolumeNormalizationModeVerifier.INSTANCE;
}
private static final class VolumeNormalizationModeVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new VolumeNormalizationModeVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return VolumeNormalizationMode.forNumber(number) != null;
}
};
private final int value;
private VolumeNormalizationMode(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:com.google.openrtb.VolumeNormalizationMode)
}
|
0 | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads/browser/NestedWebView.java | package com.particles.android.ads.browser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.OverScroller;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.NestedScrollingChild3;
import androidx.core.view.NestedScrollingChildHelper;
import androidx.core.view.ViewCompat;
/**
* https://github.com/gdutxiaoxu/nestedwebview
*/
public class NestedWebView extends WebView implements NestedScrollingChild3 {
private static final String TAG = "NestedWebView";
private static final int INVALID_POINTER = -1;
private final int[] mScrollOffset = new int[2];
private final int[] mScrollConsumed = new int[2];
private int mLastMotionY;
private NestedScrollingChildHelper mChildHelper;
private boolean mIsBeingDragged = false;
private VelocityTracker mVelocityTracker;
private int mTouchSlop;
private int mActivePointerId = INVALID_POINTER;
private int mNestedYOffset;
private OverScroller mScroller;
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mLastScrollerY;
public NestedWebView(Context context) {
this(context, null);
}
public NestedWebView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.webViewStyle);
}
public NestedWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOverScrollMode(WebView.OVER_SCROLL_NEVER);
initScrollView();
mChildHelper = new NestedScrollingChildHelper(this);
setNestedScrollingEnabled(true);
}
private void initScrollView() {
mScroller = new OverScroller(getContext());
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { // most common
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId);
if (pointerIndex == -1) {
Log.e(TAG, "Invalid pointerId=" + activePointerId
+ " in onInterceptTouchEvent");
break;
}
final int y = (int) ev.getY(pointerIndex);
final int yDiff = Math.abs(y - mLastMotionY);
if (yDiff > mTouchSlop
&& (getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) {
mIsBeingDragged = true;
mLastMotionY = y;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
mNestedYOffset = 0;
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
break;
case MotionEvent.ACTION_DOWN:
mLastMotionY = (int) ev.getY();
mActivePointerId = ev.getPointerId(0);
initOrResetVelocityTracker();
mVelocityTracker.addMovement(ev);
mScroller.computeScrollOffset();
mIsBeingDragged = !mScroller.isFinished();
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
recycleVelocityTracker();
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
ViewCompat.postInvalidateOnAnimation(this);
}
stopNestedScroll();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
return mIsBeingDragged;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
MotionEvent vtev = MotionEvent.obtain(ev);
final int actionMasked = ev.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
mNestedYOffset = 0;
}
vtev.offsetLocation(0, mNestedYOffset);
switch (actionMasked) {
case MotionEvent.ACTION_DOWN:
if ((mIsBeingDragged = !mScroller.isFinished())) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
if (!mScroller.isFinished()) {
abortAnimatedScroll();
}
mLastMotionY = (int) ev.getY();
mActivePointerId = ev.getPointerId(0);
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH);
break;
case MotionEvent.ACTION_MOVE:
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
if (activePointerIndex == -1) {
Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
break;
}
final int y = (int) ev.getY(activePointerIndex);
int deltaY = mLastMotionY - y;
if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset,
ViewCompat.TYPE_TOUCH)) {
deltaY -= mScrollConsumed[1];
mNestedYOffset += mScrollOffset[1];
}
if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
mIsBeingDragged = true;
if (deltaY > 0) {
deltaY -= mTouchSlop;
} else {
deltaY += mTouchSlop;
}
}
if (mIsBeingDragged) {
mLastMotionY = y - mScrollOffset[1];
final int oldY = getScrollY();
final int range = getScrollRange();
// Calling overScrollByCompat will call onOverScrolled, which
// calls onScrollChanged if applicable.
if (overScrollByCompat(0, deltaY, 0, oldY, 0, range, 0,
0, true) && !hasNestedScrollingParent(ViewCompat.TYPE_TOUCH)) {
mVelocityTracker.clear();
}
final int scrolledDeltaY = getScrollY() - oldY;
final int unconsumedY = deltaY - scrolledDeltaY;
mScrollConsumed[1] = 0;
dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset,
ViewCompat.TYPE_TOUCH, mScrollConsumed);
mLastMotionY -= mScrollOffset[1];
mNestedYOffset += mScrollOffset[1];
}
break;
case MotionEvent.ACTION_UP:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
if (!dispatchNestedPreFling(0, -initialVelocity)) {
dispatchNestedFling(0, -initialVelocity, true);
fling(-initialVelocity);
}
} else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
getScrollRange())) {
ViewCompat.postInvalidateOnAnimation(this);
}
mActivePointerId = INVALID_POINTER;
endDrag();
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
getScrollRange())) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
mActivePointerId = INVALID_POINTER;
endDrag();
break;
case MotionEvent.ACTION_POINTER_DOWN:
final int index = ev.getActionIndex();
mLastMotionY = (int) ev.getY(index);
mActivePointerId = ev.getPointerId(index);
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(vtev);
}
vtev.recycle();
return super.onTouchEvent(ev);
}
private void abortAnimatedScroll() {
mScroller.abortAnimation();
stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);
}
private void endDrag() {
mIsBeingDragged = false;
recycleVelocityTracker();
stopNestedScroll();
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionY = (int) ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void fling(int velocityY) {
int height = getHeight();
mScroller.fling(getScrollX(), getScrollY(), // start
0, velocityY, // velocities
0, 0, // x
Integer.MIN_VALUE, Integer.MAX_VALUE, // y
0, height / 2);
runAnimatedScroll(true);
}
private void runAnimatedScroll(boolean participateInNestedScrolling) {
if (participateInNestedScrolling) {
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_NON_TOUCH);
} else {
stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);
}
mLastScrollerY = getScrollY();
ViewCompat.postInvalidateOnAnimation(this);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept) {
recycleVelocityTracker();
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
private void initOrResetVelocityTracker() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
}
private void initVelocityTrackerIfNotExists() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
}
private void recycleVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY,
int scrollX, int scrollY,
int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY,
boolean isTouchEvent) {
// this is causing double scroll call (doubled speed), but this WebView isn't overscrollable
// all overscrolls are passed to appbar, so commenting this out during drag
if (!mIsBeingDragged)
overScrollByCompat(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY,
maxOverScrollX, maxOverScrollY, isTouchEvent);
// without this call webview won't scroll to top when url change or when user pick input
// (webview should move a bit making input still in viewport when "adjustResize")
return true;
}
int getScrollRange() {
//Using scroll range of webview instead of childs as NestedScrollView does.
return computeVerticalScrollRange();
}
@Override
public boolean isNestedScrollingEnabled() {
return mChildHelper.isNestedScrollingEnabled();
}
@Override
public void setNestedScrollingEnabled(boolean enabled) {
mChildHelper.setNestedScrollingEnabled(enabled);
}
@Override
public boolean startNestedScroll(int axes, int type) {
return mChildHelper.startNestedScroll(axes, type);
}
@Override
public boolean startNestedScroll(int axes) {
return startNestedScroll(axes, ViewCompat.TYPE_TOUCH);
}
@Override
public void stopNestedScroll(int type) {
mChildHelper.stopNestedScroll(type);
}
@Override
public void stopNestedScroll() {
stopNestedScroll(ViewCompat.TYPE_TOUCH);
}
@Override
public boolean hasNestedScrollingParent(int type) {
return mChildHelper.hasNestedScrollingParent(type);
}
@Override
public boolean hasNestedScrollingParent() {
return hasNestedScrollingParent(ViewCompat.TYPE_TOUCH);
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
int[] offsetInWindow) {
return dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
offsetInWindow, ViewCompat.TYPE_TOUCH);
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
int[] offsetInWindow, int type) {
return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
offsetInWindow, type);
}
@Override
public void dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
@Nullable int[] offsetInWindow, int type, @NonNull int[] consumed) {
mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
offsetInWindow, type, consumed);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
return dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, ViewCompat.TYPE_TOUCH);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow, int type) {
return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type);
}
@Override
public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
return mChildHelper.dispatchNestedFling(velocityX, velocityY, false);
}
@Override
public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
return mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
}
@Override
public int getNestedScrollAxes() {
return ViewCompat.SCROLL_AXIS_VERTICAL;
}
@Override
public void computeScroll() {
if (mScroller.isFinished()) {
return;
}
mScroller.computeScrollOffset();
final int y = mScroller.getCurrY();
int unconsumed = y - mLastScrollerY;
mLastScrollerY = y;
// Nested Scrolling Pre Pass
mScrollConsumed[1] = 0;
dispatchNestedPreScroll(0, unconsumed, mScrollConsumed, null,
ViewCompat.TYPE_NON_TOUCH);
unconsumed -= mScrollConsumed[1];
if (unconsumed != 0) {
// Internal Scroll
final int oldScrollY = getScrollY();
overScrollByCompat(0, unconsumed, getScrollX(), oldScrollY, 0, getScrollRange(),
0, 0, false);
final int scrolledByMe = getScrollY() - oldScrollY;
unconsumed -= scrolledByMe;
// Nested Scrolling Post Pass
mScrollConsumed[1] = 0;
dispatchNestedScroll(0, 0, 0, unconsumed, mScrollOffset,
ViewCompat.TYPE_NON_TOUCH, mScrollConsumed);
unconsumed -= mScrollConsumed[1];
}
if (unconsumed != 0) {
abortAnimatedScroll();
}
if (!mScroller.isFinished()) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
// copied from NestedScrollView exacly as it looks, leaving overscroll related code, maybe future use
private boolean overScrollByCompat(int deltaX, int deltaY,
int scrollX, int scrollY,
int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY,
boolean isTouchEvent) {
final int overScrollMode = getOverScrollMode();
final boolean canScrollHorizontal =
computeHorizontalScrollRange() > computeHorizontalScrollExtent();
final boolean canScrollVertical =
computeVerticalScrollRange() > computeVerticalScrollExtent();
final boolean overScrollHorizontal = overScrollMode == View.OVER_SCROLL_ALWAYS
|| (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
final boolean overScrollVertical = overScrollMode == View.OVER_SCROLL_ALWAYS
|| (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
int newScrollX = scrollX + deltaX;
if (!overScrollHorizontal) {
maxOverScrollX = 0;
}
int newScrollY = scrollY + deltaY;
if (!overScrollVertical) {
maxOverScrollY = 0;
}
// Clamp values if at the limits and record
final int left = -maxOverScrollX;
final int right = maxOverScrollX + scrollRangeX;
final int top = -maxOverScrollY;
final int bottom = maxOverScrollY + scrollRangeY;
boolean clampedX = false;
if (newScrollX > right) {
newScrollX = right;
clampedX = true;
} else if (newScrollX < left) {
newScrollX = left;
clampedX = true;
}
boolean clampedY = false;
if (newScrollY > bottom) {
newScrollY = bottom;
clampedY = true;
} else if (newScrollY < top) {
newScrollY = top;
clampedY = true;
}
if (clampedY && !hasNestedScrollingParent(ViewCompat.TYPE_NON_TOUCH)) {
mScroller.springBack(newScrollX, newScrollY, 0, 0, 0, getScrollRange());
}
onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
return clampedX || clampedY;
}
}
|
0 | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads/internal | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads/internal/loader/ApiParamKey.java | package com.particles.android.ads.internal.loader;
/**
* @author foxcoder
* @since 2020-05-29
*/
public class ApiParamKey {
public static final String CV = "cv";
public static final String DEVICE_ID = "device_id";
public static final String PROFILE_ID = "profile_id";
public static final String TS = "ts"; // request timestamp
public static final String WEATHER = "weather"; // whether the weather card is displayed in the brief
public static final String CITY = "city";
public static final String BRAND = "brand";
// ads
public static final String REQ_ID = "req_id";
public static final String FORMAT = "format";
public static final String NUM_ADS = "num_ads";
public static final String AD_UNIT = "ad_unit";
public static final String POSTAL_CODE = "postal_code";
public static final String STATE = "state";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String USER_ID = "user_id";
public static final String SESSION_ID = "session_id";
public static final String LANGUAGE = "language";
public static final String WIDTH = "width";
public static final String HEIGHT = "height";
public static final String MAKE = "make";
public static final String MODEL = "model";
public static final String OS = "os";
public static final String OSV = "osv";
public static final String CARRIER = "carrier";
public static final String LANG = "lang";
public static final String CT = "ct";
public static final String AAID = "aaid";
public static final String LMT = "lmt";
public static final String BUNDLE = "bundle";
public static final String DEDUPE_INFO = "dedupe_info";
public static final String US_PRIVACY = "us_privacy";
}
|
0 | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads/internal/util | java-sources/ai/themsp/nova-sdk/2.5.0/main/com/particles/android/ads/internal/util/viewability/OMSDKUtil.java | package com.particles.android.ads.internal.util.viewability;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.iab.omid.library.newsbreak1.Omid;
import com.iab.omid.library.newsbreak1.ScriptInjector;
import com.iab.omid.library.newsbreak1.adsession.AdSession;
import com.iab.omid.library.newsbreak1.adsession.AdSessionConfiguration;
import com.iab.omid.library.newsbreak1.adsession.AdSessionContext;
import com.iab.omid.library.newsbreak1.adsession.CreativeType;
import com.iab.omid.library.newsbreak1.adsession.FriendlyObstructionPurpose;
import com.iab.omid.library.newsbreak1.adsession.ImpressionType;
import com.iab.omid.library.newsbreak1.adsession.Owner;
import com.iab.omid.library.newsbreak1.adsession.Partner;
import com.iab.omid.library.newsbreak1.adsession.VerificationScriptResource;
import com.particles.android.ads.R;
import com.particles.android.ads.internal.NovaInternal;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class OMSDKUtil {
private static final String PARTNER_NAME = "Newsbreak1";
public static String injectScriptContentIntoHtml(Context context, String html) {
try {
String omidJs = getOmidJs(context);
return ScriptInjector.injectScriptContentIntoHtml(omidJs, html);
} catch (Exception e) {
return html;
}
}
@Nullable
public static AdSession createHtmlAdSession(WebView webView) {
Omid.activate(webView.getContext());
if (!Omid.isActive()) {
return null;
}
Partner partner = Partner.createPartner(PARTNER_NAME, NovaInternal.INSTANCE.getAppVersion());
AdSessionContext adSessionContext =
AdSessionContext.createHtmlAdSessionContext(partner, webView, "", "");
AdSessionConfiguration adSessionConfiguration = AdSessionConfiguration.createAdSessionConfiguration(
CreativeType.HTML_DISPLAY,
ImpressionType.BEGIN_TO_RENDER,
Owner.NATIVE,
Owner.NONE,
false);
return AdSession.createAdSession(adSessionConfiguration, adSessionContext);
}
@Nullable
public static AdSession createNativeAdSession(Context applicationContext, List<String> verificationResourceUrls) {
Omid.activate(applicationContext);
if (!Omid.isActive()) {
return null;
}
AdSessionConfiguration adSessionConfiguration =
AdSessionConfiguration.createAdSessionConfiguration(CreativeType.NATIVE_DISPLAY, ImpressionType.VIEWABLE, Owner.NATIVE,
Owner.NONE, false);
try {
Partner partner = Partner.createPartner(PARTNER_NAME, NovaInternal.INSTANCE.getAppVersion());
final String omidJs = getOmidJs(applicationContext);
List<VerificationScriptResource> verificationScripts = getVerificationScriptResources(verificationResourceUrls);
AdSessionContext adSessionContext = AdSessionContext.createNativeAdSessionContext(partner, omidJs, verificationScripts, null, "");
return AdSession.createAdSession(adSessionConfiguration, adSessionContext);
} catch (IOException e) {
return null;
}
}
@Nullable
public static AdSession createNativeVideoSession(Context applicationContext, List<String> verificationResourceUrls) {
Omid.activate(applicationContext);
if (!Omid.isActive()) {
return null;
}
AdSessionConfiguration adSessionConfiguration =
AdSessionConfiguration.createAdSessionConfiguration(CreativeType.VIDEO, ImpressionType.BEGIN_TO_RENDER, Owner.NATIVE,
Owner.NATIVE, false);
try {
Partner partner = Partner.createPartner(PARTNER_NAME, NovaInternal.INSTANCE.getAppVersion());
final String omidJs = getOmidJs(applicationContext);
List<VerificationScriptResource> verificationScripts = getVerificationScriptResources(verificationResourceUrls);
AdSessionContext adSessionContext = AdSessionContext.createNativeAdSessionContext(partner, omidJs, verificationScripts, null, "");
return AdSession.createAdSession(adSessionConfiguration, adSessionContext);
} catch (IOException e) {
return null;
}
}
private static String getOmidJs(Context applicationContext) throws IOException {
Resources res = applicationContext.getResources();
// load IAB OM SDK JavaScript file
InputStream inputStream = res.openRawResource(R.raw.omsdk_v1_4_10);
byte[] b = new byte[inputStream.available()];
final int bytesRead = inputStream.read(b);
return new String(b, 0, bytesRead, "UTF-8");
}
@NonNull
private static List<VerificationScriptResource> getVerificationScriptResources(List<String> verificationResourceUrls)
throws MalformedURLException {
List<VerificationScriptResource> verificationScriptResources = new ArrayList<>();
if (verificationResourceUrls != null) {
for (String url : verificationResourceUrls) {
VerificationScriptResource verificationScriptResource =
VerificationScriptResource.createVerificationScriptResourceWithoutParameters(new URL(url));
verificationScriptResources.add(verificationScriptResource);
}
}
return verificationScriptResources;
}
public static void addFriendlyObstructions(View adView, AdSession adSession) {
// TODO:
// Context context = getActivityContext(adView);
// if (context instanceof NewsDetailActivity) {
// View view = ((Activity) context).findViewById(R.id.bottom_bar_layout);
// if (view != null) {
// adSession.addFriendlyObstruction(view, FriendlyObstructionPurpose.NOT_VISIBLE, "transparent overlay");
// }
// }
}
private static Context getActivityContext(View view) {
for (View v = view; v != null && v.getParent() instanceof View; v = (View) v.getParent()) {
Context context = v.getContext();
if (context instanceof Activity) {
return context;
}
}
return null;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/AdSize.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
/**
* AdSize class defines the size of the ad slot to be made available for auction.
*/
public class AdSize {
private int width;
private int height;
/**
* Creates an ad size object with width and height as specified
*
* @param width width of the ad container
* @param height height of the ad container
*/
public AdSize(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Returns the width of the ad container
*
* @return width
*/
public int getWidth() {
return width;
}
/**
* Returns the height of the ad container
*
* @return height
*/
public int getHeight() {
return height;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AdSize adSize = (AdSize) o;
if (width != adSize.width) return false;
return height == adSize.height;
}
@Override
public int hashCode() {
String size = width + "x" + height;
return size.hashCode();
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/AdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.jetbrains.annotations.NotNull;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.BidInfo;
import org.prebid.mobile.api.data.FetchDemandResult;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.original.OnFetchDemandResult;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import org.prebid.mobile.rendering.bidding.loader.BidLoader;
import org.prebid.mobile.tasksmanager.TasksManager;
import java.util.*;
import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MAX;
import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MIN;
public abstract class AdUnit {
protected AdUnitConfiguration configuration = new AdUnitConfiguration();
@Nullable
protected BidLoader bidLoader;
@Nullable
protected Object adObject;
@Nullable
protected BidResponse bidResponse;
protected boolean allowNullableAdObject = false;
AdUnit(@NonNull String configId, @NonNull EnumSet<AdFormat> adTypes) {
configuration.setConfigId(configId);
configuration.setAdFormats(adTypes);
configuration.setIsOriginalAdUnit(true);
}
public AdUnit(@NotNull String configId) {
configuration.setConfigId(configId);
configuration.setIsOriginalAdUnit(true);
}
/**
* @deprecated Please use setAutoRefreshInterval() in seconds!
*/
@Deprecated
public void setAutoRefreshPeriodMillis(
@IntRange(from = AUTO_REFRESH_DELAY_MIN, to = AUTO_REFRESH_DELAY_MAX) int periodMillis
) {
configuration.setAutoRefreshDelay(periodMillis / 1000);
}
public void setAutoRefreshInterval(
@IntRange(from = AUTO_REFRESH_DELAY_MIN / 1000, to = AUTO_REFRESH_DELAY_MAX / 1000) int seconds
) {
configuration.setAutoRefreshDelay(seconds);
}
public void resumeAutoRefresh() {
LogUtil.verbose("Resuming auto refresh...");
if (bidLoader != null) {
bidLoader.setupRefreshTimer();
}
}
public void stopAutoRefresh() {
LogUtil.verbose("Stopping auto refresh...");
if (bidLoader != null) {
bidLoader.cancelRefresh();
}
}
public void destroy() {
if (bidLoader != null) {
bidLoader.destroy();
}
}
public void fetchDemand(@NonNull final OnCompleteListener2 listener) {
final Map<String, String> keywordsMap = new HashMap<>();
fetchDemand(keywordsMap, (resultCode, message) -> {
TasksManager.getInstance().executeOnMainThread(() ->
listener.onComplete(resultCode, keywordsMap.size() != 0 ? Collections.unmodifiableMap(keywordsMap) : null, message)
);
});
}
public void fetchDemand(Object adObj, @NonNull OnCompleteListener listener) {
if (TextUtils.isEmpty(PrebidMobile.getPrebidServerAccountId())) {
LogUtil.error("Empty account id.");
listener.onComplete(ResultCode.INVALID_ACCOUNT_ID, null);
return;
}
if (TextUtils.isEmpty(configuration.getConfigId())) {
LogUtil.error("Empty config id.");
listener.onComplete(ResultCode.INVALID_CONFIG_ID, null);
return;
}
if (PrebidMobile.getPrebidServerHost().equals(Host.CUSTOM)) {
if (TextUtils.isEmpty(PrebidMobile.getPrebidServerHost().getHostUrl())) {
LogUtil.error("Empty host url for custom Prebid Server host.");
listener.onComplete(ResultCode.INVALID_HOST_URL, null);
return;
}
}
HashSet<AdSize> sizes = configuration.getSizes();
for (AdSize size : sizes) {
if (size.getWidth() < 0 || size.getHeight() < 0) {
listener.onComplete(ResultCode.INVALID_SIZE, null);
return;
}
}
Context context = PrebidMobile.getApplicationContext();
if (context != null) {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr != null && context.checkCallingOrSelfPermission("android.permission.ACCESS_NETWORK_STATE") == PackageManager.PERMISSION_GRANTED) {
NetworkInfo activeNetworkInfo = conMgr.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
listener.onComplete(ResultCode.NETWORK_ERROR, null);
return;
}
}
} else {
LogUtil.error("Invalid context");
listener.onComplete(ResultCode.INVALID_CONTEXT, null);
return;
}
if (Util.supportedAdObject(adObj) || allowNullableAdObject) {
adObject = adObj;
bidLoader = new BidLoader(
context,
configuration,
createBidListener(listener)
);
if (configuration.getAutoRefreshDelay() > 0) {
BidLoader.BidRefreshListener bidRefreshListener = () -> true;
bidLoader.setBidRefreshListener(bidRefreshListener);
LogUtil.verbose("Start fetching bids with auto refresh millis: " + configuration.getAutoRefreshDelay());
} else {
bidLoader.setBidRefreshListener(null);
LogUtil.verbose("Start a single fetching.");
}
bidLoader.load();
} else {
adObject = null;
listener.onComplete(ResultCode.INVALID_AD_OBJECT, null);
}
}
public void fetchDemand(OnFetchDemandResult listener) {
if (listener == null) {
LogUtil.error("Parameter OnFetchDemandResult in fetchDemand() must be not null.");
return;
}
allowNullableAdObject = true;
fetchDemand(null, (resultCode, message) -> {
BidInfo bidInfo = BidInfo.create(resultCode, bidResponse, configuration);
Util.saveCacheId(bidInfo.getNativeCacheId(), adObject);
listener.onComplete(bidInfo, message);
});
}
// MARK: - adunit context data aka inventory data (imp[].ext.context.data)
/**
* This method obtains the context data keyword & value for adunit context targeting
* if the key already exists the value will be appended to the list. No duplicates will be added
*/
public void addContextData(String key, String value) {
configuration.addContextData(key, value);
}
/**
* This method obtains the context data keyword & values for adunit context targeting
* the values if the key already exist will be replaced with the new set of values
*/
public void updateContextData(String key, Set<String> value) {
configuration.addContextData(key, value);
}
/**
* This method allows to remove specific context data keyword & values set from adunit context targeting
*/
public void removeContextData(String key) {
configuration.removeContextData(key);
}
/**
* This method allows to remove all context data set from adunit context targeting
*/
public void clearContextData() {
configuration.clearContextData();
}
Map<String, Set<String>> getContextDataDictionary() {
return configuration.getContextDataDictionary();
}
// MARK: - adunit context keywords (imp[].ext.context.keywords)
/**
* This method obtains the context keyword for adunit context targeting
* Inserts the given element in the set if it is not already present.
*/
public void addContextKeyword(String keyword) {
configuration.addContextKeyword(keyword);
}
/**
* This method obtains the context keyword set for adunit context targeting
* Adds the elements of the given set to the set.
*/
public void addContextKeywords(Set<String> keywords) {
configuration.addContextKeywords(keywords);
}
/**
* This method allows to remove specific context keyword from adunit context targeting
*/
public void removeContextKeyword(String keyword) {
configuration.removeContextKeyword(keyword);
}
/**
* This method allows to remove all keywords from the set of adunit context targeting
*/
public void clearContextKeywords() {
configuration.clearContextKeywords();
}
Set<String> getContextKeywordsSet() {
return configuration.getContextKeywordsSet();
}
/**
* This method obtains the content for adunit, content, in which impression will appear
*/
public void setAppContent(ContentObject content) {
configuration.setAppContent(content);
}
public ContentObject getAppContent() {
return configuration.getAppContent();
}
public void addUserData(DataObject dataObject) {
configuration.addUserData(dataObject);
}
public ArrayList<DataObject> getUserData() {
return configuration.getUserData();
}
public void clearUserData() {
configuration.clearUserData();
}
public String getPbAdSlot() {
return configuration.getPbAdSlot();
}
public void setPbAdSlot(String pbAdSlot) {
configuration.setPbAdSlot(pbAdSlot);
}
protected BidRequesterListener createBidListener(OnCompleteListener originalListener) {
return new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
bidResponse = response;
HashMap<String, String> keywords = response.getTargeting();
Util.apply(keywords, adObject);
originalListener.onComplete(ResultCode.SUCCESS, null);
}
@Override
public void onError(AdException exception) {
bidResponse = null;
Util.apply(null, adObject);
originalListener.onComplete(convertToResultCode(exception), null);
}
};
}
protected ResultCode convertToResultCode(AdException renderingException) {
FetchDemandResult fetchDemandResult = FetchDemandResult.parseErrorMessage(renderingException.getMessage());
LogUtil.error("Prebid", "Can't download bids: " + fetchDemandResult);
switch (fetchDemandResult) {
case INVALID_ACCOUNT_ID:
return ResultCode.INVALID_ACCOUNT_ID;
case INVALID_CONFIG_ID:
return ResultCode.INVALID_CONFIG_ID;
case INVALID_SIZE:
return ResultCode.INVALID_SIZE;
case INVALID_CONTEXT:
return ResultCode.INVALID_CONTEXT;
case INVALID_AD_OBJECT:
return ResultCode.INVALID_AD_OBJECT;
case INVALID_HOST_URL:
return ResultCode.INVALID_HOST_URL;
case NETWORK_ERROR:
return ResultCode.NETWORK_ERROR;
case TIMEOUT:
return ResultCode.TIMEOUT;
case NO_BIDS:
return ResultCode.NO_BIDS;
default:
return ResultCode.PREBID_SERVER_ERROR;
}
}
@VisibleForTesting
public AdUnitConfiguration getConfiguration() {
return configuration;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/BannerAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import org.prebid.mobile.api.data.AdFormat;
import java.util.EnumSet;
import java.util.HashSet;
public class BannerAdUnit extends BannerBaseAdUnit {
public BannerAdUnit(@NonNull String configId, int width, int height) {
super(configId, EnumSet.of(AdFormat.BANNER));
configuration.addSize(new AdSize(width, height));
}
public void addAdditionalSize(int width, int height) {
configuration.addSize(new AdSize(width, height));
}
HashSet<AdSize> getSizes() {
return configuration.getSizes();
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/BannerBaseAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.api.data.AdFormat;
import java.util.EnumSet;
import java.util.List;
public abstract class BannerBaseAdUnit extends AdUnit {
BannerBaseAdUnit(@NonNull String configId, @NonNull EnumSet<AdFormat> adType) {
super(configId, adType);
}
@Nullable
public BannerParameters getBannerParameters() {
return configuration.getBannerParameters();
}
public void setBannerParameters(@Nullable BannerParameters parameters) {
configuration.setBannerParameters(parameters);
}
/**
* @deprecated use `setBannerParameters()`.
*/
@Deprecated
public void setParameters(@Nullable Parameters parameters) {
if (parameters != null) {
BannerParameters newParameters = new BannerParameters();
newParameters.setApi(parameters.getApi());
configuration.setBannerParameters(newParameters);
}
}
/**
* @deprecated use `getBannerParameters()`
*/
@Deprecated
@Nullable
public Parameters getParameters() {
BannerParameters newParameters = configuration.getBannerParameters();
if (newParameters != null) {
Parameters oldParameters = new Parameters();
oldParameters.setApi(newParameters.getApi());
return oldParameters;
}
return null;
}
/**
* Describes an <a href="https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf">OpenRTB</a> banner object
*/
public static class Parameters {
/**
List of supported API frameworks for this impression. If an API is not explicitly listed, it is assumed not to be supported.
*/
@Nullable
private List<Signals.Api> api;
@Nullable
public List<Signals.Api> getApi() {
return api;
}
public void setApi(@Nullable List<Signals.Api> api) {
this.api = api;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/BannerParameters.java | package org.prebid.mobile;
import androidx.annotation.Nullable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Describes an <a href="https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf">OpenRTB</a> banner object
*/
public class BannerParameters {
/**
* List of supported API frameworks for this impression. If an API is not explicitly listed, it is assumed not to be supported.
*/
@Nullable
private List<Signals.Api> api;
@Nullable
private Set<AdSize> adSizes;
@Nullable
private Integer interstitialMinWidthPercentage;
@Nullable
private Integer interstitialMinHeightPercentage;
@Nullable
public List<Signals.Api> getApi() {
return api;
}
public void setApi(@Nullable List<Signals.Api> api) {
this.api = api;
}
@Nullable
public Set<AdSize> getAdSizes() {
return adSizes;
}
public void setAdSizes(@Nullable Set<AdSize> adSizes) {
if (adSizes == null) {
this.adSizes = null;
return;
}
this.adSizes = new HashSet<>(adSizes);
}
@Nullable
public Integer getInterstitialMinWidthPercentage() {
return interstitialMinWidthPercentage;
}
public void setInterstitialMinWidthPercentage(@Nullable Integer interstitialMinWidthPercentage) {
this.interstitialMinWidthPercentage = interstitialMinWidthPercentage;
}
@Nullable
public Integer getInterstitialMinHeightPercentage() {
return interstitialMinHeightPercentage;
}
public void setInterstitialMinHeightPercentage(@Nullable Integer interstitialMinHeightPercentage) {
this.interstitialMinHeightPercentage = interstitialMinHeightPercentage;
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/BidLog.java | package org.prebid.mobile;
public class BidLog {
private BidLogEntry lastEntry;
private static BidLog instance;
public static BidLog getInstance() {
if (instance == null) {
instance = new BidLog();
}
return instance;
}
private BidLog() {
}
public BidLogEntry getLastBid() {
return lastEntry;
}
public void setLastEntry(BidLogEntry entry) {
this.lastEntry = entry;
}
public void cleanLog() {
this.lastEntry = null;
}
public static class BidLogEntry {
private String requestUrl;
private String requestBody;
private int responseCode;
private boolean containsTopBid;
private String response;
public BidLogEntry() {
this.requestUrl = "";
this.requestBody = "";
this.responseCode = -1;
this.containsTopBid = false;
this.response = "";
}
public String getRequestUrl() {
return requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public boolean containsTopBid() {
return containsTopBid;
}
public void setContainsTopBid(boolean containsTopBid) {
this.containsTopBid = containsTopBid;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/CacheManager.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.os.Handler;
import androidx.annotation.VisibleForTesting;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.UUID;
public class CacheManager {
private static final int NATIVE_AD_EXPIRY_TIMEOUT = 300000;
private static HashMap<String, String> savedValues = new HashMap<>();
private static HashMap<String, Long> expiryIntervalMap = new HashMap<>();
private static HashMap<String, CacheExpiryListener> cacheExpiryListenerMap = new HashMap<>();
private static Handler handler = new Handler();
public static String save(String content) {
if (!TextUtils.isEmpty(content)) {
final String cacheId = "Prebid_" + UUID.randomUUID().toString();
savedValues.put(cacheId, content);
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (cacheExpiryListenerMap.containsKey(cacheId)) {
cacheExpiryListenerMap.remove(cacheId).onCacheExpired();
}
savedValues.remove(cacheId);
}
}, getExpiryInterval(cacheId));
return cacheId;
} else {
return null;
}
}
private static long getExpiryInterval(String cacheId) {
return expiryIntervalMap.containsKey(cacheId) ? expiryIntervalMap.get(cacheId) : NATIVE_AD_EXPIRY_TIMEOUT;
}
public static boolean isValid(String cacheId) {
return savedValues.keySet().contains(cacheId);
}
@VisibleForTesting
public static void clear() {
savedValues.clear();
cacheExpiryListenerMap.clear();
expiryIntervalMap.clear();
}
protected static String get(String cacheId) {
return savedValues.remove(cacheId);
}
protected static void registerCacheExpiryListener(String cacheId, CacheExpiryListener expiryListener) {
cacheExpiryListenerMap.put(cacheId, expiryListener);
}
public static void setExpiry(String cacheId, long exp) {
expiryIntervalMap.put(cacheId, exp * 1000); //converting seconds into ms
}
interface CacheExpiryListener {
void onCacheExpired();
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ContentObject.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ContentObject {
/**
* ID uniquely identifying the content.
*/
@Nullable
private String id;
/**
* Episode number.
*/
@Nullable
private Integer episode;
/**
* Content title.
*/
@Nullable
private String title;
/**
* Content series.
*/
@Nullable
private String series;
/**
* Content season.
*/
@Nullable
private String season;
/**
* Artist credited with the content.
*/
@Nullable
private String artist;
/**
* Genre that best describes the content.
*/
@Nullable
private String genre;
/**
* Album to which the content belongs; typically for audio.
*/
@Nullable
private String album;
/**
* International Standard Recording Code conforming to ISO- 3901.
*/
@Nullable
private String isrc;
/**
* URL of the content, for buy-side contextualization or review.
*/
@Nullable
private String url;
/**
* Array of IAB content categories that describe the content producer.
*/
@NonNull
private ArrayList<String> categories = new ArrayList<>();
/**
* Production quality.
*/
@Nullable
private Integer productionQuality;
/**
* Type of content (game, video, text, etc.).
*/
@Nullable
private Integer context;
/**
* Content rating (e.g., MPAA).
*/
@Nullable
private String contentRating;
/**
* User rating of the content (e.g., number of stars, likes, etc.).
*/
@Nullable
private String userRating;
/**
* Media rating per IQG guidelines.
*/
@Nullable
private Integer qaMediaRating;
/**
* Comma separated list of keywords describing the content.
*/
@Nullable
private String keywords;
/**
* Live stream. 0 = not live, 1 = content is live (e.g., stream, live blog).
*/
@Nullable
private Integer liveStream;
/**
* Source relationship. 0 = indirect, 1 = direct.
*/
@Nullable
private Integer sourceRelationship;
/**
* Length of content in seconds; appropriate for video or audio.
*/
@Nullable
private Integer length;
/**
* Content language using ISO-639-1-alpha-2.
*/
@Nullable
private String language;
/**
* Indicator of whether or not the content is embeddable (e.g., an embeddable video player), where 0 = no, 1 = yes.
*/
@Nullable
private Integer embeddable;
/**
* Additional content data.
*/
@NonNull
private ArrayList<DataObject> dataObjects = new ArrayList<>();
/**
* This object defines the producer of the content in which the ad will be shown.
*/
@Nullable
private ProducerObject producerObject;
/**
* @return JSONObject if at least one parameter was set; otherwise null.
*/
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("id", id);
result.putOpt("episode", episode);
result.putOpt("title", title);
result.putOpt("series", series);
result.putOpt("season", season);
result.putOpt("artist", artist);
result.putOpt("genre", genre);
result.putOpt("album", album);
result.putOpt("isrc", isrc);
result.putOpt("url", url);
result.putOpt("prodq", productionQuality);
result.putOpt("context", context);
result.putOpt("contentrating", contentRating);
result.putOpt("userrating", userRating);
result.putOpt("qagmediarating", qaMediaRating);
result.putOpt("keywords", keywords);
result.putOpt("livestream", liveStream);
result.putOpt("sourcerelationship", sourceRelationship);
result.putOpt("len", length);
result.putOpt("language", language);
result.putOpt("embeddable", embeddable);
if (producerObject != null) {
result.putOpt("producer", producerObject.getJsonObject());
}
if (!categories.isEmpty()) {
JSONArray jsonCategories = new JSONArray();
for (String category : categories) {
jsonCategories.put(category);
}
result.putOpt("cat", jsonCategories);
}
if (!dataObjects.isEmpty()) {
JSONArray dataJson = new JSONArray();
for (DataObject dataObject : dataObjects) {
dataJson.put(dataObject.getJsonObject());
}
result.put("data", dataJson);
}
if (result.length() == 0) {
return null;
}
} catch (JSONException exception) {
LogUtil.error("ContentObject", "Can't create json result object.");
}
return result;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public Integer getEpisode() {
return episode;
}
public void setEpisode(@Nullable Integer episode) {
this.episode = episode;
}
@Nullable
public String getTitle() {
return title;
}
public void setTitle(@Nullable String title) {
this.title = title;
}
@Nullable
public String getSeries() {
return series;
}
public void setSeries(@Nullable String series) {
this.series = series;
}
@Nullable
public String getSeason() {
return season;
}
public void setSeason(@Nullable String season) {
this.season = season;
}
@Nullable
public String getArtist() {
return artist;
}
public void setArtist(@Nullable String artist) {
this.artist = artist;
}
@Nullable
public String getGenre() {
return genre;
}
public void setGenre(@Nullable String genre) {
this.genre = genre;
}
@Nullable
public String getAlbum() {
return album;
}
public void setAlbum(@Nullable String album) {
this.album = album;
}
@Nullable
public String getIsrc() {
return isrc;
}
public void setIsrc(@Nullable String isrc) {
this.isrc = isrc;
}
@Nullable
public String getUrl() {
return url;
}
public void setUrl(@Nullable String url) {
this.url = url;
}
public void addCategory(@NonNull String category) {
categories.add(category);
}
@NonNull
public ArrayList<String> getCategories() {
return categories;
}
public void setCategories(@NonNull ArrayList<String> categories) {
this.categories = categories;
}
@Nullable
public Integer getProductionQuality() {
return productionQuality;
}
public void setProductionQuality(@Nullable Integer productionQuality) {
this.productionQuality = productionQuality;
}
@Nullable
public Integer getContext() {
return context;
}
public void setContext(@Nullable Integer context) {
this.context = context;
}
@Nullable
public String getContentRating() {
return contentRating;
}
public void setContentRating(@Nullable String contentRating) {
this.contentRating = contentRating;
}
@Nullable
public String getUserRating() {
return userRating;
}
public void setUserRating(@Nullable String userRating) {
this.userRating = userRating;
}
@Nullable
public Integer getQaMediaRating() {
return qaMediaRating;
}
public void setQaMediaRating(@Nullable Integer qaMediaRating) {
this.qaMediaRating = qaMediaRating;
}
@Nullable
public String getKeywords() {
return keywords;
}
public void setKeywords(@Nullable String keywords) {
this.keywords = keywords;
}
@Nullable
public Integer getLiveStream() {
return liveStream;
}
public void setLiveStream(@Nullable Integer liveStream) {
this.liveStream = liveStream;
}
@Nullable
public Integer getSourceRelationship() {
return sourceRelationship;
}
public void setSourceRelationship(@Nullable Integer sourceRelationship) {
this.sourceRelationship = sourceRelationship;
}
@Nullable
public Integer getLength() {
return length;
}
public void setLength(@Nullable Integer length) {
this.length = length;
}
@Nullable
public String getLanguage() {
return language;
}
public void setLanguage(@Nullable String language) {
this.language = language;
}
@Nullable
public Integer getEmbeddable() {
return embeddable;
}
public void setEmbeddable(@Nullable Integer embeddable) {
this.embeddable = embeddable;
}
public void addData(@NonNull DataObject dataObject) {
dataObjects.add(dataObject);
}
@NonNull
public ArrayList<DataObject> getDataList() {
return dataObjects;
}
public void setDataList(@NonNull ArrayList<DataObject> dataObjects) {
this.dataObjects = dataObjects;
}
public void clearDataList() {
dataObjects.clear();
}
@Nullable
public ProducerObject getProducer() {
return producerObject;
}
public void setProducer(@Nullable ProducerObject producerObject) {
this.producerObject = producerObject;
}
public static class ProducerObject {
/**
* Content producer or originator ID.
*/
@Nullable
private String id;
/**
* Content producer or originator name (e.g., “Warner Bros”).
*/
@Nullable
private String name;
/**
* Array of IAB content categories that describe the content producer.
*/
@NonNull
private ArrayList<String> categories = new ArrayList<>();
/**
* Highest level domain of the content producer (e.g., “producer.com”).
*/
@Nullable
private String domain;
@Nullable
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("id", id);
result.putOpt("name", name);
result.putOpt("domain", domain);
if (!categories.isEmpty()) {
JSONArray categoriesJson = new JSONArray();
for (String category : categories) {
categoriesJson.put(category);
}
result.put("cat", categoriesJson);
}
} catch (JSONException exception) {
LogUtil.error("ContentObject", "Can't create json producer content object.");
}
return result;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
public void addCategory(@NonNull String category) {
categories.add(category);
}
@NonNull
public List<String> getCategories() {
return categories;
}
public void setCategories(@NonNull ArrayList<String> categories) {
this.categories = categories;
}
@Nullable
public String getDomain() {
return domain;
}
public void setDomain(@Nullable String domain) {
this.domain = domain;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/DataObject.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class DataObject {
/**
* Exchange-specific ID for the data provider.
*/
@Nullable
private String id;
/**
* Exchange-specific name for the data provider.
*/
@Nullable
private String name;
/**
* Segment objects are essentially key-value pairs that convey specific units of data.
*/
@NonNull
private ArrayList<SegmentObject> segments = new ArrayList<>();
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("id", id);
result.putOpt("name", name);
if (!segments.isEmpty()) {
JSONArray segmentsJson = new JSONArray();
for (SegmentObject segment : segments) {
segmentsJson.put(segment.getJsonObject());
}
result.put("segment", segmentsJson);
}
} catch (JSONException exception) {
LogUtil.error("DataObject", "Can't create json data content object.");
}
return result;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
public void addSegment(@NonNull SegmentObject segmentObject) {
segments.add(segmentObject);
}
@NonNull
public ArrayList<SegmentObject> getSegments() {
return segments;
}
public void setSegments(@NonNull ArrayList<SegmentObject> segments) {
this.segments = segments;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataObject that = (DataObject) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return segments.equals(that.segments);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + segments.hashCode();
return result;
}
public static class SegmentObject {
/**
* ID of the data segment specific to the data provider.
*/
@Nullable
private String id;
/**
* Name of the data segment specific to the data provider.
*/
@Nullable
private String name;
/**
* String representation of the data segment value.
*/
@Nullable
private String value;
@Nullable
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("id", id);
result.putOpt("name", name);
result.putOpt("value", value);
} catch (JSONException exception) {
LogUtil.error("SegmentObject", "Can't create json segment object.");
}
return result;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public String getValue() {
return value;
}
public void setValue(@Nullable String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SegmentObject that = (SegmentObject) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return value != null ? value.equals(that.value) : that.value == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ExternalUserId.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
/**
* Defines the User Id Object from an External Third Party Source
*/
public class ExternalUserId {
private String source;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
private String identifier;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
private Integer atype;
public Integer getAtype() {
return atype;
}
public void setAtype(Integer atype) {
this.atype = atype;
}
private Map<String, Object> ext;
public Map<String, Object> getExt() {
return ext;
}
public void setExt(Map<String, Object> ext) {
this.ext = ext;
}
/**
* Initialize ExternalUserId Class
* - Parameter source: Source of the External User Id String.
* - Parameter identifier: String of the External User Id.
* - Parameter atype: (Optional) Integer of the External User Id.
* - Parameter ext: (Optional) Map of the External User Id.
*/
public ExternalUserId(@NonNull String source, @NonNull String identifier, Integer atype, Map<String, Object> ext) {
this.source = source;
this.identifier = identifier;
this.atype = atype;
this.ext = ext;
}
@Nullable
public JSONObject getJson() {
JSONObject result = new JSONObject();
if (getSource() == null || getSource().isEmpty() || getIdentifier() == null || getIdentifier().isEmpty()) {
return null;
}
try {
JSONObject uidObject = new JSONObject();
uidObject.putOpt("id", getIdentifier());
uidObject.putOpt("adtype", getAtype());
if (getExt() != null) {
uidObject.putOpt("ext", new JSONObject(getExt()));
}
result.put("source", getSource());
result.put("uids", new JSONArray().put(uidObject));
} catch (JSONException e) {
LogUtil.warning("ExternalUserId", "Can't create json object.");
return null;
}
return result;
}
@Override
public String toString() {
JSONObject transformedUserIdObject = new JSONObject();
try {
transformedUserIdObject.put("source", getSource());
transformedUserIdObject.put("id", getIdentifier());
transformedUserIdObject.put("atype", getAtype());
if (getExt() != null && !getExt().isEmpty()) {
JSONObject extObject = new JSONObject(getExt());
transformedUserIdObject.put("ext", extObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
return transformedUserIdObject.toString();
}
static List<ExternalUserId> getExternalUidListFromJson(String list) {
List<ExternalUserId> externalUserIdList = new ArrayList<>();
try {
JSONArray jsonArr = new JSONArray(list);
for (int i = 0; i < jsonArr.length(); i++) {
if (getExternalUidFromJson(jsonArr.getJSONObject(i).toString()) != null) {
externalUserIdList.add(getExternalUidFromJson(jsonArr.getJSONObject(i).toString()));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return externalUserIdList;
}
static ExternalUserId getExternalUidFromJson(String json) {
ExternalUserId extUId = null;
try {
JSONObject jsonObject = new JSONObject(json);
String source = jsonObject.has("source") ? jsonObject.optString("source") : null;
String id = jsonObject.has("id") ? jsonObject.optString("id") : null;
Integer aType = jsonObject.has("atype") ? jsonObject.optInt("atype") : null;
Map<String, Object> ext = null;
JSONObject extObj = jsonObject.optJSONObject("ext");
if (extObj != null) {
for (Iterator<String> it = extObj.keys(); it.hasNext(); ) {
ext = new HashMap<>();
String key = it.next();
ext.put(key, extObj.getString(key));
}
}
extUId = new ExternalUserId(source, id, aType, ext);
} catch (JSONException e) {
e.printStackTrace();
}
return extUId;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/Host.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
public enum Host {
/**
* URL <a href=https://ib.adnxs.com/openrtb2/prebid>https://ib.adnxs.com/openrtb2/prebid</a>
*/
APPNEXUS("https://ib.adnxs.com/openrtb2/prebid"),
/**
* URL <a href=https://prebid-server.rubiconproject.com/openrtb2/auction>https://prebid-server.rubiconproject.com/openrtb2/auction</a>
*/
RUBICON("https://prebid-server.rubiconproject.com/openrtb2/auction"),
CUSTOM("");
private String url;
Host(String url) {
this.url = url;
}
public String getHostUrl() {
return this.url;
}
public void setHostUrl(String url) {
if (this.equals(CUSTOM)) {
this.url = url;
}
}
public static Host createCustomHost(String url) {
Host custom = Host.CUSTOM;
custom.setHostUrl(url);
return custom;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ImpressionTracker.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.annotation.SuppressLint;
import android.content.Context;
import org.prebid.mobile.http.HTTPGet;
import org.prebid.mobile.http.HTTPResponse;
class ImpressionTracker {
private String url;
private VisibilityDetector visibilityDetector;
private boolean fired = false;
private Context context;
private ImpressionListener listener;
private ImpressionTrackerListener impressionTrackerListener;
static ImpressionTracker create(String url, VisibilityDetector visibilityDetector, Context context, ImpressionTrackerListener impressionTrackerListener) {
if (visibilityDetector == null) {
return null;
} else {
ImpressionTracker impressionTracker = new ImpressionTracker(url, visibilityDetector, context, impressionTrackerListener);
visibilityDetector.addVisibilityListener(impressionTracker.listener);
return impressionTracker;
}
}
private ImpressionTracker(String url, VisibilityDetector visibilityDetector, Context context, ImpressionTrackerListener impressionTrackerListener) {
this.url = url;
this.visibilityDetector = visibilityDetector;
this.listener = new ImpressionListener();
this.context = context;
this.impressionTrackerListener = impressionTrackerListener;
}
private synchronized void fire() {
// check if impression has already fired
if (!fired) {
SharedNetworkManager nm = SharedNetworkManager.getInstance(context);
if (nm.isConnected(context)) {
@SuppressLint("StaticFieldLeak") HTTPGet asyncTask = new HTTPGet() {
@Override
protected void onPostExecute(HTTPResponse response) {
if (impressionTrackerListener != null) {
impressionTrackerListener.onImpressionTrackerFired();
}
}
@Override
protected String getUrl() {
return url;
}
};
asyncTask.execute();
visibilityDetector.removeVisibilityListener(listener);
listener = null;
} else {
nm.addURL(url, context, new ImpressionTrackerListener() {
@Override
public void onImpressionTrackerFired() {
if (impressionTrackerListener != null) {
impressionTrackerListener.onImpressionTrackerFired();
}
}
});
}
fired = true;
}
}
class ImpressionListener implements VisibilityDetector.VisibilityListener {
long elapsedTime = 0;
@Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
elapsedTime += VisibilityDetector.VISIBILITY_THROTTLE_MILLIS;
} else {
elapsedTime = 0;
}
if (elapsedTime >= Util.NATIVE_AD_VISIBLE_PERIOD_MILLIS) {
ImpressionTracker.this.fire();
}
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ImpressionTrackerListener.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
public interface ImpressionTrackerListener {
public void onImpressionTrackerFired();
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/InStreamVideoAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import org.prebid.mobile.api.data.AdFormat;
import java.util.EnumSet;
public class InStreamVideoAdUnit extends VideoBaseAdUnit {
public InStreamVideoAdUnit(@NonNull String configId, int width, int height) {
super(configId, EnumSet.of(AdFormat.VAST));
configuration.addSize(new AdSize(width, height));
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/InterstitialAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.AdUnitFormat;
import org.prebid.mobile.rendering.models.AdPosition;
import org.prebid.mobile.rendering.models.PlacementType;
import java.util.EnumSet;
public class InterstitialAdUnit extends BannerBaseAdUnit {
public InterstitialAdUnit(@NonNull String configId) {
super(configId, EnumSet.of(AdFormat.INTERSTITIAL));
configuration.setAdPosition(AdPosition.FULLSCREEN);
}
public InterstitialAdUnit(@NonNull String configId, int minWidthPerc, int minHeightPerc) {
this(configId);
configuration.setMinSizePercentage(new AdSize(minWidthPerc, minHeightPerc));
}
@Nullable
AdSize getMinSizePerc() {
return configuration.getMinSizePercentage();
}
/**
* Constructor for multi-format request.
*
* @param adUnitFormats for example `EnumSet.of(AdUnitFormat.DISPLAY, AdUnitFormat.VIDEO);`
*/
public InterstitialAdUnit(@NonNull String configId, EnumSet<AdUnitFormat> adUnitFormats) {
super(configId, AdFormat.fromSet(adUnitFormats, true));
if (adUnitFormats.contains(AdUnitFormat.VIDEO)) {
configuration.setAdPosition(AdPosition.FULLSCREEN);
configuration.setPlacementType(PlacementType.INTERSTITIAL);
}
}
public void setMinSizePercentage(
@IntRange(from = 0, to = 100) int width,
@IntRange(from = 0, to = 100) int height
) {
configuration.setMinSizePercentage(new AdSize(width, height));
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/LogUtil.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.util.Log;
import androidx.annotation.Size;
public class LogUtil {
private static final String BASE_TAG = "PrebidMobile";
public static final int NONE = -1;
public static final int VERBOSE = android.util.Log.VERBOSE; // 2
public static final int DEBUG = android.util.Log.DEBUG; // 3
public static final int INFO = android.util.Log.INFO; // 4
public static final int WARN = android.util.Log.WARN; // 5
public static final int ERROR = android.util.Log.ERROR; // 6
public static final int ASSERT = android.util.Log.ASSERT; // 7
private static int logLevel;
private LogUtil() {
}
public static void setLogLevel(int level) {
logLevel = level;
}
public static int getLogLevel() {
return logLevel;
}
/**
* Prints a message with VERBOSE priority and default BASE_TAG
*/
public static void verbose(String message) {
verbose(BASE_TAG, message);
}
/**
* Prints a message with DEBUG priority and default BASE_TAG
*/
public static void debug(String message) {
debug(BASE_TAG, message);
}
/**
* Prints a message with INFO priority and default BASE_TAG
*/
public static void info(String message) {
info(BASE_TAG, message);
}
/**
* Prints a message with WARNING priority and default BASE_TAG
*/
public static void warning(String message) {
warning(BASE_TAG, message);
}
/**
* Prints a message with ERROR priority and default BASE_TAG
*/
public static void error(String message) {
error(BASE_TAG, message);
}
/**
* Prints a message with VERBOSE priority.
*/
public static void verbose(@Size(max = 23) String tag, String msg) {
print(VERBOSE, tag, msg);
}
/**
* Prints a message with DEBUG priority.
*/
public static void debug(@Size(max = 23) String tag, String msg) {
print(DEBUG, tag, msg);
}
/**
* Prints a message with INFO priority.
*/
public static void info(@Size(max = 23) String tag, String msg) {
print(INFO, tag, msg);
}
/**
* Prints a message with WARN priority.
*/
public static void warning(@Size(max = 23) String tag, String msg) {
print(WARN, tag, msg);
}
/**
* Prints a message with ERROR priority.
*/
public static void error(@Size(max = 23) String tag, String msg) {
print(ERROR, tag, msg);
}
/**
* Prints a message with ASSERT priority.
*/
public static void wtf(@Size(max = 23) String tag, String msg) {
print(ASSERT, tag, msg);
}
/**
* Prints a message with ERROR priority and exception.
*/
public static void error(final String tag, String message, Throwable throwable) {
if (tag == null || message == null) {
return;
}
if (ERROR >= getLogLevel()) {
Log.e(getTagWithBase(tag), message, throwable);
}
}
/**
* Prints information with set priority. Every tag
*/
private static void print(int messagePriority, String tag, String message) {
if (tag == null || message == null) {
return;
}
if (messagePriority >= getLogLevel()) {
Log.println(messagePriority, getTagWithBase(tag), message);
}
}
/**
* Helper method to add Prebid tag to logging messages.
*/
private static String getTagWithBase(String tag) {
StringBuilder result = new StringBuilder();
String prefix = "Prebid";
if (tag.startsWith(prefix)) {
result.append(tag);
} else {
result.append(prefix).append(tag);
}
if (result.length() > 23) {
return result.substring(0, 22);
} else {
return result.toString();
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeAdUnit.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import org.json.JSONObject;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.NativeAdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import java.util.EnumSet;
import java.util.HashMap;
/**
* For details of the configuration of native imps, please check this documentation:
* https://www.iab.com/wp-content/uploads/2018/03/OpenRTB-Native-Ads-Specification-Final-1.2.pdf
*/
public class NativeAdUnit extends AdUnit {
public static final String BUNDLE_KEY_CACHE_ID = "NativeAdUnitCacheId";
private final NativeAdUnitConfiguration nativeConfiguration;
public NativeAdUnit(@NonNull String configId) {
super(configId, EnumSet.of(AdFormat.NATIVE));
nativeConfiguration = configuration.getNativeConfiguration();
}
@Override
protected BidRequesterListener createBidListener(OnCompleteListener originalListener) {
return new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
bidResponse = response;
HashMap<String, String> keywords = response.getTargeting();
Util.apply(keywords, adObject);
String cacheId = CacheManager.save(response.getWinningBidJson());
Util.saveCacheId(cacheId, adObject);
originalListener.onComplete(ResultCode.SUCCESS, null);
}
@Override
public void onError(AdException exception) {
bidResponse = null;
Util.apply(null, adObject);
originalListener.onComplete(convertToResultCode(exception), null);
}
};
}
public enum CONTEXT_TYPE {
CONTENT_CENTRIC(1),
SOCIAL_CENTRIC(2),
PRODUCT(3),
CUSTOM(500);
private int id;
CONTEXT_TYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
CONTEXT_TYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (CONTEXT_TYPE value : possibleValues) {
if (!value.equals(CONTEXT_TYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
public void setContextType(CONTEXT_TYPE type) {
nativeConfiguration.setContextType(type);
}
public enum CONTEXTSUBTYPE {
GENERAL(10),
ARTICAL(11),
VIDEO(12),
AUDIO(13),
IMAGE(14),
USER_GENERATED(15),
GENERAL_SOCIAL(20),
EMAIL(21),
CHAT_IM(22),
SELLING(30),
APPLICATION_STORE(31),
PRODUCT_REVIEW_SITES(32),
CUSTOM(500);
private int id;
CONTEXTSUBTYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
CONTEXTSUBTYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (CONTEXTSUBTYPE value : possibleValues) {
if (!value.equals(CONTEXTSUBTYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
public void setContextSubType(CONTEXTSUBTYPE type) {
nativeConfiguration.setContextSubtype(type);
}
public enum PLACEMENTTYPE {
CONTENT_FEED(1),
CONTENT_ATOMIC_UNIT(2),
OUTSIDE_CORE_CONTENT(3),
RECOMMENDATION_WIDGET(4),
CUSTOM(500);
private int id;
PLACEMENTTYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
PLACEMENTTYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (PLACEMENTTYPE value : possibleValues) {
if (!value.equals(PLACEMENTTYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
public void setPlacementType(PLACEMENTTYPE placementType) {
nativeConfiguration.setPlacementType(placementType);
}
public void setPlacementCount(int placementCount) {
nativeConfiguration.setPlacementCount(placementCount);
}
public void setSeq(int seq) {
nativeConfiguration.setSeq(seq);
}
public void setAUrlSupport(boolean support) {
nativeConfiguration.setAUrlSupport(support);
}
public void setDUrlSupport(boolean support) {
nativeConfiguration.setDUrlSupport(support);
}
public void setPrivacy(boolean privacy) {
nativeConfiguration.setPrivacy(privacy);
}
public void setExt(Object jsonObject) {
if (jsonObject instanceof JSONObject) {
nativeConfiguration.setExt((JSONObject) jsonObject);
}
}
public void addEventTracker(NativeEventTracker tracker) {
nativeConfiguration.addEventTracker(tracker);
}
public void addAsset(NativeAsset asset) {
nativeConfiguration.addAsset(asset);
}
@VisibleForTesting
public NativeAdUnitConfiguration getNativeConfiguration() {
return nativeConfiguration;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeAsset.java | package org.prebid.mobile;
import org.json.JSONObject;
public abstract class NativeAsset {
enum REQUEST_ASSET {
TITLE,
IMAGE,
DATA
}
private REQUEST_ASSET type;
NativeAsset(REQUEST_ASSET type) {
this.type = type;
}
public REQUEST_ASSET getType() {
return type;
}
public abstract JSONObject getJsonObject();
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeData.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
public class NativeData {
private final int typeNumber;
private final String value;
public NativeData(int typeNumber, @NonNull String value) {
this.typeNumber = typeNumber;
this.value = value;
}
public NativeData(Type type, @NonNull String value) {
if (type == Type.CUSTOM) {
throw new IllegalArgumentException("For CUSTOM type use constructor with typeNumber parameter.");
}
this.typeNumber = Type.getNumberFromType(type);
this.value = value;
}
public int getTypeNumber() {
return typeNumber;
}
@NonNull
public String getValue() {
return value;
}
@NonNull
public Type getType() {
return Type.getFromTypeNumber(typeNumber);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
NativeData that = (NativeData) object;
return typeNumber == that.typeNumber && value.equals(that.value);
}
public enum Type {
SPONSORED_BY,
DESCRIPTION,
CALL_TO_ACTION,
RATING,
CUSTOM;
public static Type getFromTypeNumber(int typeNumber) {
switch (typeNumber) {
case 1:
return SPONSORED_BY;
case 2:
return DESCRIPTION;
case 3:
return RATING;
case 12:
return CALL_TO_ACTION;
default:
return CUSTOM;
}
}
public static int getNumberFromType(Type type) {
switch (type) {
case SPONSORED_BY:
return 1;
case DESCRIPTION:
return 2;
case RATING:
return 3;
case CALL_TO_ACTION:
return 12;
default:
return 0;
}
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeDataAsset.java | package org.prebid.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
public class NativeDataAsset extends NativeAsset {
public NativeDataAsset() {
super(REQUEST_ASSET.DATA);
}
public enum DATA_TYPE {
SPONSORED(1),
DESC(2),
RATING(3),
LIKES(4),
DOWNLOADS(5),
PRICE(6),
SALEPRICE(7),
PHONE(8),
ADDRESS(9),
DESC2(10),
DESPLAYURL(11),
CTATEXT(12),
CUSTOM(500);
private int id;
DATA_TYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
DATA_TYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (DATA_TYPE value : possibleValues) {
if (!value.equals(DATA_TYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
private DATA_TYPE dataType = null;
public DATA_TYPE getDataType() {
return dataType;
}
public void setDataType(DATA_TYPE dataType) {
this.dataType = dataType;
}
private int len = -1;
public int getLen() {
return len;
}
public void setLen(int len) {
this.len = len;
}
private boolean required = false;
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
private Object dataExt = null;
public Object getDataExt() {
return dataExt;
}
public void setDataExt(Object dataExt) {
if (dataExt instanceof JSONObject || dataExt instanceof JSONArray) {
this.dataExt = dataExt;
}
}
private Object assetExt = null;
public Object getAssetExt() {
return assetExt;
}
public void setAssetExt(Object assetExt) {
if (assetExt instanceof JSONArray || assetExt instanceof JSONObject) {
this.assetExt = assetExt;
}
}
@Override
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("required", required ? 1 : 0);
result.putOpt("ext", assetExt);
JSONObject dataObject = new JSONObject();
dataObject.putOpt("type", dataType != null ? dataType.getID() : null);
dataObject.putOpt("len", len);
dataObject.putOpt("ext", dataExt);
result.put("data", dataObject);
} catch (Exception exception) {
LogUtil.error("NativeTitleAsset", "Can't create json object: " + exception.getMessage());
}
return result;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeEventTracker.java | package org.prebid.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class NativeEventTracker {
public enum EVENT_TYPE {
IMPRESSION(1),
VIEWABLE_MRC50(2),
VIEWABLE_MRC100(3),
VIEWABLE_VIDEO50(4),
CUSTOM(500);
private int id;
EVENT_TYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
EVENT_TYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (EVENT_TYPE value : possibleValues) {
if (!value.equals(EVENT_TYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
public enum EVENT_TRACKING_METHOD {
IMAGE(1),
JS(2),
CUSTOM(500);
private int id;
EVENT_TRACKING_METHOD(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
EVENT_TRACKING_METHOD[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (EVENT_TRACKING_METHOD value : possibleValues) {
if (!value.equals(EVENT_TRACKING_METHOD.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
EVENT_TYPE event;
ArrayList<EVENT_TRACKING_METHOD> methods;
Object extObject;
public NativeEventTracker(EVENT_TYPE event, ArrayList<EVENT_TRACKING_METHOD> methods) throws Exception {
this.event = event;
if (methods == null || methods.isEmpty()) {
throw new Exception("Methods are required");
}
this.methods = methods;
}
public void setExt(Object extObject) {
if (extObject instanceof JSONObject || extObject instanceof JSONArray) {
this.extObject = extObject;
}
}
public EVENT_TYPE getEvent() {
return event;
}
public ArrayList<EVENT_TRACKING_METHOD> getMethods() {
return methods;
}
public Object getExtObject() {
return extObject;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeImage.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
public class NativeImage {
private final int typeNumber;
private final String url;
public NativeImage(int typeNumber, @NonNull String url) {
this.typeNumber = typeNumber;
this.url = url;
}
public NativeImage(@NonNull Type type, @NonNull String url) {
if (type == Type.CUSTOM) {
throw new IllegalArgumentException("For CUSTOM type use constructor with typeNumber parameter.");
}
this.typeNumber = Type.getNumberFromType(type);
this.url = url;
}
public int getTypeNumber() {
return typeNumber;
}
@NonNull
public String getUrl() {
return url;
}
@NonNull
public Type getType() {
return Type.getTypeFromNumber(typeNumber);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
NativeImage that = (NativeImage) object;
return typeNumber == that.typeNumber && url.equals(that.url);
}
public enum Type {
ICON,
MAIN_IMAGE,
CUSTOM;
public static Type getTypeFromNumber(int typeNumber) {
switch (typeNumber) {
case 1:
return Type.ICON;
case 3:
return Type.MAIN_IMAGE;
default:
return Type.CUSTOM;
}
}
public static int getNumberFromType(Type type) {
switch (type) {
case ICON:
return 1;
case MAIN_IMAGE:
return 3;
default:
return 0;
}
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeImageAsset.java | package org.prebid.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class NativeImageAsset extends NativeAsset {
@Deprecated
public NativeImageAsset() {
super(REQUEST_ASSET.IMAGE);
}
public NativeImageAsset(int w, int h, int minWidth, int minHeight) {
super(REQUEST_ASSET.IMAGE);
this.w = w;
this.h = h;
wmin = minWidth;
hmin = minHeight;
}
public enum IMAGE_TYPE {
ICON(1),
MAIN(3),
CUSTOM(500);
private int id;
IMAGE_TYPE(final int id) {
this.id = id;
}
public int getID() {
return this.id;
}
public void setID(int id) {
if (this.equals(CUSTOM) && !inExistingValue(id)) {
this.id = id;
}
}
private boolean inExistingValue(int id) {
IMAGE_TYPE[] possibleValues = this.getDeclaringClass().getEnumConstants();
for (IMAGE_TYPE value : possibleValues) {
if (!value.equals(IMAGE_TYPE.CUSTOM) && value.getID() == id) {
return true;
}
}
return false;
}
}
private IMAGE_TYPE type;
public void setImageType(IMAGE_TYPE type) {
this.type = type;
}
public IMAGE_TYPE getImageType() {
return type;
}
private int wmin = -1;
public void setWMin(int wmin) {
this.wmin = wmin;
}
public int getWMin() {
return wmin;
}
private int hmin = -1;
public int getHMin() {
return hmin;
}
public void setHMin(int hmin) {
this.hmin = hmin;
}
private int w = -1;
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
private int h = -1;
public void setH(int h) {
this.h = h;
}
public int getH() {
return h;
}
private ArrayList<String> mimes = new ArrayList<>();
public void addMime(String mime) {
mimes.add(mime);
}
public ArrayList<String> getMimes() {
return mimes;
}
private boolean required = false;
public void setRequired(boolean required) {
this.required = required;
}
public boolean isRequired() {
return required;
}
private Object assetExt = null;
public void setAssetExt(Object assetExt) {
if (assetExt instanceof JSONArray || assetExt instanceof JSONObject) {
this.assetExt = assetExt;
}
}
public Object getAssetExt() {
return assetExt;
}
private Object imageExt = null;
public void setImageExt(Object imageExt) {
if (imageExt instanceof JSONArray || imageExt instanceof JSONObject) {
this.imageExt = imageExt;
}
}
public Object getImageExt() {
return imageExt;
}
@Override
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("required", required ? 1 : 0);
result.putOpt("ext", assetExt);
JSONObject imageObject = new JSONObject();
imageObject.putOpt("type", type != null ? type.getID() : null);
imageObject.put("w", w);
imageObject.put("wmin", wmin);
imageObject.put("h", h);
imageObject.put("hmin", hmin);
imageObject.putOpt("ext", imageExt);
if (!mimes.isEmpty()) {
JSONArray mimesArray = new JSONArray();
for (String mime : mimes) {
mimesArray.put(mime);
}
imageObject.putOpt("mimes", mimesArray);
}
result.put("img", imageObject);
} catch (Exception exception) {
LogUtil.error("NativeImageAsset", "Can't create json object: " + exception.getMessage());
}
return result;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeParameters.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONObject;
import org.prebid.mobile.configuration.NativeAdUnitConfiguration;
import java.util.List;
/**
* For details of the configuration of native parameters, please check this documentation:
* https://www.iab.com/wp-content/uploads/2018/03/OpenRTB-Native-Ads-Specification-Final-1.2.pdf
*/
public class NativeParameters {
private final NativeAdUnitConfiguration nativeConfiguration = new NativeAdUnitConfiguration();
public NativeParameters(
@NonNull List<NativeAsset> assets
) {
for (NativeAsset asset : assets) {
nativeConfiguration.addAsset(asset);
}
}
@Nullable
public NativeAdUnitConfiguration getNativeConfiguration() {
return nativeConfiguration;
}
public void addEventTracker(NativeEventTracker tracker) {
nativeConfiguration.addEventTracker(tracker);
}
public void setContextType(NativeAdUnit.CONTEXT_TYPE type) {
nativeConfiguration.setContextType(type);
}
public void setContextSubType(NativeAdUnit.CONTEXTSUBTYPE type) {
nativeConfiguration.setContextSubtype(type);
}
public void setPlacementType(NativeAdUnit.PLACEMENTTYPE placementType) {
nativeConfiguration.setPlacementType(placementType);
}
public void setPlacementCount(int placementCount) {
nativeConfiguration.setPlacementCount(placementCount);
}
public void setSeq(int seq) {
nativeConfiguration.setSeq(seq);
}
public void setAUrlSupport(boolean support) {
nativeConfiguration.setAUrlSupport(support);
}
public void setDUrlSupport(boolean support) {
nativeConfiguration.setDUrlSupport(support);
}
public void setPrivacy(boolean privacy) {
nativeConfiguration.setPrivacy(privacy);
}
public void setExt(Object jsonObject) {
if (jsonObject instanceof JSONObject) {
nativeConfiguration.setExt((JSONObject) jsonObject);
}
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeTitle.java | package org.prebid.mobile;
import androidx.annotation.NonNull;
public class NativeTitle {
private final String text;
public NativeTitle(@NonNull String text) {
this.text = text;
}
@NonNull
public String getText() {
return text;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
NativeTitle that = (NativeTitle) object;
return text.equals(that.text);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/NativeTitleAsset.java | package org.prebid.mobile;
import org.json.JSONArray;
import org.json.JSONObject;
public class NativeTitleAsset extends NativeAsset {
private int len;
private boolean required;
private Object titleExt;
private Object assetExt;
public NativeTitleAsset() {
super(REQUEST_ASSET.TITLE);
}
public void setLength(int len) {
this.len = len;
}
public int getLen() {
return len;
}
public void setRequired(boolean required) {
this.required = required;
}
public boolean isRequired() {
return required;
}
public void setTitleExt(Object ext) {
if (ext instanceof JSONArray || ext instanceof JSONObject) {
this.titleExt = ext;
}
}
public Object getTitleExt() {
return titleExt;
}
public Object getAssetExt() {
return assetExt;
}
public void setAssetExt(Object assetExt) {
if (assetExt instanceof JSONArray || assetExt instanceof JSONObject) {
this.assetExt = assetExt;
}
}
@Override
public JSONObject getJsonObject() {
JSONObject result = new JSONObject();
try {
result.putOpt("required", required ? 1 : 0);
result.putOpt("ext", assetExt);
JSONObject titleObject = new JSONObject();
titleObject.putOpt("len", len);
titleObject.putOpt("ext", titleExt);
result.put("title", titleObject);
} catch (Exception exception) {
LogUtil.error("NativeTitleAsset", "Can't create json object: " + exception.getMessage());
}
return result;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/OnCompleteListener.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.MainThread;
public interface OnCompleteListener {
/**
* This method will be called when PrebidMobile finishes attaching keywords to your ad object.
* @param resultCode see object class definition for details
*/
@MainThread
void onComplete(ResultCode resultCode, String message);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/OnCompleteListener2.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import java.util.Map;
public interface OnCompleteListener2 {
/**
* This method will be called when PrebidMobile finishes attaching keywords to unmodifiableMap.
* @param resultCode see {@link ResultCode} class definition for details
* @param unmodifiableMap a map of targeting Key/Value pairs
*/
@MainThread
void onComplete(ResultCode resultCode, @Nullable Map<String, String> unmodifiableMap, @Nullable String message);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ParametersMatcher.java | package org.prebid.mobile;
import android.os.Bundle;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
public class ParametersMatcher {
private static final String TAG = "ParametersMatcher";
public static boolean doParametersMatch(
@Nullable String serverParametersJsonString,
@Nullable HashMap<String, String> prebidParameters
) {
HashMap<String, String> serverParameters = jsonStringToHashMap(serverParametersJsonString);
return doParametersMatch(serverParameters, prebidParameters);
}
public static boolean doParametersMatch(
@Nullable Bundle serverParametersBundle,
@Nullable HashMap<String, String> prebidParameters
) {
HashMap<String, String> serverParameters = bundleToHashMap(serverParametersBundle);
return doParametersMatch(serverParameters, prebidParameters);
}
public static boolean doParametersMatch(
@Nullable HashMap<String, String> serverParameters,
@Nullable HashMap<String, String> prebidParameters
) {
if (serverParameters == null || prebidParameters == null) {
return false;
}
try {
for (String serverKey : serverParameters.keySet()) {
if (prebidParameters.containsKey(serverKey)) {
String prebidValue = prebidParameters.get(serverKey);
String serverValue = serverParameters.get(serverKey);
if (prebidValue == null || !prebidValue.equals(serverValue)) {
return false;
}
} else {
return false;
}
}
return true;
} catch (NullPointerException e) {
LogUtil.error(TAG, "Null pointer exception");
}
return false;
}
@Nullable
private static HashMap<String, String> bundleToHashMap(@Nullable Bundle bundle) {
if (bundle == null) {
return null;
}
HashMap<String, String> parameters = new HashMap<>();
if (bundle.size() > 0) {
for (String bundleKey : bundle.keySet()) {
String bundleValue = bundle.getString(bundleKey);
if (bundleValue != null) {
parameters.put(bundleKey, bundleValue);
}
}
return parameters;
}
return null;
}
@Nullable
private static HashMap<String, String> jsonStringToHashMap(@Nullable String jsonString) {
if (jsonString == null || jsonString.trim().length() == 0) {
return null;
}
try {
JSONObject root = new JSONObject(jsonString);
HashMap<String, String> parameters = new HashMap<>();
Iterator<String> keys = root.keys();
while (keys.hasNext()) {
String key = keys.next();
parameters.put(key, root.getString(key));
}
return parameters;
} catch (JSONException e) {
LogUtil.error(TAG, "Can't parse parameters");
return null;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/PrebidMobile.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.api.exceptions.InitError;
import org.prebid.mobile.core.BuildConfig;
import org.prebid.mobile.rendering.listeners.SdkInitializationListener;
import org.prebid.mobile.rendering.mraid.MraidEnv;
import org.prebid.mobile.rendering.sdk.ManagersResolver;
import org.prebid.mobile.rendering.sdk.SdkInitializer;
import org.prebid.mobile.rendering.sdk.deviceData.listeners.SdkInitListener;
import java.util.*;
public class PrebidMobile {
public static boolean isCoppaEnabled = false;
public static boolean useExternalBrowser = false;
/**
* If true, the SDK sends "af=3,5", indicating support for MRAID
*/
public static boolean sendMraidSupportParams = true;
/**
* Minimum refresh interval allowed. 30 seconds
*/
public static final int AUTO_REFRESH_DELAY_MIN = 30_000;
/**
* Maximum refresh interval allowed. 120 seconds
*/
public static final int AUTO_REFRESH_DELAY_MAX = 120_000;
public static final String SCHEME_HTTPS = "https";
public static final String SCHEME_HTTP = "http";
/**
* SDK version
*/
public static final String SDK_VERSION = BuildConfig.VERSION;
/**
* SDK name provided for MRAID_ENV in {@link MraidEnv}
*/
public static final String SDK_NAME = "prebid-mobile-sdk-rendering";
/**
* Currently implemented MRAID version.
*/
public static final String MRAID_VERSION = "3.0";
/**
* Currently implemented Native Ads version.
*/
public static final String NATIVE_VERSION = "1.2";
/**
* Open measurement SDK version
*/
public static final String OMSDK_VERSION = BuildConfig.OMSDK_VERSION;
/**
* Please use {@link PrebidMobile#setLogLevel(LogLevel)}, this field will become private in next releases.
*/
@Deprecated
public static LogLevel logLevel = LogLevel.NONE;
private static boolean pbsDebug = false;
private static boolean shareGeoLocation = false;
private static boolean assignNativeAssetID = false;
/**
* Indicates whether the PBS should cache the bid for the rendering API.
* If the value is true the SDK will make the cache request in order to report
* the impression event respectively to the legacy analytic setup.
*/
private static boolean useCacheForReportingWithRenderingApi = false;
private static int timeoutMillis = 5_000;
private static final String TAG = PrebidMobile.class.getSimpleName();
private static String accountId = "";
private static String storedAuctionResponse = "";
private static boolean isViewabilityV3 = false;
private static Host host = Host.CUSTOM;
private static final Map<String, String> storedBidResponses = new LinkedHashMap<>();
private static List<ExternalUserId> externalUserIds = new ArrayList<>();
private static HashMap<String, String> customHeaders = new HashMap<>();
private PrebidMobile() {}
public static boolean isUseCacheForReportingWithRenderingApi() {
return useCacheForReportingWithRenderingApi;
}
public static void setUseCacheForReportingWithRenderingApi(boolean useCacheForReportingWithRenderingApi) {
PrebidMobile.useCacheForReportingWithRenderingApi = useCacheForReportingWithRenderingApi;
}
public static int getTimeoutMillis() {
return timeoutMillis;
}
public static void setTimeoutMillis(int timeoutMillis) {
PrebidMobile.timeoutMillis = timeoutMillis;
}
public static void setPrebidServerAccountId(String accountId) {
PrebidMobile.accountId = accountId;
}
public static void setIsViewabilityV3(boolean isViewabilityV3) {
PrebidMobile.isViewabilityV3 = isViewabilityV3;
}
public static boolean isViewabilityV3() {
return isViewabilityV3;
}
public static String getPrebidServerAccountId() {
return accountId;
}
public static void setPrebidServerHost(Host host) {
if (host == null) {
LogUtil.error(TAG, "setPrebidServerHost: Can't set null.");
return;
}
PrebidMobile.host = host;
}
public static Host getPrebidServerHost() {
return host;
}
public static void setShareGeoLocation(boolean share) {
PrebidMobile.shareGeoLocation = share;
}
public static boolean isShareGeoLocation() {
return shareGeoLocation;
}
/**
* List containing objects that hold External User Id parameters for the current application user.
*/
public static void setExternalUserIds(List<ExternalUserId> externalUserIds) {
PrebidMobile.externalUserIds = externalUserIds;
}
/**
* Returns the List that hold External UserId parameters for the current application user
*
* @@return externalUserIds as Array.
*/
public static List<ExternalUserId> getExternalUserIds() {
return PrebidMobile.externalUserIds;
}
/**
* HashMap containing a list of custom headers to add to requests
*/
public static void setCustomHeaders(@Nullable HashMap<String, String> customHeaders) {
if (customHeaders != null) {
PrebidMobile.customHeaders = customHeaders;
}
}
/**
* Returns the HashMap containing a list of custom headers to add to requests
*
* @return externalUserIds as Array.
*/
@NonNull
public static HashMap<String, String> getCustomHeaders() {
return PrebidMobile.customHeaders;
}
/**
* Initializes the main SDK classes. Makes request to Prebid server to check its status.
* You have to set host url ({@link PrebidMobile#setPrebidServerHost(Host)}) before calling this method.
*
* @param context any context (must be not null)
* @param listener initialization listener (can be null)
* @see <a href="https://docs.prebid.org/prebid-server/endpoints/pbs-endpoint-status.html">GET /status</a>
*/
public static void initializeSdk(
@Nullable Context context,
@Nullable SdkInitializationListener listener
) {
SdkInitializer.init(context, listener);
}
/**
* Please use {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Deprecated
public static void setApplicationContext(@Nullable Context context) {
SdkInitializer.init(context, null);
}
/**
* Please use {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Deprecated
public static void setApplicationContext(
@Nullable Context context,
@Nullable SdkInitListener listener
) {
SdkInitializer.init(context, new SdkInitializationListener() {
@Override
public void onSdkInit() {
if (listener != null) {
listener.onSDKInit();
}
}
@Override
public void onSdkFailedToInit(InitError error) {
LogUtil.error(TAG, error.getError());
}
});
}
public static Context getApplicationContext() {
return ManagersResolver.getInstance().getContext();
}
public static void setStoredAuctionResponse(@Nullable String storedAuctionResponse) {
PrebidMobile.storedAuctionResponse = storedAuctionResponse;
}
@Nullable
public static String getStoredAuctionResponse() {
return storedAuctionResponse;
}
public static void addStoredBidResponse(
String bidder,
String responseId
) {
storedBidResponses.put(bidder, responseId);
}
public static void clearStoredBidResponses() {
storedBidResponses.clear();
}
@NonNull
public static Map<String, String> getStoredBidResponses() {
return storedBidResponses;
}
public static boolean getPbsDebug() {
return pbsDebug;
}
public static void setPbsDebug(boolean pbsDebug) {
PrebidMobile.pbsDebug = pbsDebug;
}
/**
* @return boolean that states if the ID will be set to the Asset array (in the Native Ad Request)
* This value can be set using the {@link #assignNativeAssetID(boolean)}
*/
public static boolean shouldAssignNativeAssetID() {
return assignNativeAssetID;
}
/**
* For assigning ID to the Assets in the Asset array (in Native Ad Request)
*/
public static void assignNativeAssetID(boolean assignNativeAssetID) {
PrebidMobile.assignNativeAssetID = assignNativeAssetID;
}
/**
* Return 'true' if Prebid Rendering SDK is initialized completely
*/
public static boolean isSdkInitialized() {
return SdkInitializer.isIsSdkInitialized();
}
public static LogLevel getLogLevel() {
return PrebidMobile.logLevel;
}
public static void setLogLevel(LogLevel logLevel) {
PrebidMobile.logLevel = logLevel;
}
/**
* LogLevel for logging control.
* NONE - no sdk logs.
* ERROR - sdk logs with error level only.
* WARN - sdk logs with warn level only.
* DEBUG - sdk logs with debug level only. Noisy level.
*/
public enum LogLevel {
NONE(-1),
DEBUG(3),
WARN(5),
ERROR(6);
private final int value;
LogLevel(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/PrebidNativeAd.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.events.EventsNotifier;
import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils;
import java.util.ArrayList;
import java.util.List;
public class PrebidNativeAd {
private static final String TAG = "PrebidNativeAd";
private boolean impressionIsNotNotified = true;
private final ArrayList<NativeTitle> titles = new ArrayList<>();
private final ArrayList<NativeImage> images = new ArrayList<>();
private final ArrayList<NativeData> dataList = new ArrayList<>();
private String clickUrl;
private ArrayList<String> imp_trackers = new ArrayList<>();
private VisibilityDetector visibilityDetector;
private boolean expired;
private View registeredView;
private PrebidNativeAdEventListener listener;
private ArrayList<ImpressionTracker> impressionTrackers;
private String winEvent;
private String impEvent;
private double price;
private Bid winningBid;
public static PrebidNativeAd create(String cacheId) {
String content = CacheManager.get(cacheId);
if (!TextUtils.isEmpty(content)) {
try {
JSONObject details = new JSONObject(content);
String bidder = getBidder(details);
boolean isS2S = "audienceNetwork".equals(bidder)
|| "msp_google".equals(bidder)
|| "msp_nova".equals(bidder);
String admStr = details.getString("adm");
JSONObject adm = new JSONObject(admStr);
final PrebidNativeAd ad = new PrebidNativeAd();
ad.winningBid = Bid.fromJSONObject(details);
CacheManager.registerCacheExpiryListener(cacheId, new CacheManager.CacheExpiryListener() {
@Override
public void onCacheExpired() {
if (ad.registeredView == null) {
if (ad.listener != null) {
ad.listener.onAdExpired();
}
ad.expired = true;
if (ad.visibilityDetector != null) {
ad.visibilityDetector.destroy();
ad.visibilityDetector = null;
}
ad.impressionTrackers = null;
ad.listener = null;
}
}
});
if (!Double.isNaN(details.optDouble("price"))) {
ad.price = details.optDouble("price");
}
if (!isS2S) { // assets fields only exist for "prebid" native ads(not server-to-server).
JSONArray asset = adm.getJSONArray("assets");
for (int i = 0; i < asset.length(); i++) {
JSONObject adObject = asset.getJSONObject(i);
if (adObject.has("title")) {
JSONObject title = adObject.getJSONObject("title");
if (title.has("text")) {
String titleText = title.getString("text");
if (!titleText.isEmpty()) {
ad.addTitle(new NativeTitle(titleText));
}
} else {
LogUtil.warning(TAG, "Json title object doesn't have text field");
}
}
if (adObject.has("data")) {
JSONObject data = adObject.getJSONObject("data");
if (data.has("value")) {
int type = 0;
if (data.has("type")) {
type = data.optInt("type");
}
String value = data.getString("value");
ad.addData(new NativeData(type, value));
} else {
LogUtil.warning(TAG, "Json data object doesn't have type or value field");
}
}
if (adObject.has("img")) {
JSONObject img = adObject.getJSONObject("img");
if (img.has("url")) {
int type = 0;
if (img.has("type")) {
type = img.optInt("type");
}
String url = img.getString("url");
ad.addImage(new NativeImage(type, url));
} else {
LogUtil.warning(TAG, "Json image object doesn't have url or type field");
}
}
}
if (adm.has("link")) {
JSONObject link = adm.getJSONObject("link");
if (link.has("url")) {
String url = link.getString("url");
if (url.contains("{AUCTION_PRICE}") && details.has("price")) {
url = url.replace("{AUCTION_PRICE}", details.getString("price"));
}
ad.setClickUrl(url);
}
}
if (adm.has("eventtrackers")) {
JSONArray eventtrackers = adm.getJSONArray("eventtrackers");
if (eventtrackers.length() > 0) {
ad.imp_trackers = new ArrayList<>();
for (int count = 0; count < eventtrackers.length(); count++) {
JSONObject eventtracker = eventtrackers.getJSONObject(count);
if (eventtracker.has("url")) {
String impUrl = eventtracker.getString("url");
if (impUrl.contains("{AUCTION_PRICE}") && details.has("price")) {
impUrl = impUrl.replace("{AUCTION_PRICE}", details.getString("price"));
}
ad.imp_trackers.add(impUrl);
}
}
}
}
}
parseEvents(details, ad);
return ad;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
private static void parseEvents(
JSONObject bidJson,
PrebidNativeAd ad
) {
ad.winEvent = EventsNotifier.parseEvent("win", bidJson);
ad.impEvent = EventsNotifier.parseEvent("imp", bidJson);
}
private PrebidNativeAd() {
}
public void addTitle(NativeTitle title) {
titles.add(title);
}
public void addData(NativeData data) {
dataList.add(data);
}
public void addImage(NativeImage image) {
images.add(image);
}
@NonNull
public ArrayList<NativeTitle> getTitles() {
return titles;
}
@NonNull
public ArrayList<NativeImage> getImages() {
return images;
}
@NonNull
public ArrayList<NativeData> getDataList() {
return dataList;
}
private void setClickUrl(String clickUrl) {
this.clickUrl = clickUrl;
}
/**
* @return First title or empty string if it doesn't exist
*/
@NonNull
public String getTitle() {
if (!titles.isEmpty()) {
return titles.get(0).getText();
}
return "";
}
/**
* @return First description data value or empty string if it doesn't exist
*/
@NonNull
public String getDescription() {
for (NativeData data : dataList) {
if (data.getType() == NativeData.Type.DESCRIPTION) {
return data.getValue();
}
}
return "";
}
/**
* @return First icon url or empty string if it doesn't exist
*/
@NonNull
public String getIconUrl() {
for (NativeImage image : images) {
if (image.getType() == NativeImage.Type.ICON) {
return image.getUrl();
}
}
return "";
}
/**
* @return First main image url or empty string if it doesn't exist
*/
@NonNull
public String getImageUrl() {
for (NativeImage image : images) {
if (image.getType() == NativeImage.Type.MAIN_IMAGE) {
return image.getUrl();
}
}
return "";
}
/**
* @return First call to action data value or empty string if it doesn't exist
*/
@NonNull
public String getCallToAction() {
for (NativeData data : dataList) {
if (data.getType() == NativeData.Type.CALL_TO_ACTION) {
return data.getValue();
}
}
return "";
}
/**
* @return First sponsored by data value or empty string if it doesn't exist
*/
@NonNull
public String getSponsoredBy() {
for (NativeData data : dataList) {
if (data.getType() == NativeData.Type.SPONSORED_BY) {
return data.getValue();
}
}
return "";
}
/**
* This API is used to register the view for Ad Events (#onAdClicked(), #onAdImpression, #onAdExpired)
*
* @param view
* @param listener
*/
public boolean registerView(View view, final PrebidNativeAdEventListener listener) {
if (!expired && view != null) {
this.listener = listener;
visibilityDetector = VisibilityDetector.create(view);
if (visibilityDetector == null) {
return false;
}
impressionTrackers = new ArrayList<ImpressionTracker>(imp_trackers.size());
for (String url : imp_trackers) {
ImpressionTracker impressionTracker = ImpressionTracker.create(url, visibilityDetector, view.getContext(), new ImpressionTrackerListener() {
@Override
public void onImpressionTrackerFired() {
if (listener != null) {
listener.onAdImpression();
}
notifyImpressionEvent();
}
});
impressionTrackers.add(impressionTracker);
}
this.registeredView = view;
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleClick(v, listener);
}
});
return true;
}
return false;
}
/**
* This API is used to register a list of views for Ad Events (#onAdClicked(), #onAdImpression, #onAdExpired)
*
* @param container
* @param viewList
* @param listener
*/
public boolean registerViewList(View container, List<View> viewList, final PrebidNativeAdEventListener listener) {
if (container == null || viewList == null || viewList.isEmpty()) {
return false;
}
if (!expired && container != null) {
this.listener = listener;
visibilityDetector = VisibilityDetector.create(container);
if (visibilityDetector == null) {
return false;
}
impressionTrackers = new ArrayList<ImpressionTracker>(imp_trackers.size());
for (String url : imp_trackers) {
ImpressionTracker impressionTracker = ImpressionTracker.create(url, visibilityDetector, container.getContext(), new ImpressionTrackerListener() {
@Override
public void onImpressionTrackerFired() {
if (listener != null) {
listener.onAdImpression();
}
notifyImpressionEvent();
}
});
impressionTrackers.add(impressionTracker);
}
this.registeredView = container;
container.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleClick(v, listener);
}
});
if (viewList != null && viewList.size() > 0) {
for (View views : viewList) {
if (views != null) {
views.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleClick(v, listener);
}
});
}
}
}
return true;
}
return false;
}
protected boolean registerPrebidNativeAdEventListener(PrebidNativeAdEventListener listener) {
this.listener = listener;
return true;
}
private boolean handleClick(View v, PrebidNativeAdEventListener listener) {
if (clickUrl == null || clickUrl.isEmpty()) {
return false;
}
// open browser
if (openNativeIntent(clickUrl, v.getContext())) {
if (listener != null) {
listener.onAdClicked();
}
return true;
}
return false;
}
private boolean openNativeIntent(
String url,
Context context
) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ExternalViewerUtils.startActivity(context, intent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public String getWinEvent() {
return winEvent;
}
public String getImpEvent() {
return impEvent;
}
public double getPrice() {
return price;
}
public Bid getWinningBid() {
return winningBid;
}
private void notifyImpressionEvent() {
if (impressionIsNotNotified) {
impressionIsNotNotified = false;
EventsNotifier.notify(impEvent);
}
}
public void destroy() {
registeredView = null;
listener = null;
if (visibilityDetector != null) {
visibilityDetector.destroy();
visibilityDetector = null;
}
impressionTrackers = null;
}
private static String getBidder(JSONObject bid) {
String bidder = "";
try {
bidder = bid.getJSONObject("ext").getJSONObject("prebid").getJSONObject("meta").getString("adaptercode");
} catch (JSONException ignored){}
return bidder;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/PrebidNativeAdEventListener.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.WorkerThread;
public interface PrebidNativeAdEventListener {
/**
* Callback method for Ad's click event
*/
void onAdClicked();
/**
* Callback method for Ad's click event
*/
@WorkerThread
void onAdImpression();
/**
* Callback method for Ad's click event
*/
void onAdExpired();
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/PrebidNativeAdListener.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
public interface PrebidNativeAdListener {
/**
* A successful Prebid Native ad is returned
*
* @param ad use this instance for displaying
*/
void onPrebidNativeLoaded(PrebidNativeAd ad);
/**
* Prebid Native was not found in the server returned response,
* Please display the ad as regular ways
*/
void onPrebidNativeNotFound();
/**
* Prebid Native ad was returned, however, the bid is not valid for displaying
* Should be treated as on ad load failed
*/
void onPrebidNativeNotValid();
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/ResultCode.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
public enum ResultCode {
/**
* The attaching keywords was successful, which means
* there was demand and the demand was set on the ad object.
*/
SUCCESS,
/**
* The ad request failed due to empty account id
*/
INVALID_ACCOUNT_ID,
/**
* The ad request failed due to empty config id on the ad unit
*/
INVALID_CONFIG_ID,
/**
* The ad request failed because a CUSTOM host used without providing host url
*/
INVALID_HOST_URL,
/**
* For banner view, we don't support multi-size request
*/
INVALID_SIZE,
/**
* Unable to obtain the Application Context, check if you have set it through PrebidMobile.setApplicationContext()
*/
INVALID_CONTEXT,
/**
* Currently, we only support Banner, Interstitial, DFP Banner, Interstitial
*/
INVALID_AD_OBJECT,
/**
* The ad request failed due to a network error.
*/
NETWORK_ERROR,
/**
* The ad request took longer than set time out
*/
TIMEOUT,
/**
* No bids available from demand source
*/
NO_BIDS,
/**
* Prebid Server responded with some error messages
*/
PREBID_SERVER_ERROR,
/**
* Missing assets requirement for native ad unit
*/
INVALID_NATIVE_REQUEST,
/**
* Check @{@link org.prebid.mobile.api.original.PrebidRequest} object that you put into fetchDemand().
*/
INVALID_PREBID_REQUEST_OBJECT
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/RewardedVideoAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.rendering.models.AdPosition;
import java.util.EnumSet;
public class RewardedVideoAdUnit extends VideoBaseAdUnit {
public RewardedVideoAdUnit(@NonNull String configId) {
super(configId, EnumSet.of(AdFormat.VAST));
configuration.setRewarded(true);
configuration.setAdPosition(AdPosition.FULLSCREEN);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/SharedNetworkManager.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import org.prebid.mobile.http.HTTPGet;
import org.prebid.mobile.http.HTTPResponse;
import org.prebid.mobile.http.HttpErrorCode;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class SharedNetworkManager {
private static SharedNetworkManager manager;
public static SharedNetworkManager getInstance(Context context) {
if (manager == null) {
manager = new SharedNetworkManager(context);
}
return manager;
}
private ArrayList<UrlObject> urls = new ArrayList<UrlObject>();
private Timer retryTimer;
private static final int TOTAL_RETRY_TIMES = 3;
private static final int TOTAL_RETRY_WAIT_INTERVAL_MILLISECONDS = 10 * 1000;
private static final String permission = "android.permission.ACCESS_NETWORK_STATE";
private boolean permitted;
private ImpressionTrackerListener impressionTrackerListener;
private SharedNetworkManager(Context context) {
int permissionStatus = context.getPackageManager().checkPermission(
permission,
context.getPackageName()
);
permitted = (permissionStatus == PackageManager.PERMISSION_GRANTED);
}
public boolean isConnected(Context context) {
if (permitted) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
} else {
return true;
}
}
synchronized void addURL(String url, Context context) {
addURL(url, context, null);
}
synchronized void addURL(String url, Context context, ImpressionTrackerListener impressionTrackerListener) {
LogUtil.debug("SharedNetworkManager adding URL for Network Retry");
this.impressionTrackerListener = impressionTrackerListener;
urls.add(new UrlObject(url));
startTimer(context);
}
private void startTimer(Context context) {
if (retryTimer == null) {
// check Network Connectivity after a certain period
final WeakReference<Context> weakContext = new WeakReference<Context>(context);
retryTimer = new Timer();
retryTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Context context = weakContext.get();
if (context != null) {
while (!urls.isEmpty()) {
if (isConnected(context)) {
final UrlObject urlObject = urls.remove(0);
if (urlObject.retryTimes < TOTAL_RETRY_TIMES) {
{
HTTPGet fire = new HTTPGet() {
@Override
protected void onPostExecute(HTTPResponse response) {
if (response == null ||
(!response.getSucceeded() && response.getErrorCode() == HttpErrorCode.CONNECTION_FAILURE)) {
urlObject.retryTimes += 1;
urls.add(urlObject);
} else {
// Nothing more to do just print logs and exit.
if (impressionTrackerListener != null) {
impressionTrackerListener.onImpressionTrackerFired();
}
}
}
@Override
protected String getUrl() {
return urlObject.url;
}
};
fire.execute();
}
}
} else {
break;
}
}
if (urls.isEmpty()) stopTimer();
} else {
stopTimer();
}
}
}, TOTAL_RETRY_WAIT_INTERVAL_MILLISECONDS, TOTAL_RETRY_WAIT_INTERVAL_MILLISECONDS);
}
}
private void stopTimer() {
if (retryTimer != null) {
retryTimer.cancel();
retryTimer = null;
}
}
class UrlObject {
String url;
int retryTimes;
UrlObject(String url) {
this.url = url;
this.retryTimes = 0;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/Signals.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
public class Signals {
static class SingleContainerInt {
final int value;
private SingleContainerInt(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SingleContainerInt that = (SingleContainerInt) o;
return value == that.value;
}
@Override
public int hashCode() {
return value;
}
public int getValue() {
return value;
}
}
/**
* OpenRTB - API Frameworks
* <pre>
| Value | Description |
|-------|-------------|
| 1 | VPAID 1.0 |
| 2 | VPAID 2.0 |
| 3 | MRAID-1 |
| 4 | ORMMA |
| 5 | MRAID-2 |
| 6 | MRAID-3 |
| 7 | OMID-1 |
*</pre>
*/
public static class Api extends SingleContainerInt {
/** VPAID 1.0 */
public static Api VPAID_1 = new Api(1);
/** VPAID 2.0 */
public static Api VPAID_2 = new Api(2);
/** MRAID-1 */
public static Api MRAID_1 = new Api(3);
/** ORMMA */
public static Api ORMMA = new Api(4);
/** MRAID-2 */
public static Api MRAID_2 = new Api(5);
/** MRAID-3 */
public static Api MRAID_3 = new Api(6);
/** OMID-1 */
public static Api OMID_1 = new Api(7);
public Api(int value) {
super(value);
}
}
/**
OpenRTB - Playback Methods
* <pre>
| Value | Description |
|-------|----------------------------------------------------------|
| 1 | Initiates on Page Load with Sound On |
| 2 | Initiates on Page Load with Sound Off by Default |
| 3 | Initiates on Click with Sound On |
| 4 | Initiates on Mouse-Over with Sound On |
| 5 | Initiates on Entering Viewport with Sound On |
| 6 | Initiates on Entering Viewport with Sound Off by Default |
*</pre>
*/
public static class PlaybackMethod extends SingleContainerInt {
/** Initiates on Page Load with Sound On */
public static PlaybackMethod AutoPlaySoundOn = new PlaybackMethod(1);
/** Initiates on Page Load with Sound Off by Default */
public static PlaybackMethod AutoPlaySoundOff = new PlaybackMethod(2);
/** Initiates on Click with Sound On */
public static PlaybackMethod ClickToPlay = new PlaybackMethod(3);
/** Initiates on Mouse-Over with Sound On */
public static PlaybackMethod MouseOver = new PlaybackMethod(4);
/** Initiates on Entering Viewport with Sound On */
public static PlaybackMethod EnterSoundOn = new PlaybackMethod(5);
/** Initiates on Entering Viewport with Sound Off by Default */
public static PlaybackMethod EnterSoundOff = new PlaybackMethod(6);
public PlaybackMethod(int value) {
super(value);
}
}
/**
OpenRTB - Protocols
* <pre>
| Value | Description |
|-------|-------------------|
| 1 | VAST 1.0 |
| 2 | VAST 2.0 |
| 3 | VAST 3.0 |
| 4 | VAST 1.0 Wrapper |
| 5 | VAST 2.0 Wrapper |
| 6 | VAST 3.0 Wrapper |
| 7 | VAST 4.0 |
| 8 | VAST 4.0 Wrapper |
| 9 | DAAST 1.0 |
| 10 | DAAST 1.0 Wrapper |
*</pre>
*/
public static class Protocols extends SingleContainerInt {
/** VAST 1.0 */
public static Protocols VAST_1_0 = new Protocols(1);
/** VAST 2.0 */
public static Protocols VAST_2_0 = new Protocols(2);
/** VAST 3.0 */
public static Protocols VAST_3_0 = new Protocols(3);
/** VAST 1.0 Wrapper */
public static Protocols VAST_1_0_Wrapper = new Protocols(4);
/** VAST 2.0 Wrapper */
public static Protocols VAST_2_0_Wrapper = new Protocols(5);
/** VAST 3.0 Wrapper */
public static Protocols VAST_3_0_Wrapper = new Protocols(6);
/** VAST 4.0 */
public static Protocols VAST_4_0 = new Protocols(7);
/** VAST 4.0 Wrapper */
public static Protocols VAST_4_0_Wrapper = new Protocols(8);
/** DAAST 1.0 */
public static Protocols DAAST_1_0 = new Protocols(9);
/** DAAST 1.0 Wrapper */
public static Protocols DAAST_1_0_WRAPPER = new Protocols(10);
public Protocols(int value) {
super(value);
}
}
/**
OpenRTB - Start Delay
* <pre>
| Value | Description |
|-------|--------------------------------------------------|
| > 0 | Mid-Roll (value indicates start delay in second) |
| 0 | Pre-Roll |
| -1 | Generic Mid-Roll |
| -2 | Generic Post-Roll |
*</pre>
*/
public static class StartDelay extends SingleContainerInt {
/** Pre-Roll */
public static StartDelay PreRoll = new StartDelay(0);
/** Generic Mid-Roll */
public static StartDelay GenericMidRoll = new StartDelay(-1);
/** Generic Post-Roll */
public static StartDelay GenericPostRoll = new StartDelay(-2);
public StartDelay(int value) {
super(value);
}
}
/**
OpenRTB - Video Placement Types
* <pre>
| Value | Description |
|-------|------------------------------|
| 1 | In-Stream |
| 2 | In-Banner |
| 3 | In-Article |
| 4 | In-Feed |
| 5 | Interstitial/Slider/Floating |
*</pre>
*/
public static class Placement extends SingleContainerInt {
/** In-Stream */
public static Placement InStream = new Placement(1);
/** In-Banner */
public static Placement InBanner = new Placement(2);
/** In-Article */
public static Placement InArticle = new Placement(3);
/** In-Feed */
public static Placement InFeed = new Placement(4);
/** Interstitial */
public static Placement Interstitial = new Placement(5);
/** Slider */
public static Placement Slider = new Placement(5);
/** Floating */
public static Placement Floating = new Placement(5);
public Placement(int value) {
super(value);
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/StorageUtils.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Class for external user ids management.
*/
public final class StorageUtils {
private static final String TAG = StorageUtils.class.getSimpleName();
static final String PB_ExternalUserIdsKey = "PB_ExternalUserIdsKey";
static final String PB_UserAgentKey = "PB_UserAgentKey";
private StorageUtils() {}
public static void storeUserAgent(String userAgent, Context context) {
if (userAgent == null) {
return;
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(StorageUtils.PB_UserAgentKey, userAgent);
editor.apply();
}
public static String fetchUserAgent(Context context) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
return pref.getString(StorageUtils.PB_UserAgentKey, null);
}
static void storeExternalUserId(ExternalUserId externalUserId) {
// Remove the existing ExternalUserId with same source.
removeStoredExternalUserId(externalUserId.getSource());
// Storing the ExternalUserId
SharedPreferences pref = getSharedPreferences();
if (pref == null) return;
String externalUserIdString = pref.getString(PB_ExternalUserIdsKey, null);
List<ExternalUserId> externalUidListFromJson;
if (!TextUtils.isEmpty(externalUserIdString)) {
externalUidListFromJson = ExternalUserId.getExternalUidListFromJson(externalUserIdString);
} else {
externalUidListFromJson = new ArrayList<>();
}
externalUidListFromJson.add(externalUserId);
SharedPreferences.Editor editor = pref.edit();
if (externalUserId != null) {
editor.putString(StorageUtils.PB_ExternalUserIdsKey, externalUidListFromJson.toString());
}
editor.apply();
}
static List<ExternalUserId> fetchStoredExternalUserIds() {
SharedPreferences pref = getSharedPreferences();
if (pref == null) return null;
String externalUserIds = pref.getString(StorageUtils.PB_ExternalUserIdsKey, null);
if (externalUserIds != null) {
return ExternalUserId.getExternalUidListFromJson(externalUserIds);
}
return null;
}
static ExternalUserId fetchStoredExternalUserId(String source) {
SharedPreferences pref = getSharedPreferences();
if (pref == null) return null;
String externalUserIds = pref.getString(StorageUtils.PB_ExternalUserIdsKey, null);
if (!TextUtils.isEmpty(externalUserIds)) {
List<ExternalUserId> externalUidListFromJson = ExternalUserId.getExternalUidListFromJson(externalUserIds);
for (ExternalUserId externalUserId : externalUidListFromJson) {
if (externalUserId.getSource().equals(source)) {
return externalUserId;
}
}
}
return null;
}
static void removeStoredExternalUserId(String source) {
SharedPreferences pref = getSharedPreferences();
if (pref == null) return;
String externalUserIds = pref.getString(StorageUtils.PB_ExternalUserIdsKey, null);
if (!TextUtils.isEmpty(externalUserIds)) {
List<ExternalUserId> externalUidListFromJson = ExternalUserId.getExternalUidListFromJson(externalUserIds);
ExternalUserId toBeRemoved = null;
for (ExternalUserId externalUserId : externalUidListFromJson) {
if (externalUserId.getSource().equals(source)) {
toBeRemoved = externalUserId;
break;
}
}
if (toBeRemoved != null) {
externalUidListFromJson.remove(toBeRemoved);
if (externalUidListFromJson.isEmpty()) {
clearStoredExternalUserIds();
} else {
SharedPreferences.Editor editor = pref.edit();
editor.putString(StorageUtils.PB_ExternalUserIdsKey, externalUidListFromJson.toString());
editor.apply();
}
}
}
}
static void clearStoredExternalUserIds() {
if (fetchStoredExternalUserIds() != null) {
SharedPreferences pref = getSharedPreferences();
if (pref == null) return;
SharedPreferences.Editor editor = pref.edit();
editor.remove(StorageUtils.PB_ExternalUserIdsKey);
editor.apply();
}
}
@Nullable
private static SharedPreferences getSharedPreferences() {
Context context = PrebidMobile.getApplicationContext();
if (context == null) {
LogUtil.error(TAG, "You can't manage external user ids before calling PrebidMobile.initializeSdk().");
return null;
}
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/TargetingParams.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.content.Context;
import android.text.TextUtils;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.prebid.mobile.rendering.listeners.SdkInitializationListener;
import org.prebid.mobile.rendering.models.openrtb.bidRequests.Ext;
import org.prebid.mobile.rendering.sdk.UserConsentUtils;
import java.util.*;
/**
* TargetingParams class sets the Targeting parameters like yob, gender, location
* and other custom parameters for the adUnits to be made available in the auction.
*/
public class TargetingParams {
public static final String BIDDER_NAME_APP_NEXUS = "appnexus";
public static final String BIDDER_NAME_RUBICON_PROJECT = "rubicon";
private static final String TAG = "TargetingParams";
private static int yearOfBirth = 0;
private static Integer userAge = null;
private static GENDER gender = GENDER.UNKNOWN;
private static String userId;
private static String publisherName;
private static String buyerUserId;
private static String domain = "";
private static String storeUrl = "";
private static String bundleName = null;
private static String omidPartnerName;
private static String omidPartnerVersion;
private static String userCustomData;
private static Pair<Float, Float> userLatLon;
private static Ext userExt;
private static JSONArray extendedUserIds;
private static final Map<String, Set<String>> userDataMap = new HashMap<>();
private static final Set<String> accessControlList = new HashSet<>();
private static final Set<String> userKeywordsSet = new HashSet<>();
private static final Map<String, Set<String>> contextDataDictionary = new HashMap<>();
private static final Set<String> contextKeywordsSet = new HashSet<>();
private TargetingParams() {
}
/* -------------------- User data -------------------- */
public static void setUserAge(@Nullable Integer age) {
if (age == null) {
yearOfBirth = 0;
userAge = null;
return;
}
if (age <= 0 || age > 120) {
LogUtil.error(TAG, "Can't set age, it must be in range from 0 to 120");
return;
}
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int yearOfBirth = currentYear - age;
TargetingParams.userAge = age;
TargetingParams.yearOfBirth = yearOfBirth;
}
@Nullable
public static Integer getUserAge() {
return userAge;
}
/**
* Get the year of birth for targeting
*
* @return yob
*/
public static int getYearOfBirth() {
return yearOfBirth;
}
/**
* Set the year of birth and user age for targeting
*
* @param yob yob of the user
*/
public static void setYearOfBirth(int yob) throws Exception {
if (yob == 0) {
TargetingParams.yearOfBirth = 0;
TargetingParams.userAge = null;
return;
}
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
if (yob >= 1900 && yob < currentYear) {
TargetingParams.yearOfBirth = yob;
TargetingParams.userAge = currentYear - yearOfBirth;
} else {
throw new Exception("Year of birth must be between 1900 and " + Calendar.getInstance().get(Calendar.YEAR));
}
}
public enum GENDER {
FEMALE,
MALE,
UNKNOWN;
public String getKey() {
switch (this) {
case MALE:
return "M";
case FEMALE:
return "F";
default:
return "O";
}
}
public static GENDER genderByKey(String key) {
switch (key) {
case "M":
return MALE;
case "F":
return FEMALE;
default:
return UNKNOWN;
}
}
}
/**
* Get the current user's gender, if it's available. The default value is UNKNOWN.
*
* @return The user's gender.
*/
@NonNull
public static GENDER getGender() {
return gender;
}
/**
* Set the user's gender. This should be set if the user's gender is known, as it
* can help make buying the ad space more attractive to advertisers. The default
* value is UNKNOWN.
*
* @param gender The user's gender.
*/
public static void setGender(@Nullable GENDER gender) {
if (gender != null) {
TargetingParams.gender = gender;
}
}
/**
* Sets user latitude and longitude
*
* @param latitude User latitude
* @param longitude User longitude
*/
public static void setUserLatLng(
Float latitude,
Float longitude
) {
if (latitude == null || longitude == null) {
userLatLon = null;
return;
}
userLatLon = new Pair<>(latitude, longitude);
}
public static Pair<Float, Float> getUserLatLng() {
return userLatLon;
}
/**
* This method obtains the user data keyword & value for global user targeting
* if the key already exists the value will be appended to the list. No duplicates will be added
*/
public static void addUserData(
String key,
String value
) {
Util.addValue(userDataMap, key, value);
}
/**
* This method obtains the user data keyword & values set for global user targeting
* the values if the key already exist will be replaced with the new set of values
*/
public static void updateUserData(
String key,
Set<String> value
) {
userDataMap.put(key, value);
}
/**
* This method allows to remove specific user data keyword & value set from global user targeting
*/
public static void removeUserData(String key) {
userDataMap.remove(key);
}
/**
* This method allows to remove all user data set from global user targeting
*/
public static void clearUserData() {
userDataMap.clear();
}
public static Map<String, Set<String>> getUserDataDictionary() {
return userDataMap;
}
/**
* This method obtains the user keyword for global user targeting
* Inserts the given element in the set if it is not already present.
*/
public static void addUserKeyword(String keyword) {
userKeywordsSet.add(keyword);
}
/**
* This method obtains the user keyword set for global user targeting
* Adds the elements of the given set to the set.
*/
public static void addUserKeywords(Set<String> keywords) {
userKeywordsSet.addAll(keywords);
}
/**
* This method allows to remove specific user keyword from global user targeting
*/
public static void removeUserKeyword(String keyword) {
userKeywordsSet.remove(keyword);
}
/**
* This method allows to remove all keywords from the set of global user targeting
*/
public static void clearUserKeywords() {
userKeywordsSet.clear();
}
public static String getUserKeywords() {
String result = TextUtils.join(",", userKeywordsSet);
if (result.isEmpty()) return null;
return result;
}
public static Set<String> getUserKeywordsSet() {
return userKeywordsSet;
}
/**
* Optional feature to pass bidder data that was set in the
* exchange’s cookie. The string must be in base85 cookie safe
* characters and be in any format. Proper JSON encoding must
* be used to include “escaped” quotation marks.
*
* @param data Custom data to be passed
*/
public static void setUserCustomData(@Nullable String data) {
userCustomData = data;
}
@Nullable
public static String getUserCustomData() {
return userCustomData;
}
/* -------------------- Ids -------------------- */
/**
* Set the user identifier.
*
* @param userId the new user identifier
*/
public static void setUserId(String userId) {
TargetingParams.userId = userId;
}
public static String getUserId() {
return TargetingParams.userId;
}
/**
* Sets buyerId
*
* @param buyerId Buyer-specific ID for the user as mapped by the exchange for
* the buyer. At least one of buyeruid or id is recommended.
*/
public static void setBuyerId(@Nullable String buyerId) {
buyerUserId = buyerId;
}
@Nullable
public static String getBuyerId() {
return buyerUserId;
}
/**
* Use this API for storing the externalUserId in the SharedPreference.
* Prebid server provide them participating server-side bid adapters.
*
* @param externalUserId the externalUserId instance to be stored in the SharedPreference
*/
public static void storeExternalUserId(ExternalUserId externalUserId) {
if (externalUserId != null) {
StorageUtils.storeExternalUserId(externalUserId);
} else {
LogUtil.error("Targeting", "External User ID can't be set as null");
}
}
/**
* Returns the stored (in the SharedPreference) ExternalUserId instance for a given source
*/
public static ExternalUserId fetchStoredExternalUserId(@NonNull String source) {
if (!TextUtils.isEmpty(source)) {
return StorageUtils.fetchStoredExternalUserId(source);
}
return null;
}
/**
* Returns the stored (in the SharedPreferences) External User Id list
*/
public static List<ExternalUserId> fetchStoredExternalUserIds() {
return StorageUtils.fetchStoredExternalUserIds();
}
/**
* Removes the stored (in the SharedPreference) ExternalUserId instance for a given source
*/
public static void removeStoredExternalUserId(@NonNull String source) {
if (!TextUtils.isEmpty(source)) {
StorageUtils.removeStoredExternalUserId(source);
}
}
/**
* Clear the Stored ExternalUserId list from the SharedPreference
*/
public static void clearStoredExternalUserIds() {
StorageUtils.clearStoredExternalUserIds();
}
/* -------------------- Context and application data -------------------- */
/**
* Sets publisher name
*
* @param publisherName Publisher name
*/
public static void setPublisherName(String publisherName) {
TargetingParams.publisherName = publisherName;
}
public static String getPublisherName() {
return TargetingParams.publisherName;
}
/**
* Set the domain of your app for targeting purpose
*
* @param domain domain of your app
*/
public static synchronized void setDomain(String domain) {
TargetingParams.domain = domain;
}
/**
* Get the domain of your app
*
* @return domain of your app
*/
public static synchronized String getDomain() {
return domain;
}
/**
* Set the store url of your app
*
* @param storeUrl store url
*/
public static synchronized void setStoreUrl(String storeUrl) {
TargetingParams.storeUrl = storeUrl;
}
/**
* Get the store url of your app
*
* @return store url
*/
public static synchronized String getStoreUrl() {
return storeUrl;
}
/**
* Get the platform-specific identifier, should be bundle/package name
*/
public static synchronized String getBundleName() {
if (TextUtils.isEmpty(bundleName)) {
Context context = PrebidMobile.getApplicationContext();
if (context != null) {
return context.getPackageName();
}
}
return bundleName;
}
/**
* Set the platform-specific identifier for targeting purpose
* Should be bundle/package name
*/
public static synchronized void setBundleName(String bundleName) {
TargetingParams.bundleName = bundleName;
}
/**
* This method obtains the context data keyword & value context for global context targeting
* if the key already exists the value will be appended to the list. No duplicates will be added
* (app.ext.data)
*/
public static void addContextData(
String key,
String value
) {
Util.addValue(contextDataDictionary, key, value);
}
/**
* This method obtains the context data keyword & values set for global context targeting.
* the values if the key already exist will be replaced with the new set of values
*/
public static void updateContextData(
String key,
Set<String> value
) {
contextDataDictionary.put(key, value);
}
/**
* This method allows to remove specific context data keyword & values set from global context targeting
*/
public static void removeContextData(String key) {
contextDataDictionary.remove(key);
}
/**
* This method allows to remove all context data set from global context targeting
*/
public static void clearContextData() {
contextDataDictionary.clear();
}
public static Map<String, Set<String>> getContextDataDictionary() {
return contextDataDictionary;
}
/**
* This method obtains the context keyword for adunit context targeting
* Inserts the given element in the set if it is not already present.
* (imp[].ext.context.keywords)
*/
public static void addContextKeyword(String keyword) {
contextKeywordsSet.add(keyword);
}
/**
* This method obtains the context keyword set for adunit context targeting
* Adds the elements of the given set to the set.
*/
public static void addContextKeywords(Set<String> keywords) {
contextKeywordsSet.addAll(keywords);
}
/**
* This method allows to remove specific context keyword from adunit context targeting
*/
public static void removeContextKeyword(String keyword) {
contextKeywordsSet.remove(keyword);
}
/**
* This method allows to remove all keywords from the set of adunit context targeting
*/
public static void clearContextKeywords() {
contextKeywordsSet.clear();
}
public static Set<String> getContextKeywordsSet() {
return contextKeywordsSet;
}
/* -------------------- Publishers -------------------- */
/**
* This method obtains a bidder name allowed to receive global targeting
* (ext.prebid.data)
*/
public static void addBidderToAccessControlList(String bidderName) {
accessControlList.add(bidderName);
}
/**
* This method allows to remove specific bidder name
*/
public static void removeBidderFromAccessControlList(String bidderName) {
accessControlList.remove(bidderName);
}
/**
* This method allows to remove all the bidder name set
*/
public static void clearAccessControlList() {
accessControlList.clear();
}
public static Set<String> getAccessControlList() {
return accessControlList;
}
/**
* OMID signaling
*/
@Nullable
public static String getOmidPartnerName() {
return omidPartnerName;
}
public static void setOmidPartnerName(@Nullable String omidPartnerName) {
TargetingParams.omidPartnerName = omidPartnerName;
}
@Nullable
public static String getOmidPartnerVersion() {
return omidPartnerVersion;
}
public static void setOmidPartnerVersion(@Nullable String omidPartnerVersion) {
TargetingParams.omidPartnerVersion = omidPartnerVersion;
}
/* -------------------- Consents -------------------- */
/**
* Sets subject to COPPA. Null to set undefined. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
public static void setSubjectToCOPPA(@Nullable Boolean value) {
UserConsentUtils.tryToSetSubjectToCoppa(value);
}
/**
* Gets subject to COPPA. Null is undefined. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static Boolean isSubjectToCOPPA() {
return UserConsentUtils.tryToGetSubjectToCoppa();
}
/**
* Sets subject to GDPR for Prebid. It uses custom key "Prebid_GDPR", not IAB. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
public static void setSubjectToGDPR(@Nullable Boolean value) {
UserConsentUtils.tryToSetPrebidSubjectToGdpr(value);
}
/**
* Gets any given subject to GDPR in that order. <br>
* 1) Prebid subject to GDPR custom value, if present. <br>
* 2) IAB subject to GDPR TCF 2.0, if CMP SDK id value bigger
* or equals 0 and value present. <br>
* 3) IAB subject to GDPR TCF 1.0, if present. <br>
* Otherwise, null. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static Boolean isSubjectToGDPR() {
return UserConsentUtils.tryToGetAnySubjectToGdpr();
}
/**
* Sets GDPR consent for Prebid. It uses custom key "Prebid_GDPR_consent_strings", not IAB. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
public static void setGDPRConsentString(@Nullable String consent) {
UserConsentUtils.tryToSetPrebidGdprConsent(consent);
}
/**
* Gets any given GDPR consent in that order. <br>
* 1) Prebid GDPR consent custom value, if present. <br>
* 2) IAB GDPR consent TCF 2.0, if CMP SDK id value bigger
* or equals 0 and value present. <br>
* 3) IAB GDPR consent TCF 1.0, if present. <br>
* Otherwise, null. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static String getGDPRConsentString() {
return UserConsentUtils.tryToGetAnyGdprConsent();
}
/**
* Sets Prebid custom GDPR purpose consent (device access consent). <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
public static void setPurposeConsents(@Nullable String purposeConsents) {
UserConsentUtils.tryToSetPrebidGdprPurposeConsents(purposeConsents);
}
/**
* Gets any given purpose consent for set index in that order. <br>
* 1) Prebid GDPR purpose consent custom value, if present. <br>
* 2) IAB GDPR TCF 2.0 purpose consent. <br>
* Returns null if purpose consent isn't set or index is out of bounds. <br><br>
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static Boolean getPurposeConsent(int index) {
return UserConsentUtils.tryToGetAnyGdprPurposeConsent(index);
}
/**
* Gets any given purpose consent for set index in that order. <br>
* 1) Prebid GDPR purpose consent custom value, if present. <br>
* 2) IAB GDPR TCF 2.0 purpose consent. <br>
* Otherwise, null.
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static String getPurposeConsents() {
return UserConsentUtils.tryToGetAnyGdprPurposeConsents();
}
/**
* Gets the device access consent set by the publisher.<br><br>
* If custom Prebid subject and purpose consent set, gets device access from them.
* Otherwise from IAB standard.
* <p>
* Must be called only after {@link PrebidMobile#initializeSdk(Context, SdkInitializationListener)}.
*/
@Nullable
public static Boolean getDeviceAccessConsent() {
return UserConsentUtils.tryToGetAnyDeviceAccessConsent();
}
/* -------------------- Ext -------------------- */
/**
* Sets user Ext
*
* @param ext Placeholder for exchange-specific extensions to OpenRTB.
*/
public static void setUserExt(Ext ext) {
userExt = ext;
}
public static Ext getUserExt() {
return userExt;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/Util.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.os.Bundle;
import android.text.TextUtils;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.util.*;
public class Util {
static final String AD_MANAGER_REQUEST_CLASS = "com.google.android.gms.ads.doubleclick.PublisherAdRequest";
static final String AD_MANAGER_REQUEST_CLASS_V20 = "com.google.android.gms.ads.admanager.AdManagerAdRequest";
static final String AD_MANAGER_REQUEST_BUILDER_CLASS = "com.google.android.gms.ads.doubleclick.PublisherAdRequest$Builder";
static final String AD_MANAGER_REQUEST_BUILDER_CLASS_V20 = "com.google.android.gms.ads.admanager.AdManagerAdRequest$Builder";
static final String APPLOVIN_MAX_NATIVE_AD_LOADER = "com.applovin.mediation.nativeAds.MaxNativeAdLoader";
static final String ANDROID_OS_BUNDLE = "android.os.Bundle";
public static final String APPLOVIN_MAX_RESPONSE_ID_KEY = "PrebidMaxMediationAdapterExtraResponseId";
public static final String APPLOVIN_MAX_KEYWORDS_KEY = "PrebidMaxMediationAdapterExtraKeywordsId";
public static final int HTTP_CONNECTION_TIMEOUT = 15000;
public static final int HTTP_SOCKET_TIMEOUT = 20000;
public static final int NATIVE_AD_VISIBLE_PERIOD_MILLIS = 1000;
private static final Random RANDOM = new Random();
private static final HashSet<String> reservedKeys;
static {
reservedKeys = new HashSet<>();
}
private Util() {
}
public interface ResizeInBannerNativeListener {
void onResizePrebidAdSuccessful();
void onPrebidAdNotFound();
}
@Nullable
static JSONObject getObjectWithoutEmptyValues(@NonNull JSONObject jsonObject) {
JSONObject result = null;
try {
JSONObject clone = new JSONObject(jsonObject.toString());
removeEntryWithoutValue(clone);
if (clone.length() > 0) {
result = clone;
}
} catch (JSONException e) {
LogUtil.error("message:" + e.getMessage());
}
return result;
}
private static void removeEntryWithoutValue(@NonNull JSONObject map) throws JSONException {
Iterator<String> iterator = map.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = map.opt(key);
if (value != null) {
if (value instanceof JSONObject) {
JSONObject mapValue = (JSONObject) value;
removeEntryWithoutValue(mapValue);
if (mapValue.length() == 0) {
iterator.remove();
}
} else if (value instanceof JSONArray) {
JSONArray arrayValue = (JSONArray) value;
arrayValue = removeEntryWithoutValue(arrayValue);
map.put(key, arrayValue);
if (arrayValue.length() == 0) {
iterator.remove();
}
} else if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.length() == 0) {
iterator.remove();
}
}
}
}
}
@CheckResult
private static JSONArray removeEntryWithoutValue(@NonNull JSONArray array) throws JSONException {
for (int i = 0; i < array.length(); i++) {
Object value = array.opt(i);
if (value != null) {
if (value instanceof JSONObject) {
JSONObject mapValue = (JSONObject) value;
removeEntryWithoutValue(mapValue);
if (mapValue.length() == 0) {
array = getJsonArrayWithoutEntryByIndex(array, i);
}
} else if (value instanceof JSONArray) {
JSONArray arrayValue = (JSONArray) value;
arrayValue = removeEntryWithoutValue(arrayValue);
array.put(i, arrayValue);
if (arrayValue.length() == 0) {
array = getJsonArrayWithoutEntryByIndex(array, i);
}
} else if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.length() == 0) {
array = getJsonArrayWithoutEntryByIndex(array, i);
}
}
}
}
return array;
}
@CheckResult
private static JSONArray getJsonArrayWithoutEntryByIndex(JSONArray jsonArray, int pos) throws JSONException {
JSONArray result = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
if (i != pos) {
result.put(jsonArray.get(i));
}
}
return result;
}
static Class getClassFromString(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
}
return null;
}
static Object callMethodOnObject(
Object object,
String methodName,
Object... params
) {
try {
int len = params.length;
Class<?>[] classes = new Class[len];
for (int i = 0; i < len; i++) {
classes[i] = params[i].getClass();
}
Method method = object.getClass().getMethod(methodName, classes);
return method.invoke(object, params);
} catch (Exception exception) {
LogUtil.error("Util", "Can't call method: " + methodName + "() on object " + object.getClass());
}
return null;
}
/**
* Creates a random lowercase string whose length is the number
* of characters specified.
* <p>
* Characters will be chosen from the set of Latin alphabetic
* characters (a-z).
*
* @param count the length of random string to create
* @return the random string
*/
static String randomLowercaseAlphabetic(int count) {
return randomLowercaseAlphabetic(count, RANDOM);
}
// Code inspiration from apache commons RandomStringUtils
static String randomLowercaseAlphabetic(int count, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Invalid count value: " + count + " is less than 0.");
}
int start = 'a';
int end = 'z' + 1;
StringBuilder sb = new StringBuilder(count);
int gap = end - start;
while (count-- != 0) {
int codePoint = random.nextInt(gap) + start;
sb.appendCodePoint(codePoint);
}
return sb.toString();
}
/**
* Escapes the string using EcmaScript String rules, dealing correctly with
* quotes and control-chars (tab, backslash, cr, ff, etc.).
* <p>
* <p>Example:</p>
* <pre>
* input string: He didn't say, "Stop!"
* output string: He didn\'t say, \"Stop!\"
* </pre>
* <p>
* NOTE: Code inspiration from apache commons StringEscapeUtils and android
* JSONStringer.
*
* @param str String to escape values in, may be null
* @return String with escaped values, {@code null} if null string input
*/
static String escapeEcmaScript(String str) {
if (str == null) return null;
StringBuilder sb = new StringBuilder(str.length() + 50); // optimistic initial size
int pos = 0;
int len = str.length();
while (pos < len) {
char c = str.charAt(pos);
switch (c) {
case '\'':
case '"':
case '\\':
case '/':
sb.append('\\').append(c);
break;
case '\t':
sb.append("\\t");
break;
case '\b':
sb.append("\\b");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\f':
sb.append("\\f");
break;
default:
int cp = Character.codePointAt(str, pos);
if (cp < 32 || cp > 0x7f) {
if (cp > 0xffff) {
char[] surrogatePair = Character.toChars(cp);
sb.append("\\u");
sb.append(Integer.toHexString(surrogatePair[0]));
sb.append("\\u");
sb.append(Integer.toHexString(surrogatePair[1]));
} else {
sb.append(String.format("\\u%04x", cp));
}
pos += Character.charCount(cp) - 1;
} else {
sb.append(c);
}
break;
}
pos++;
}
return sb.toString();
}
static boolean supportedAdObject(Object adObj) {
if (adObj == null) return false;
if (adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS)
|| adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS_V20)
|| adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_BUILDER_CLASS)
|| adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_BUILDER_CLASS_V20)
|| adObj.getClass() == getClassFromString(ANDROID_OS_BUNDLE)
|| adObj.getClass() == getClassFromString(APPLOVIN_MAX_NATIVE_AD_LOADER)
|| adObj.getClass() == HashMap.class)
return true;
return false;
}
public static void apply(HashMap<String, String> bids, Object adObj) {
if (adObj == null) return;
if (adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS) || adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS_V20)) {
handleAdManagerCustomTargeting(bids, adObj);
} else if (adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_BUILDER_CLASS) || adObj.getClass() == getClassFromString(AD_MANAGER_REQUEST_BUILDER_CLASS_V20)) {
handleAdManagerBuilderCustomTargeting(bids, adObj);
} else if (adObj.getClass() == getClassFromString(ANDROID_OS_BUNDLE)) {
handleAndroidBundleCustomTargeting(bids, adObj);
} else if (adObj.getClass() == getClassFromString(APPLOVIN_MAX_NATIVE_AD_LOADER)) {
handleApplovinMaxCustomTargeting(adObj, bids);
} else if (adObj.getClass() == HashMap.class) {
if (bids != null && !bids.isEmpty()) {
HashMap map = ((HashMap) adObj);
map.clear();
map.putAll(bids);
}
}
}
public static void saveCacheId(
@Nullable String cacheId,
Object adObject
) {
if (adObject == null) return;
if (adObject.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS) || adObject.getClass() == getClassFromString(AD_MANAGER_REQUEST_CLASS_V20)) {
setCacheIdToGamManager(cacheId, adObject);
} else if (adObject.getClass() == getClassFromString(ANDROID_OS_BUNDLE)) {
Bundle adBundle = (Bundle) adObject;
adBundle.putString(NativeAdUnit.BUNDLE_KEY_CACHE_ID, cacheId);
} else if (adObject.getClass() == getClassFromString(APPLOVIN_MAX_NATIVE_AD_LOADER)) {
setApplovinMaxLocalParameters(adObject, cacheId);
}
}
private static void setCacheIdToGamManager(
String cacheId,
Object object
) {
if (cacheId == null) {
return;
}
try {
Bundle bundle = (Bundle) Util.callMethodOnObject(object, "getCustomTargeting");
if (bundle != null) {
String key = "hb_cache_id_local";
bundle.putString(key, cacheId);
addReservedKeys(key);
}
} catch (Exception ignored) {}
}
private static void setApplovinMaxLocalParameters(
Object adObject,
String cacheId
) {
setLocalParamsToMax(adObject, APPLOVIN_MAX_RESPONSE_ID_KEY, cacheId);
}
private static void handleApplovinMaxCustomTargeting(
Object adObject,
HashMap<String, String> bids
) {
setLocalParamsToMax(adObject, APPLOVIN_MAX_KEYWORDS_KEY, bids);
}
private static void setLocalParamsToMax(
Object adObject,
String key,
Object value
) {
String methodName = "setLocalExtraParameter";
try {
Class<?>[] classes = new Class[2];
classes[0] = String.class;
classes[1] = Object.class;
Method method = adObject.getClass().getMethod(methodName, classes);
method.invoke(adObject, key, value);
} catch (Exception exception) {
LogUtil.error("Util", "Can't call method: " + methodName + "() on object " + adObject.getClass());
}
}
static void handleAndroidBundleCustomTargeting(
@Nullable HashMap<String, String> bids,
Object adObject
) {
Bundle adBundle = (Bundle) adObject;
if (bids != null) {
for (Map.Entry<String, String> entry : bids.entrySet()) {
adBundle.putString(entry.getKey(), entry.getValue());
}
}
}
private static void handleAdManagerCustomTargeting(HashMap<String, String> bids, Object publisherAdRequest) {
removeUsedCustomTargetingForDFP(publisherAdRequest);
if (bids != null && !bids.isEmpty()) {
Bundle bundle = (Bundle) Util.callMethodOnObject(publisherAdRequest, "getCustomTargeting");
if (bundle != null) {
for (String key : bids.keySet()) {
bundle.putString(key, bids.get(key));
addReservedKeys(key);
}
}
}
}
private static void handleAdManagerBuilderCustomTargeting(HashMap<String, String> bids, Object publisherAdRequestBuilder) {
Object publisherAdRequest = Util.callMethodOnObject(publisherAdRequestBuilder, "build");
removeUsedCustomTargetingForDFP(publisherAdRequest);
if (bids != null && !bids.isEmpty()) {
for (String key : bids.keySet()) {
Util.callMethodOnObject(publisherAdRequestBuilder, "addCustomTargeting", key, bids.get(key));
addReservedKeys(key);
}
}
}
private static void addReservedKeys(String key) {
synchronized (reservedKeys) {
reservedKeys.add(key);
}
}
private static void removeUsedCustomTargetingForDFP(Object publisherAdRequest) {
Bundle bundle = (Bundle) Util.callMethodOnObject(publisherAdRequest, "getCustomTargeting");
if (bundle != null && reservedKeys != null) {
for (String key : reservedKeys) {
bundle.remove(key);
}
}
}
static <E, U> void addValue(Map<E, Set<U>> map, E key, U value) {
Set<U> valueSet = map.get(key);
if (valueSet == null) {
valueSet = new HashSet<>();
map.put(key, valueSet);
}
valueSet.add(value);
}
@NonNull
static <E, U> JSONObject toJson(@Nullable Map<E, ? extends Collection<U>> map) throws JSONException {
JSONObject jsonObject = new JSONObject();
if (map == null) {
return jsonObject;
}
for (Map.Entry<E, ? extends Collection<U>> entry : map.entrySet()) {
jsonObject.put(entry.getKey().toString(), new JSONArray(entry.getValue()));
}
return jsonObject;
}
static <T> List<T> convertJSONArray(JSONArray jsonArray) throws Exception {
List<T> list = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
list.add((T) jsonArray.get(i));
}
return list;
}
public interface Function1<R, T> {
R apply(T element);
}
@Nullable
static <T, E> List<T> convertCollection(@Nullable Collection<E> collection, Function1<T, E> callable) {
List<T> result = null;
if (collection != null) {
result = new ArrayList<>(collection.size());
for (E element : collection) {
result.add(callable.apply(element));
}
}
return result;
}
/**
* Generate ad tag url for Google's IMA SDK to fetch ads
*
* @param adUnit GAM ad unit id
* @param sizes a set of ad sizes, only 640x480 and 400x300 are valid
* @param prebidKeywords prebid keywords
* @return ad tag url
*/
public static String generateInstreamUriForGam(String adUnit, HashSet<AdSize> sizes, Map<String, String> prebidKeywords) {
String uri = "https://pubads.g.doubleclick.net/gampad/ads?";
if (TextUtils.isEmpty(adUnit)) {
throw new IllegalArgumentException("adUnit should not be empty");
}
String sz = "";
if (sizes == null || sizes.size() == 0) {
throw new IllegalArgumentException("sizes should not be empty");
} else {
for (AdSize size : sizes) {
if (!(size.getWidth() == 640 && size.getHeight() == 480) && !(size.getWidth() == 400 && size.getHeight() == 300)) {
throw new IllegalArgumentException("size should be either 640x480 or 400x300");
} else {
sz = sz + size.getWidth() + 'x' + size.getHeight() + "|";
}
}
}
sz = sz.substring(0, sz.length() - 1);
uri = uri + "sz=" + sz + "&iu=" + adUnit + "&impl=s&gdfp_req=1&env=vp&output=xml_vast4&unviewed_position_start=1";
if (prebidKeywords != null) {
uri = uri + "&cust_params=";
for (String key : prebidKeywords.keySet()) {
uri = uri + key + "%3D" + prebidKeywords.get(key) + "%26";
}
}
return uri;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/VideoAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import org.prebid.mobile.api.data.AdFormat;
import java.util.EnumSet;
import java.util.HashSet;
public class VideoAdUnit extends VideoBaseAdUnit {
/**
* @deprecated - For outstream video ads use {@link BannerAdUnit} with adUnitFormat parameter:
* {@code EnumSet.of(AdUnitFormat.VIDEO); }
* <br>
* - For instream video ads use {@link InStreamVideoAdUnit}.
*/
public VideoAdUnit(@NonNull String configId, int width, int height) {
super(configId, EnumSet.of(AdFormat.VAST));
configuration.addSize(new AdSize(width, height));
}
AdSize getAdSize() {
HashSet<AdSize> sizes = configuration.getSizes();
return sizes.iterator().next();
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/VideoBaseAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.api.data.AdFormat;
import java.util.EnumSet;
import java.util.List;
public abstract class VideoBaseAdUnit extends AdUnit {
VideoBaseAdUnit(@NonNull String configId, @NonNull EnumSet<AdFormat> adType) {
super(configId, adType);
}
@Nullable
public VideoParameters getVideoParameters() {
return configuration.getVideoParameters();
}
public void setVideoParameters(@Nullable VideoParameters parameters) {
configuration.setVideoParameters(parameters);
}
/**
* @deprecated use `setVideoParameters()`
*/
@Deprecated
public void setParameters(Parameters parameters) {
if (parameters != null) {
VideoParameters newParameters = new VideoParameters(parameters.getMimes());
newParameters.setApi(parameters.getApi());
newParameters.setMaxBitrate(parameters.getMaxBitrate());
newParameters.setMinBitrate(parameters.getMinBitrate());
newParameters.setMaxDuration(parameters.getMaxDuration());
newParameters.setMinDuration(parameters.getMinDuration());
newParameters.setPlacement(parameters.getPlacement());
newParameters.setPlaybackMethod(parameters.getPlaybackMethod());
newParameters.setProtocols(parameters.getProtocols());
newParameters.setStartDelay(parameters.getStartDelay());
configuration.setVideoParameters(newParameters);
}
}
/**
* @deprecated use `getVideoParameters()`
*/
@Deprecated
@Nullable
public Parameters getParameters() {
VideoParameters newParameters = configuration.getVideoParameters();
if (newParameters != null) {
Parameters oldParameters = new Parameters();
oldParameters.setApi(newParameters.getApi());
oldParameters.setMaxBitrate(newParameters.getMaxBitrate());
oldParameters.setMinBitrate(newParameters.getMinBitrate());
oldParameters.setMimes(newParameters.getMimes());
oldParameters.setMaxDuration(newParameters.getMaxDuration());
oldParameters.setMinDuration(newParameters.getMinDuration());
oldParameters.setPlacement(newParameters.getPlacement());
oldParameters.setPlaybackMethod(newParameters.getPlaybackMethod());
oldParameters.setProtocols(newParameters.getProtocols());
oldParameters.setStartDelay(newParameters.getStartDelay());
return oldParameters;
}
return null;
}
/**
* Describes an <a href="https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf">OpenRTB</a> video object
*/
public static class Parameters {
/**
List of supported API frameworks for this impression. If an API is not explicitly listed, it is assumed not to be supported.
*/
@Nullable
private List<Signals.Api> api;
/**
Maximum bit rate in Kbps.
*/
@Nullable
private Integer maxBitrate;
/**
Maximum bit rate in Kbps.
*/
@Nullable
private Integer minBitrate;
/**
Maximum video ad duration in seconds.
*/
@Nullable
private Integer maxDuration;
/**
Minimum video ad duration in seconds.
*/
@Nullable
private Integer minDuration;
/**
Content MIME types supported
# Example #
* "video/mp4"
* "video/x-ms-wmv"
*/
@Nullable
private List<String> mimes;
/**
Allowed playback methods. If none specified, assume all are allowed.
*/
@Nullable
private List<Signals.PlaybackMethod> playbackMethod;
/**
Array of supported video bid response protocols.
*/
@Nullable
private List<Signals.Protocols> protocols;
/**
Indicates the start delay in seconds for pre-roll, mid-roll, or post-roll ad placements.
*/
@Nullable
private Signals.StartDelay startDelay;
/**
Placement type for the impression.
*/
@Nullable
private Signals.Placement placement;
/**
* Placement type for the impression.
*/
@Nullable
private Integer linearity;
//Getters and setters
@Nullable
public List<Signals.Api> getApi() {
return api;
}
public void setApi(@Nullable List<Signals.Api> api) {
this.api = api;
}
@Nullable
public Integer getMaxBitrate() {
return maxBitrate;
}
public void setMaxBitrate(@Nullable Integer maxBitrate) {
this.maxBitrate = maxBitrate;
}
@Nullable
public Integer getMinBitrate() {
return minBitrate;
}
public void setMinBitrate(@Nullable Integer minBitrate) {
this.minBitrate = minBitrate;
}
@Nullable
public Integer getMaxDuration() {
return maxDuration;
}
public void setMaxDuration(@Nullable Integer maxDuration) {
this.maxDuration = maxDuration;
}
@Nullable
public Integer getMinDuration() {
return minDuration;
}
public void setMinDuration(@Nullable Integer minDuration) {
this.minDuration = minDuration;
}
@Nullable
public List<String> getMimes() {
return mimes;
}
public void setMimes(@Nullable List<String> mimes) {
this.mimes = mimes;
}
@Nullable
public List<Signals.PlaybackMethod> getPlaybackMethod() {
return playbackMethod;
}
public void setPlaybackMethod(@Nullable List<Signals.PlaybackMethod> playbackMethod) {
this.playbackMethod = playbackMethod;
}
@Nullable
public List<Signals.Protocols> getProtocols() {
return protocols;
}
public void setProtocols(@Nullable List<Signals.Protocols> protocols) {
this.protocols = protocols;
}
@Nullable
public Signals.StartDelay getStartDelay() {
return startDelay;
}
public void setStartDelay(@Nullable Signals.StartDelay startDelay) {
this.startDelay = startDelay;
}
@Nullable
public Signals.Placement getPlacement() {
return placement;
}
public void setPlacement(@Nullable Signals.Placement placement) {
this.placement = placement;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/VideoInterstitialAdUnit.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import androidx.annotation.NonNull;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.rendering.models.AdPosition;
import java.util.EnumSet;
public class VideoInterstitialAdUnit extends VideoBaseAdUnit {
public VideoInterstitialAdUnit(@NonNull String configId) {
super(configId, EnumSet.of(AdFormat.VAST));
configuration.setAdPosition(AdPosition.FULLSCREEN);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/VideoParameters.java | package org.prebid.mobile;
import androidx.annotation.Nullable;
import java.util.List;
/**
* Describes an <a href="https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf">OpenRTB</a> video object
*/
public class VideoParameters {
/**
* @param mimes - supported content MIME types (required parameter)
* "video/mp4"
* "video/x-ms-wmv"
*/
public VideoParameters(List<String> mimes) {
this.mimes = mimes;
}
/**
* List of supported API frameworks for this impression. If an API is not explicitly listed, it is assumed not to be supported.
*/
@Nullable
private List<Signals.Api> api;
/**
* Maximum bit rate in Kbps.
*/
@Nullable
private Integer maxBitrate;
/**
* Maximum bit rate in Kbps.
*/
@Nullable
private Integer minBitrate;
/**
* Maximum video ad duration in seconds.
*/
@Nullable
private Integer maxDuration;
/**
* Minimum video ad duration in seconds.
*/
@Nullable
private Integer minDuration;
/**
* Content MIME types supported
* <p>
* # Example #
* "video/mp4"
* "video/x-ms-wmv"
*/
private List<String> mimes;
/**
* Allowed playback methods. If none specified, assume all are allowed.
*/
@Nullable
private List<Signals.PlaybackMethod> playbackMethod;
/**
* Array of supported video bid response protocols.
*/
@Nullable
private List<Signals.Protocols> protocols;
/**
* Indicates the start delay in seconds for pre-roll, mid-roll, or post-roll ad placements.
*/
@Nullable
private Signals.StartDelay startDelay;
/**
* Placement type for the impression.
*/
@Nullable
private Signals.Placement placement;
/**
* Placement type for the impression.
*/
@Nullable
private Integer linearity;
@Nullable
private AdSize adSize;
//Getters and setters
@Nullable
public List<Signals.Api> getApi() {
return api;
}
public void setApi(@Nullable List<Signals.Api> api) {
this.api = api;
}
@Nullable
public Integer getMaxBitrate() {
return maxBitrate;
}
public void setMaxBitrate(@Nullable Integer maxBitrate) {
this.maxBitrate = maxBitrate;
}
@Nullable
public Integer getMinBitrate() {
return minBitrate;
}
public void setMinBitrate(@Nullable Integer minBitrate) {
this.minBitrate = minBitrate;
}
@Nullable
public Integer getMaxDuration() {
return maxDuration;
}
public void setMaxDuration(@Nullable Integer maxDuration) {
this.maxDuration = maxDuration;
}
@Nullable
public Integer getMinDuration() {
return minDuration;
}
public void setMinDuration(@Nullable Integer minDuration) {
this.minDuration = minDuration;
}
@Nullable
public List<String> getMimes() {
return mimes;
}
@Nullable
public List<Signals.PlaybackMethod> getPlaybackMethod() {
return playbackMethod;
}
public void setPlaybackMethod(@Nullable List<Signals.PlaybackMethod> playbackMethod) {
this.playbackMethod = playbackMethod;
}
@Nullable
public List<Signals.Protocols> getProtocols() {
return protocols;
}
public void setProtocols(@Nullable List<Signals.Protocols> protocols) {
this.protocols = protocols;
}
@Nullable
public Signals.StartDelay getStartDelay() {
return startDelay;
}
public void setStartDelay(@Nullable Signals.StartDelay startDelay) {
this.startDelay = startDelay;
}
@Nullable
public Signals.Placement getPlacement() {
return placement;
}
public void setPlacement(@Nullable Signals.Placement placement) {
this.placement = placement;
}
@Nullable
public Integer getLinearity() {
return linearity;
}
public void setLinearity(@Nullable Integer linearity) {
this.linearity = linearity;
}
@Nullable
public AdSize getAdSize() {
return adSize;
}
public void setAdSize(@Nullable AdSize adSize) {
this.adSize = adSize;
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/VisibilityDetector.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile;
import android.graphics.Rect;
import android.view.View;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class VisibilityDetector {
static final long VISIBILITY_THROTTLE_MILLIS = 250;
private boolean scheduled = false;
private View view; // not null
private ArrayList<VisibilityListener> listeners;
private Runnable visibilityCheck;
private ScheduledExecutorService tasker;
private static final String TAG = "VisibilityDetector";
private final int MIN_PERCENTAGE_VIEWED = 50;
static VisibilityDetector create(View view) {
if (view == null) {
LogUtil.debug(TAG, "Unable to check visibility");
return null;
}
return new VisibilityDetector(view);
}
private VisibilityDetector(View view) {
this.view = view;
this.listeners = new ArrayList<VisibilityListener>();
scheduleVisibilityCheck();
}
void addVisibilityListener(VisibilityListener listener) {
if (listener != null) {
listeners.add(listener);
}
}
boolean removeVisibilityListener(VisibilityListener listener) {
return listeners.remove(listener);
}
void scheduleVisibilityCheck(){
if(scheduled) return;
scheduled = true;
this.visibilityCheck = new Runnable() {
@Override
public void run() {
if (listeners != null) {
// copy listeners to a new array to avoid concurrentmodificationexception
ArrayList<VisibilityListener> tempList = new ArrayList<VisibilityListener>();
for (VisibilityListener listener : listeners) {
tempList.add(listener);
}
if (isVisible()) {
for (VisibilityListener listener : tempList) {
listener.onVisibilityChanged(true);
}
} else {
for (VisibilityListener listener : tempList) {
listener.onVisibilityChanged(false);
}
}
}
}
};
tasker = Executors.newSingleThreadScheduledExecutor();
tasker.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
view.post(visibilityCheck);
}
}, 0, VISIBILITY_THROTTLE_MILLIS, TimeUnit.MILLISECONDS);
}
boolean isVisible() {
if (view == null || view.getVisibility() != View.VISIBLE || view.getParent() == null) {
return false;
}
// holds the visible part of a view
Rect clippedArea = new Rect();
if (!view.getGlobalVisibleRect(clippedArea)) {
return false;
}
final int visibleViewArea = clippedArea.height() * clippedArea.width();
final int totalArea = view.getHeight() * view.getWidth();
if (totalArea <= 0) {
return false;
}
return 100 * visibleViewArea >= MIN_PERCENTAGE_VIEWED * totalArea;
}
void destroy() {
if (tasker != null) {
tasker.shutdownNow();
}
view.removeCallbacks(visibilityCheck);
view = null;
listeners = null;
}
interface VisibilityListener {
void onVisibilityChanged(boolean visible);
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/addendum/AdViewUtils.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.addendum;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import org.prebid.mobile.CacheManager;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.PrebidNativeAd;
import org.prebid.mobile.PrebidNativeAdListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class AdViewUtils {
private static final String INNER_HTML_SCRIPT = "document.body.innerHTML";
private static final String SIZE_VALUE_REGEX_EXPRESSION = "[0-9]+x[0-9]+";
private static final String SIZE_OBJECT_REGEX_EXPRESSION = "hb_size\\W+" + SIZE_VALUE_REGEX_EXPRESSION; //"hb_size\\W+[0-9]+x[0-9]+"
private static final String GAM_VIEW_CLASS = "com.google.android.gms.ads.doubleclick.PublisherAdView";
private static final String GAM_VIEW_CLASS_2 = "com.google.android.gms.ads.admanager.AdManagerAdView";
private static final String GAM_CUSTOM_TEMPLATE_AD_CLASS = "com.google.android.gms.ads.formats.NativeCustomTemplateAd";
private static final String GAM_CUSTOM_TEMPLATE_AD_CLASS_2 = "com.google.android.gms.ads.nativead.NativeCustomFormatAd";
private AdViewUtils() { }
@SuppressWarnings("deprecation")
public static void findPrebidCreativeSize(@Nullable View adView, final PbFindSizeListener handler) {
if (adView == null) {
warnAndTriggerFailure(PbFindSizeErrorFactory.NO_WEB_VIEW, handler);
return;
}
List<WebView> webViewList = new ArrayList<>(2);
recursivelyFindWebViewList(adView, webViewList);
if (webViewList.size() == 0) {
warnAndTriggerFailure(PbFindSizeErrorFactory.NO_WEB_VIEW, handler);
return;
}
findSizeInWebViewListAsync(webViewList, handler);
}
static void triggerSuccess(WebView webView, Pair<Integer, Integer> adSize, PbFindSizeListener handler) {
final int width = adSize.first;
final int height = adSize.second;
handler.success(width, height);
fixZoomIn(webView, width, height);
}
//a fix of strange bug on Android with image scaling up
//case: should be called after PublisherAdView.setAdSizes()
static void fixZoomIn(final WebView webView, final int expectedWidth, final int expectedHeight) {
final int minViewHeight = 10;
//500 millis to find a webViewContentHeight
//usually it takes 200 millis
final int contentHeightDelayMillis = 100;
int queueLimit = 5;
final LimitedQueueContainer<Integer> contentHeightQueue = new LimitedQueueContainer<>(queueLimit);
final Set<Integer> contentHeightSet = new HashSet<>(queueLimit);
webView.post(new Runnable() {
@Override
public void run() {
int webViewHeight = webView.getHeight();
//case: check if a publisher have called PublisherAdView.setAdSizes()
//if publisher does not call PublisherAdView.setAdSizes() it is less then 10(e.g 3 instead of 750)
if (webViewHeight > minViewHeight) {
int webViewContentHeight = webView.getContentHeight();
//case: wait when webView.getContentHeight() >= expected height from HTML
//webView does not contain getContentWidth()
if (webViewContentHeight < expectedHeight) {
LogUtil.debug("fixZoomIn" + " webViewContentHeight:" + webViewContentHeight);
contentHeightQueue.add(webViewContentHeight);
if (contentHeightQueue.isFull()) {
contentHeightSet.clear();
contentHeightSet.addAll(contentHeightQueue.getList());
if (contentHeightSet.size() == 1) {
//case: if it is not possible to get an expected height se scale as is
setWebViewScale(webView, webViewHeight, webViewContentHeight);
return;
}
}
webView.postDelayed(this, contentHeightDelayMillis);
} else {
setWebViewScale(webView, webViewHeight, webViewContentHeight);
}
}
}
});
}
static void setWebViewScale(WebView webView, float webViewHeight, int webViewContentHeight) {
//case: regulate scale because WebView.getSettings().setLoadWithOverviewMode() does not work
int scale = (int) (webViewHeight / webViewContentHeight * 100 + 1);
LogUtil.debug("fixZoomIn WB Height:" + webViewHeight + " getContentHeight:" + webViewContentHeight + " scale:" + scale);
webView.setInitialScale(scale);
}
static void warnAndTriggerFailure(Set<Pair<WebView, PbFindSizeError>> webViewErrorSet, PbFindSizeListener handler) {
warnAndTriggerFailure(PbFindSizeErrorFactory.getCompositeFailureError(webViewErrorSet), handler);
}
static void warnAndTriggerFailure(PbFindSizeError error, PbFindSizeListener handler) {
String description = error.getDescription();
LogUtil.warning(description);
handler.failure(error);
}
@Nullable
static void recursivelyFindWebViewList(@Nullable View view, List<WebView> webViewList) {
if (view instanceof ViewGroup) {
//ViewGroup
ViewGroup viewGroup = (ViewGroup) view;
if (viewGroup instanceof WebView) {
//WebView
final WebView webView = (WebView) viewGroup;
webViewList.add(webView);
} else {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
recursivelyFindWebViewList(viewGroup.getChildAt(i), webViewList);
}
}
}
}
static void findSizeInWebViewListAsync(@Size(min = 1) final List<WebView> webViewList, final PbFindSizeListener handler) {
LogUtil.debug("webViewList size:" + webViewList.size());
int lastIndex = webViewList.size() - 1;
iterateWebViewListAsync(webViewList, lastIndex, handler);
}
/**
* {@link PbFindSizeListener} will be called only once.
* {@link PbFindSizeListener#success(int, int)} when size is found
* and {@link PbFindSizeListener#failure(PbFindSizeError)} when size is not found inside passed WebView list
*/
static void iterateWebViewListAsync(@Size(min = 1) final List<WebView> webViewList, final int index, final PbFindSizeListener handler) {
final WebView webView = webViewList.get(index);
webView.evaluateJavascript(INNER_HTML_SCRIPT, new ValueCallback<String>() {
private Set<Pair<WebView, PbFindSizeError>> errorSet = new LinkedHashSet<>();
private void processNextWebViewOrFail(PbFindSizeError error) {
errorSet.add(new Pair<>(webView, error));
int nextIndex = index - 1;
if (nextIndex >= 0) {
iterateWebViewListAsync(webViewList, nextIndex, handler);
} else {
warnAndTriggerFailure(errorSet, handler);
}
}
@Override
public void onReceiveValue(@Nullable String html) {
Pair<Pair<Integer, Integer>, PbFindSizeError> pair = findSizeInHtml(html);
@Nullable
Pair<Integer, Integer> size = pair.first;
@Nullable
PbFindSizeError error = pair.second;
if (size != null) {
triggerSuccess(webView, size, handler);
} else {
processNextWebViewOrFail(error);
}
}
});
}
/**
* {@link PrebidNativeAdListener} will be called only once.
* {@link PrebidNativeAdListener#onPrebidNativeLoaded(PrebidNativeAd)} when Cached Ad is found and is valid
* {@link PrebidNativeAdListener#onPrebidNativeNotValid()} (PrebidNativeAd)} when Cached Ad is found and but is invalid
* and {@link PrebidNativeAdListener#onPrebidNativeNotFound()} ()} (PrebidNativeAd)} when Cached Ad is not found
*/
static void iterateWebViewListAsync(final List<WebView> webViewList, final int index, final PrebidNativeAdListener listener) {
final WebView webView = webViewList.get(index);
webView.evaluateJavascript(INNER_HTML_SCRIPT, new ValueCallback<String>() {
private void processNextWebView() {
int nextIndex = index - 1;
if (nextIndex >= 0) {
iterateWebViewListAsync(webViewList, nextIndex, listener);
} else {
listener.onPrebidNativeNotFound();
}
}
@Override
public void onReceiveValue(@Nullable String html) {
Pattern prebidPattern = Pattern.compile("\\%\\%Prebid\\%\\%.*\\%\\%Prebid\\%\\%");
Matcher m = prebidPattern.matcher(html);
if (m.find()) {
String s = m.group();
String[] results = s.split("%%");
String cacheId = results[2];
if (CacheManager.isValid(cacheId)) {
PrebidNativeAd ad = createPrebidNativeAd(cacheId, listener);
if (ad != null) {
listener.onPrebidNativeLoaded(ad);
return;
}
}
listener.onPrebidNativeNotValid();
} else {
processNextWebView();
}
}
});
}
private static PrebidNativeAd createPrebidNativeAd(String cacheId, PrebidNativeAdListener listener) {
Class clazz = null;
try {
clazz = Class.forName("org.prebid.mobile.PrebidNativeAd");
Method method = clazz.getDeclaredMethod("create", String.class);
method.setAccessible(true);
return (PrebidNativeAd) method.invoke(null, cacheId);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@NonNull
static Pair<Pair<Integer, Integer>, PbFindSizeError> findSizeInHtml(@Nullable String html) {
if (TextUtils.isEmpty(html)) {
return new Pair<>(null, PbFindSizeErrorFactory.NO_HTML);
}
String hbSizeObject = findHbSizeObject(html);
if (hbSizeObject == null) {
return new Pair<>(null, PbFindSizeErrorFactory.NO_SIZE_OBJECT);
}
String hbSizeValue = findHbSizeValue(hbSizeObject);
if (hbSizeValue == null) {
return new Pair<>(null, PbFindSizeErrorFactory.NO_SIZE_VALUE);
}
Pair<Integer, Integer> size = stringToSize(hbSizeValue);
if (size == null) {
return new Pair<>(null, PbFindSizeErrorFactory.SIZE_UNPARSED);
} else {
return new Pair<>(size, null);
}
}
@Nullable
static String findHbSizeObject(String text) {
return matchAndCheck(SIZE_OBJECT_REGEX_EXPRESSION, text);
}
@Nullable
static String findHbSizeValue(String text) {
return matchAndCheck(SIZE_VALUE_REGEX_EXPRESSION, text);
}
@NonNull
static String[] matches(String regex, String text) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
List<String> allMatches = new ArrayList<>();
while (matcher.find()) {
allMatches.add(matcher.group());
}
return allMatches.toArray(new String[0]);
}
@Nullable
static String matchAndCheck(String regex, String text) {
String[] matched = matches(regex, text);
if (matched.length == 0) {
return null;
}
String firstResult = matched[0];
return firstResult;
}
@Nullable
static Pair<Integer, Integer> stringToSize(String size) {
String[] sizeArr = size.split("x");
if (sizeArr.length != 2) {
LogUtil.warning(size + " has a wrong format");
return null;
}
String widthString = sizeArr[0];
String heightString = sizeArr[1];
int width;
int height;
try {
width = Integer.parseInt(widthString);
} catch (NumberFormatException e) {
LogUtil.warning(size + "can not be converted to Size");
return null;
}
try {
height = Integer.parseInt(heightString);
} catch (NumberFormatException e) {
LogUtil.warning(size + "can not be converted to Size");
return null;
}
return new Pair<>(width, height);
}
public interface PbFindSizeListener {
void success(int width, int height);
void failure(@NonNull PbFindSizeError error);
}
/**
* This API can be used to find if the passed object contains info to retreive valid cached Native response or not,
* and notifies using the {@link PrebidNativeAdListener}
*
* @param object instances of Google Native Ads
* @param listener to notify the validity of passed object via @onPrebidNativeLoaded, #onPrebidNativeNotFound, #onPrebidNativeNotValid
*/
public static void findNative(@NonNull Object object, @NonNull PrebidNativeAdListener listener) {
String objectClassName = object.getClass().getCanonicalName();
if (GAM_VIEW_CLASS.equals(objectClassName) || GAM_VIEW_CLASS_2.equals(objectClassName)) {
View adView = (View) object;
findNativeInGAMPublisherAdView(adView, listener);
} else if (implementsInterface(object, GAM_CUSTOM_TEMPLATE_AD_CLASS) || implementsInterface(object, GAM_CUSTOM_TEMPLATE_AD_CLASS_2)) {
findNativeInGAMCustomTemplateAd(object, listener);
} else {
listener.onPrebidNativeNotFound();
}
}
private static boolean implementsInterface(@NonNull Object object, @NonNull String interfaceName) {
for (Class c : object.getClass().getInterfaces()) {
LogUtil.debug("Prebid", c.getCanonicalName());
if (c.getCanonicalName().equals(interfaceName)) {
return true;
}
}
return false;
}
private static void findNativeInGAMCustomTemplateAd(@NonNull Object object, @NonNull PrebidNativeAdListener listener) {
String isPrebid = (String) callMethodOnObject(object, "getText", "isPrebid");
if ("1".equals(isPrebid)) {
String cacheId = (String) callMethodOnObject(object, "getText", "hb_cache_id_local");
PrebidNativeAd ad = createPrebidNativeAd(cacheId, listener);
if (ad != null) {
listener.onPrebidNativeLoaded(ad);
} else {
listener.onPrebidNativeNotValid();
}
} else {
listener.onPrebidNativeNotFound();
}
}
private static void findNativeInGAMPublisherAdView(@NonNull View adView, @NonNull PrebidNativeAdListener listener) {
List<WebView> webViewList = new ArrayList<>();
AdViewUtils.recursivelyFindWebViewList(adView, webViewList);
if (webViewList.size() == 0) {
listener.onPrebidNativeNotFound();
} else {
iterateWebViewListAsync(webViewList, webViewList.size() - 1, listener);
}
}
static Object callMethodOnObject(Object object, String methodName, Object... params) {
try {
int len = params.length;
Class<?>[] classes = new Class[len];
for (int i = 0; i < len; i++) {
classes[i] = params[i].getClass();
}
Method method = object.getClass().getMethod(methodName, classes);
return method.invoke(object, params);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
//It is not possible to use Enum because we should have a possibility to pass additional information
final class PbFindSizeErrorFactory {
private PbFindSizeErrorFactory() { }
//common errors
static final int UNSPECIFIED_CODE = 201;
static final int UNSUPPORTED_ANDROID_IPI_CODE = 202;
static final int COMPOSITE_FAILURE_CODE = 203;
//Platform's errors
static final int NO_WEBVIEW_CODE = 210;
static final int WEBVIEW_FAILED_CODE = 220;
static final int NO_HTML_CODE = 230;
static final int NO_SIZE_OBJECT_CODE = 240;
static final int NO_SIZE_VALUE_CODE = 250;
static final int SIZE_UNPARSED_CODE = 260;
//factory's objects
static final PbFindSizeError UNSPECIFIED = getUnspecifiedError();
static final PbFindSizeError NO_WEB_VIEW = getNoWebViewError();
static final PbFindSizeError NO_HTML = getNoHtmlError();
static final PbFindSizeError NO_SIZE_OBJECT = getNoSizeObjectError();
static final PbFindSizeError NO_SIZE_VALUE = getNoSizeValueError();
static final PbFindSizeError SIZE_UNPARSED = getSizeUnparsedError();
private static PbFindSizeError getUnspecifiedError() {
return getError(UNSPECIFIED_CODE, "Unspecified error");
}
static PbFindSizeError getUnsupportedAndroidIpiError(int currentAndroidApi, int necessaryAndroidApi) {
return getError(UNSUPPORTED_ANDROID_IPI_CODE, "AndroidAPI:" + currentAndroidApi + " doesn't support the functionality. Minimum AndroidAPI is:" + necessaryAndroidApi);
}
static PbFindSizeError getCompositeFailureError(Set<Pair<WebView, PbFindSizeError>> errorSet) {
StringBuilder result = new StringBuilder();
result.append("There is a set of errors:\n");
for (Pair<WebView, PbFindSizeError> webViewFindSizeError : errorSet) {
result.append(" WebView:").append(webViewFindSizeError.first)
.append(" errorCode:").append(webViewFindSizeError.second.getCode())
.append(" errorDescription:").append(webViewFindSizeError.second.getDescription())
.append("\n");
}
return getError(COMPOSITE_FAILURE_CODE, result.toString());
}
//private zone
private static PbFindSizeError getNoWebViewError() {
return getError(NO_WEBVIEW_CODE, "The view doesn't include WebView");
}
private static PbFindSizeError getWebViewFailedError() {
return getError(WEBVIEW_FAILED_CODE, "The view doesn't include WebView");
}
private static PbFindSizeError getNoHtmlError() {
return getError(NO_HTML_CODE, "The WebView doesn't have HTML");
}
private static PbFindSizeError getNoSizeObjectError() {
return getError(NO_SIZE_OBJECT_CODE, "The HTML doesn't contain a size object");
}
private static PbFindSizeError getNoSizeValueError() {
return getError(NO_SIZE_VALUE_CODE, "The size object doesn't contain a value");
}
private static PbFindSizeError getSizeUnparsedError() {
return getError(SIZE_UNPARSED_CODE, "The size value has a wrong format");
}
private static PbFindSizeError getError(final int code, final String description) {
return new PbFindSizeError(code, description);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/addendum/LimitedQueueContainer.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.addendum;
import java.util.LinkedList;
import java.util.Queue;
public class LimitedQueueContainer<T> {
private Queue<T> list = new LinkedList<>();
private final int limit;
public LimitedQueueContainer(int limit) {
if (limit < 0) {
throw new IllegalArgumentException("Illegal Limit:" + limit);
}
this.limit = limit;
}
void add(T t) {
list.add(t);
if (list.size() > limit) {
list.poll();
}
}
boolean isFull() {
return list.size() == limit;
}
Queue<T> getList() {
return list;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/addendum/Pair.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.addendum;
class Pair<U, V> {
U first;
V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
@SuppressWarnings("EqualsReplaceableByObjectsCall")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
return second != null ? second.equals(pair.second) : pair.second == null;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/addendum/PbError.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.addendum;
class PbError {
private final String domain = "com.prebidmobile.android";
private final int code;
private final String description;
PbError(int code, String description) {
this.code = code;
this.description = description;
}
public final String getDomain() {
return domain;
}
public final int getCode() {
return code;
}
public final String getDescription() {
return description;
}
@Override
public int hashCode() {
return code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PbError)) return false;
PbError pbError = (PbError) o;
return code == pbError.code;
}
@Override
public String toString() {
return "PbError{" +
"domain='" + domain + '\'' +
", code=" + code +
", description='" + description + '\'' +
'}';
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/addendum/PbFindSizeError.java | /*
* Copyright 2018-2019 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.addendum;
public final class PbFindSizeError extends PbError {
PbFindSizeError(int code, String description) {
super(code, description);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/AdFormat.java | package org.prebid.mobile.api.data;
import java.util.EnumSet;
public enum AdFormat {
BANNER,
INTERSTITIAL,
NATIVE,
VAST;
public static EnumSet<AdFormat> fromSet(
EnumSet<AdUnitFormat> adUnitFormats,
boolean isInterstitial
) {
if (adUnitFormats == null || adUnitFormats.isEmpty())
throw new NullPointerException("List of ad unit formats must contain at least one item.");
EnumSet<AdFormat> result = EnumSet.noneOf(AdFormat.class);
for (AdUnitFormat format : adUnitFormats) {
if (format == AdUnitFormat.DISPLAY || format == AdUnitFormat.BANNER) {
if (isInterstitial) {
result.add(AdFormat.INTERSTITIAL);
} else {
result.add(AdFormat.BANNER);
}
}
if (format == AdUnitFormat.VIDEO) {
result.add(AdFormat.VAST);
}
}
return result;
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/AdUnitFormat.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.data;
public enum AdUnitFormat {
BANNER,
/**
* @deprecated use {@link #BANNER}
*/
@Deprecated
DISPLAY,
VIDEO
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/BannerAdPosition.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.data;
import org.prebid.mobile.rendering.models.AdPosition;
public enum BannerAdPosition {
UNDEFINED(-1),
UNKNOWN(0),
HEADER(4),
FOOTER(5),
SIDEBAR(6);
private final int value;
BannerAdPosition(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static BannerAdPosition mapToDisplayAdPosition(int adPosition) {
final BannerAdPosition[] values = BannerAdPosition.values();
for (BannerAdPosition bannerAdPosition : values) {
if (bannerAdPosition.getValue() == adPosition) {
return bannerAdPosition;
}
}
return BannerAdPosition.UNDEFINED;
}
public static AdPosition mapToAdPosition(BannerAdPosition bannerAdPosition) {
if (bannerAdPosition == null) {
return AdPosition.UNDEFINED;
}
for (AdPosition adPosition : AdPosition.values()) {
if (adPosition.getValue() == bannerAdPosition.getValue()) {
return adPosition;
}
}
return AdPosition.UNDEFINED;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/BidInfo.java | package org.prebid.mobile.api.data;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.CacheManager;
import org.prebid.mobile.ResultCode;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import java.util.Map;
public class BidInfo {
@NonNull
private final ResultCode resultCode;
@Nullable
private Map<String, String> targetingKeywords;
@Nullable
private Map<String, String> events;
@Nullable
private String nativeCacheId;
@Nullable
private Integer exp;
@Nullable
private BidResponse bidResponse;
/**
* Key for {@link #getEvents()} map to get win event.
*/
public static final String EVENT_WIN = "ext.prebid.events.win";
/**
* Key for {@link #getEvents()} map to get impression event.
*/
public static final String EVENT_IMP = "ext.prebid.events.imp";
private BidInfo(@NonNull ResultCode resultCode) {
this.resultCode = resultCode;
}
@NonNull
public ResultCode getResultCode() {
return resultCode;
}
@Nullable
public Map<String, String> getTargetingKeywords() {
return targetingKeywords;
}
@Nullable
public String getNativeCacheId() {
return nativeCacheId;
}
@Nullable
public Integer getExp() {
return exp;
}
@Nullable
public BidResponse getBidResponse() {
return bidResponse;
}
@Nullable
public Map<String, String> getEvents() {
return events;
}
@NonNull
public static BidInfo create(
@NonNull ResultCode resultCode,
@Nullable BidResponse bidResponse,
@Nullable AdUnitConfiguration configuration
) {
BidInfo bidInfo = new BidInfo(resultCode);
if (bidResponse == null) {
return bidInfo;
}
bidInfo.bidResponse = bidResponse;
bidInfo.targetingKeywords = bidResponse.getTargeting();
bidInfo.exp = bidResponse.getExpirationTimeSeconds();
boolean isNative = configuration != null && configuration.getNativeConfiguration() != null;
if (isNative && bidInfo.resultCode == ResultCode.SUCCESS) {
bidInfo.nativeCacheId = CacheManager.save(bidResponse.getWinningBidJson());
}
return bidInfo;
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/FetchDemandResult.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.data;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public enum FetchDemandResult {
/**
* The attaching keywords was successful, which means
* there was demand and the demand was set on the ad object.
*/
SUCCESS,
/**
* The ad request failed due to empty account id
*/
INVALID_ACCOUNT_ID,
/**
* The ad request failed due to empty config id on the ad unit
*/
INVALID_CONFIG_ID,
/**
* Size is invalid or missing
*/
INVALID_SIZE,
/**
* Invalid context passed
*/
INVALID_CONTEXT,
/**
* GAM views supported only
*/
INVALID_AD_OBJECT,
/**
* The ad request failed because a CUSTOM host used without providing host url
*/
INVALID_HOST_URL,
/**
* The ad request failed due to a network error.
*/
NETWORK_ERROR,
/**
* The ad request took longer than set time out
*/
TIMEOUT,
/**
* No bids available from demand source
*/
NO_BIDS,
/**
* Server responded with some error messages
*/
SERVER_ERROR;
public static FetchDemandResult parseErrorMessage(String msg) {
Pattern storedRequestNotFound = Pattern.compile("^Invalid request: Stored Request with ID=\".*\" not found.");
Pattern storedImpNotFound = Pattern.compile("^Invalid request: Stored Imp with ID=\".*\" not found.");
Pattern invalidBannerSize = Pattern.compile("^Invalid request: Request imp\\[\\d\\].banner.format\\[\\d\\] must define non-zero \"h\" and \"w\" properties.");
Pattern invalidInterstitialSize = Pattern.compile("Invalid request: Unable to set interstitial size list");
Matcher requestMatcher = storedRequestNotFound.matcher(msg);
Matcher bannerSizeMatcher = invalidBannerSize.matcher(msg);
Matcher interstitialSizeMatcher = invalidInterstitialSize.matcher(msg);
Matcher impMatcher = storedImpNotFound.matcher(msg);
if (msg.contains("No bids")) {
return NO_BIDS;
}
if (msg.contains("Timeout")) {
return TIMEOUT;
}
if (msg.contains("Network Error")) {
return NETWORK_ERROR;
}
if (requestMatcher.find() || msg.contains("No stored request")) {
return INVALID_ACCOUNT_ID;
}
if (impMatcher.find() || msg.contains("Stored Imp with ID")) {
return INVALID_CONFIG_ID;
}
if (bannerSizeMatcher.find()
|| interstitialSizeMatcher.find()
|| msg.contains("Request imp[0].banner.format")) {
return INVALID_SIZE;
}
return SERVER_ERROR;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/Position.java | package org.prebid.mobile.api.data;
import androidx.annotation.Nullable;
public enum Position {
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM,
BOTTOM_LEFT,
LEFT;
@Nullable
public static Position fromString(String string) {
switch (string.toLowerCase()) {
case "topleft":
return TOP_LEFT;
case "top":
return TOP;
case "topright":
return TOP_RIGHT;
case "right":
return RIGHT;
case "bottomright":
return BOTTOM_RIGHT;
case "bottom":
return BOTTOM;
case "bottomleft":
return BOTTOM_LEFT;
case "left":
return LEFT;
default:
return null;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/data/VideoPlacementType.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.data;
import androidx.annotation.Nullable;
import org.prebid.mobile.rendering.models.PlacementType;
public enum VideoPlacementType {
IN_BANNER(2),
IN_ARTICLE(3),
IN_FEED(4);
private final int value;
VideoPlacementType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Nullable
public static VideoPlacementType mapToVideoPlacementType(int placementTypeValue) {
for (VideoPlacementType videoPlacementType : VideoPlacementType.values()) {
if (videoPlacementType.getValue() == placementTypeValue) {
return videoPlacementType;
}
}
return null;
}
public static PlacementType mapToPlacementType(VideoPlacementType videoPlacementType) {
if (videoPlacementType == null) {
return PlacementType.UNDEFINED;
}
for (PlacementType placementType : PlacementType.values()) {
if (placementType.getValue() == videoPlacementType.getValue()) {
return placementType;
}
}
return PlacementType.UNDEFINED;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/exceptions/AdException.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.exceptions;
/**
* Base error. Maintaining error description.
*/
public class AdException extends Exception {
public static final String INVALID_REQUEST = "Invalid request";
public static final String INTERNAL_ERROR = "SDK internal error";
public static final String INIT_ERROR = "Initialization failed";
public static final String SERVER_ERROR = "Server error";
public static final String THIRD_PARTY = "Third Party SDK";
private String message;
public void setMessage(String msg) {
message = msg;
}
/**
* Error description.
*
* @return description
*/
@Override
public String getMessage() {
return message;
}
public AdException(String type, String message) {
setMessage(type + ": " + message);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/exceptions/InitError.java | package org.prebid.mobile.api.exceptions;
public class InitError {
private String error;
public InitError(String error) {
this.error = error;
}
public String getError() {
return error;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationBannerAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.mediation;
import android.content.Context;
import androidx.annotation.NonNull;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.BannerAdPosition;
import org.prebid.mobile.api.mediation.listeners.OnFetchCompleteListener;
import org.prebid.mobile.rendering.bidding.display.PrebidMediationDelegate;
import org.prebid.mobile.rendering.models.AdPosition;
import org.prebid.mobile.rendering.utils.broadcast.ScreenStateReceiver;
public class MediationBannerAdUnit extends MediationBaseAdUnit {
private static final String TAG = MediationBannerAdUnit.class.getSimpleName();
private final ScreenStateReceiver screenStateReceiver = new ScreenStateReceiver();
private boolean adFailed;
public MediationBannerAdUnit(
Context context,
String configId,
AdSize size,
PrebidMediationDelegate mediationDelegate
) {
super(context, configId, size, mediationDelegate);
screenStateReceiver.register(context);
}
@Override
protected final void initAdConfig(
String configId,
AdSize adSize
) {
adUnitConfig.addSize(adSize);
adUnitConfig.setConfigId(configId);
adUnitConfig.setAdFormat(AdFormat.BANNER);
}
@Override
public void destroy() {
super.destroy();
screenStateReceiver.unregister();
}
@Override
protected void initBidLoader() {
super.initBidLoader();
bidLoader.setBidRefreshListener(() -> {
if (adFailed) {
adFailed = false;
LogUtil.debug(TAG, "Ad failed, can perform refresh.");
return true;
}
boolean isViewVisible = mediationDelegate.canPerformRefresh();
boolean canRefresh = screenStateReceiver.isScreenOn() && isViewVisible;
LogUtil.debug(TAG, "Can perform refresh: " + canRefresh);
return canRefresh;
});
}
@Override
public final void fetchDemand(
@NonNull
OnFetchCompleteListener listener
) {
super.fetchDemand(listener);
}
public final void addAdditionalSizes(AdSize... sizes) {
adUnitConfig.addSizes(sizes);
}
public final void setRefreshInterval(int seconds) {
adUnitConfig.setAutoRefreshDelay(seconds);
}
public void setAdPosition(BannerAdPosition bannerAdPosition) {
final AdPosition adPosition = BannerAdPosition.mapToAdPosition(bannerAdPosition);
adUnitConfig.setAdPosition(adPosition);
}
public BannerAdPosition getAdPosition() {
return BannerAdPosition.mapToDisplayAdPosition(adUnitConfig.getAdPositionValue());
}
public void stopRefresh() {
if (bidLoader != null) {
bidLoader.cancelRefresh();
}
}
public void onAdFailed() {
adFailed = true;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationBaseAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.mediation;
import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.*;
import org.prebid.mobile.api.data.FetchDemandResult;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.mediation.listeners.OnFetchCompleteListener;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.display.BidResponseCache;
import org.prebid.mobile.rendering.bidding.display.PrebidMediationDelegate;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import org.prebid.mobile.rendering.bidding.loader.BidLoader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
public abstract class MediationBaseAdUnit {
private static final String TAG = MediationBaseAdUnit.class.getSimpleName();
protected OnFetchCompleteListener onFetchCompleteListener;
protected WeakReference<Context> contextWeakReference;
protected AdUnitConfiguration adUnitConfig = new AdUnitConfiguration();
protected PrebidMediationDelegate mediationDelegate;
protected BidLoader bidLoader;
private final BidRequesterListener bidRequesterListener = new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
onResponseReceived(response);
}
@Override
public void onError(AdException exception) {
onErrorReceived(exception);
}
};
protected MediationBaseAdUnit(
Context context,
String configId,
AdSize adSize,
PrebidMediationDelegate mediationDelegate
) {
contextWeakReference = new WeakReference<>(context);
this.mediationDelegate = mediationDelegate;
adUnitConfig.setAutoRefreshDelay(PrebidMobile.AUTO_REFRESH_DELAY_MIN / 1000);
initSdk(context);
initAdConfig(configId, adSize);
initBidLoader();
}
protected void fetchDemand(@NonNull OnFetchCompleteListener listener) {
if (mediationDelegate == null) {
LogUtil.error(TAG, "Demand fetch failed. Mediation delegate object must be not null");
listener.onComplete(FetchDemandResult.INVALID_AD_OBJECT);
return;
}
if (TextUtils.isEmpty(PrebidMobile.getPrebidServerAccountId())) {
LogUtil.error(TAG, "Empty account id");
listener.onComplete(FetchDemandResult.INVALID_ACCOUNT_ID);
return;
}
if (TextUtils.isEmpty(adUnitConfig.getConfigId())) {
LogUtil.error(TAG, "Empty config id");
listener.onComplete(FetchDemandResult.INVALID_CONFIG_ID);
return;
}
final Host bidServerHost = PrebidMobile.getPrebidServerHost();
if (bidServerHost.equals(Host.CUSTOM) && bidServerHost.getHostUrl().isEmpty()) {
LogUtil.error(TAG, "Empty host url for custom Prebid Server host.");
listener.onComplete(FetchDemandResult.INVALID_HOST_URL);
return;
}
onFetchCompleteListener = listener;
bidLoader.load();
}
public void addContextData(
String key,
String value
) {
adUnitConfig.addContextData(key, value);
}
public void updateContextData(
String key,
Set<String> value
) {
adUnitConfig.addContextData(key, value);
}
public void removeContextData(String key) {
adUnitConfig.removeContextData(key);
}
public void clearContextData() {
adUnitConfig.clearContextData();
}
public Map<String, Set<String>> getContextDataDictionary() {
return adUnitConfig.getContextDataDictionary();
}
public void addContextKeyword(String keyword) {
adUnitConfig.addContextKeyword(keyword);
}
public void addContextKeywords(Set<String> keywords) {
adUnitConfig.addContextKeywords(keywords);
}
public void removeContextKeyword(String keyword) {
adUnitConfig.removeContextKeyword(keyword);
}
public Set<String> getContextKeywordsSet() {
return adUnitConfig.getContextKeywordsSet();
}
public void clearContextKeywords() {
adUnitConfig.clearContextKeywords();
}
public void setPbAdSlot(String adSlot) {
adUnitConfig.setPbAdSlot(adSlot);
}
@Nullable
public String getPbAdSlot() {
return adUnitConfig.getPbAdSlot();
}
public void setAppContent(ContentObject content) {
adUnitConfig.setAppContent(content);
}
public ContentObject getAppContent() {
return adUnitConfig.getAppContent();
}
public void addUserData(DataObject dataObject) {
adUnitConfig.addUserData(dataObject);
}
public void clearUserData() {
adUnitConfig.clearUserData();
}
public ArrayList<DataObject> getUserData() {
return adUnitConfig.getUserData();
}
public void destroy() {
onFetchCompleteListener = null;
bidLoader.destroy();
bidLoader = null;
}
protected abstract void initAdConfig(
String configId,
AdSize adSize
);
protected void onResponseReceived(BidResponse response) {
LogUtil.debug(TAG, "On response received");
if (onFetchCompleteListener == null) {
cancelRefresh();
return;
}
BidResponseCache.getInstance().putBidResponse(response);
mediationDelegate.handleKeywordsUpdate(response.getTargeting());
mediationDelegate.setResponseToLocalExtras(response);
onFetchCompleteListener.onComplete(FetchDemandResult.SUCCESS);
}
protected void onErrorReceived(AdException exception) {
LogUtil.warning(TAG, "On error received");
if (onFetchCompleteListener == null) {
cancelRefresh();
return;
}
onFetchCompleteListener.onComplete(FetchDemandResult.parseErrorMessage(exception.getMessage()));
}
protected void initBidLoader() {
bidLoader = new BidLoader(contextWeakReference.get(), adUnitConfig, bidRequesterListener);
}
private void initSdk(Context context) {
PrebidMobile.initializeSdk(context, null);
}
private void cancelRefresh() {
bidLoader.cancelRefresh();
LogUtil.error(TAG, "Failed to pass callback");
if (onFetchCompleteListener == null) {
LogUtil.error(TAG, "OnFetchCompleteListener is null");
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationBaseFullScreenAdUnit.java | package org.prebid.mobile.api.mediation;
import android.content.Context;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.api.data.Position;
import org.prebid.mobile.rendering.bidding.display.PrebidMediationDelegate;
public abstract class MediationBaseFullScreenAdUnit extends MediationBaseAdUnit {
private static final String TAG = MediationBaseFullScreenAdUnit.class.getSimpleName();
protected MediationBaseFullScreenAdUnit(
Context context,
String configId,
AdSize adSize,
PrebidMediationDelegate mediationDelegate
) {
super(context, configId, adSize, mediationDelegate);
}
/**
* Sets max video duration. If the ad from server is bigger, it will be rejected.
*/
public void setMaxVideoDuration(int seconds) {
adUnitConfig.setMaxVideoDuration(seconds);
}
/**
* Sets delay in seconds to show skip or close button.
*/
public void setSkipDelay(int secondsDelay) {
adUnitConfig.setSkipDelay(secondsDelay);
}
/**
* Sets skip button percentage size in range from 0.05 to 1.
* If value less than 0.05, size will be default.
*/
public void setSkipButtonArea(@FloatRange(from = 0, to = 1.0) double buttonArea) {
adUnitConfig.setSkipButtonArea(buttonArea);
}
/**
* Sets skip button position on the screen. Suitable values TOP_LEFT and TOP_RIGHT.
* Default value TOP_RIGHT.
*/
public void setSkipButtonPosition(Position skipButtonPosition) {
adUnitConfig.setSkipButtonPosition(skipButtonPosition);
}
/**
* Sets close button percentage size in range from 0.05 to 1.
* If value less than 0.05, size will be default.
*/
public void setCloseButtonArea(@FloatRange(from = 0, to = 1.0) double closeButtonArea) {
adUnitConfig.setCloseButtonArea(closeButtonArea);
}
/**
* Sets close button position on the screen. Suitable values TOP_LEFT and TOP_RIGHT.
* Default value TOP_RIGHT.
*/
public void setCloseButtonPosition(@Nullable Position closeButtonPosition) {
adUnitConfig.setCloseButtonPosition(closeButtonPosition);
}
/**
* Sets desired is muted property.
*/
public void setIsMuted(boolean isMuted) {
adUnitConfig.setIsMuted(isMuted);
}
/**
* Makes sound button visible.
*/
public void setIsSoundButtonVisible(boolean isSoundButtonVisible) {
adUnitConfig.setIsSoundButtonVisible(isSoundButtonVisible);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationInterstitialAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.mediation;
import android.content.Context;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.AdUnitFormat;
import org.prebid.mobile.api.mediation.listeners.OnFetchCompleteListener;
import org.prebid.mobile.rendering.bidding.display.PrebidMediationDelegate;
import org.prebid.mobile.rendering.models.AdPosition;
import java.util.EnumSet;
public class MediationInterstitialAdUnit extends MediationBaseFullScreenAdUnit {
private static final String TAG = MediationInterstitialAdUnit.class.getSimpleName();
/**
* Constructor to fetch demand for a display interstitial ad with specified minHeightPercentage and minWidthPercentage
*/
public MediationInterstitialAdUnit(
Context context,
String configId,
AdSize minSizePercentage,
PrebidMediationDelegate mediationDelegate
) {
super(context, configId, minSizePercentage, mediationDelegate);
adUnitConfig.setAdFormat(AdFormat.INTERSTITIAL);
}
/**
* Constructor to fetch demand for either display or video interstitial ads
*/
public MediationInterstitialAdUnit(
Context context,
String configId,
@NonNull EnumSet<AdUnitFormat> adUnitFormats,
PrebidMediationDelegate mediationDelegate
) {
super(context, configId, null, mediationDelegate);
adUnitConfig.setAdUnitFormats(adUnitFormats);
}
@Override
public final void fetchDemand(@NonNull OnFetchCompleteListener listener) {
super.fetchDemand(listener);
}
@Override
protected final void initAdConfig(
String configId,
AdSize minSizePercentage
) {
adUnitConfig.setMinSizePercentage(minSizePercentage);
adUnitConfig.setConfigId(configId);
adUnitConfig.setAdPosition(AdPosition.FULLSCREEN);
}
/**
* Sets min width and height in percentage. Range from 0 to 100.
*/
public void setMinSizePercentage(
@IntRange(from = 0, to = 100) int width,
@IntRange(from = 0, to = 100) int height
) {
adUnitConfig.setMinSizePercentage(new AdSize(width, height));
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationNativeAdUnit.java | package org.prebid.mobile.api.mediation;
import androidx.annotation.NonNull;
import org.prebid.mobile.*;
import org.prebid.mobile.api.data.FetchDemandResult;
import org.prebid.mobile.api.mediation.listeners.OnFetchCompleteListener;
import java.util.ArrayList;
public class MediationNativeAdUnit {
private static final String TAG = "MediationNativeAdUnit";
private final Object adObject;
private final NativeAdUnit nativeAdUnit;
public MediationNativeAdUnit(
@NonNull String configId,
@NonNull Object adObject
) {
this.adObject = adObject;
this.nativeAdUnit = new NativeAdUnit(configId);
}
public void fetchDemand(
@NonNull OnFetchCompleteListener listener
) {
nativeAdUnit.fetchDemand(adObject, (resultCode, message) ->
listener.onComplete(convertResultCode(resultCode))
);
}
public void destroy() {
nativeAdUnit.stopAutoRefresh();
}
public void addAsset(NativeAsset asset) {
nativeAdUnit.addAsset(asset);
}
public void addEventTracker(NativeEventTracker tracker) {
nativeAdUnit.addEventTracker(tracker);
}
public void setContextType(NativeAdUnit.CONTEXT_TYPE type) {
nativeAdUnit.setContextType(type);
}
public void setContextSubType(NativeAdUnit.CONTEXTSUBTYPE subType) {
nativeAdUnit.setContextSubType(subType);
}
public void setExt(Object jsonObject) {
nativeAdUnit.setExt(jsonObject);
}
public void setSeq(int seq) {
nativeAdUnit.setSeq(seq);
}
public void setPrivacy(boolean privacy) {
nativeAdUnit.setPrivacy(privacy);
}
public void setPlacementType(NativeAdUnit.PLACEMENTTYPE type) {
nativeAdUnit.setPlacementType(type);
}
public void setPlacementCount(int implementCount) {
nativeAdUnit.setPlacementCount(implementCount);
}
public void setAUrlSupport(boolean support) {
nativeAdUnit.setAUrlSupport(support);
}
public void setDUrlSupport(boolean support) {
nativeAdUnit.setDUrlSupport(support);
}
public void setAppContent(ContentObject content) {
nativeAdUnit.setAppContent(content);
}
public ContentObject getAppContent() {
return nativeAdUnit.getAppContent();
}
public void addUserData(DataObject dataObject) {
nativeAdUnit.addUserData(dataObject);
}
public void clearUserData() {
nativeAdUnit.clearUserData();
}
public ArrayList<DataObject> getUserData() {
return nativeAdUnit.getUserData();
}
private FetchDemandResult convertResultCode(ResultCode originalResult) {
switch (originalResult) {
case SUCCESS:
return FetchDemandResult.SUCCESS;
case INVALID_ACCOUNT_ID:
return FetchDemandResult.INVALID_ACCOUNT_ID;
case INVALID_CONFIG_ID:
return FetchDemandResult.INVALID_CONFIG_ID;
case INVALID_CONTEXT:
return FetchDemandResult.INVALID_CONTEXT;
case INVALID_HOST_URL:
return FetchDemandResult.INVALID_HOST_URL;
case INVALID_SIZE:
return FetchDemandResult.INVALID_SIZE;
case INVALID_AD_OBJECT:
return FetchDemandResult.INVALID_AD_OBJECT;
case NO_BIDS:
return FetchDemandResult.NO_BIDS;
case PREBID_SERVER_ERROR:
return FetchDemandResult.SERVER_ERROR;
case TIMEOUT:
return FetchDemandResult.TIMEOUT;
case NETWORK_ERROR:
return FetchDemandResult.NETWORK_ERROR;
case INVALID_NATIVE_REQUEST:
LogUtil.error(TAG, "Invalid native request!");
return FetchDemandResult.NETWORK_ERROR;
default:
LogUtil.error(TAG, "Something went wrong!");
return FetchDemandResult.NETWORK_ERROR;
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/MediationRewardedVideoAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.mediation;
import android.content.Context;
import androidx.annotation.NonNull;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.FetchDemandResult;
import org.prebid.mobile.api.mediation.listeners.OnFetchCompleteListener;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.display.BidResponseCache;
import org.prebid.mobile.rendering.bidding.display.PrebidMediationDelegate;
import org.prebid.mobile.rendering.models.AdPosition;
public class MediationRewardedVideoAdUnit extends MediationBaseFullScreenAdUnit {
private static final String TAG = "MediationRewardedAdUnit";
public MediationRewardedVideoAdUnit(
Context context,
String configId,
PrebidMediationDelegate mediationDelegate
) {
super(context, configId, null, mediationDelegate);
}
public void fetchDemand(@NonNull OnFetchCompleteListener listener) {
super.fetchDemand(listener);
}
@Override
protected final void initAdConfig(
String configId,
AdSize adSize
) {
adUnitConfig.setConfigId(configId);
adUnitConfig.setAdFormat(AdFormat.VAST);
adUnitConfig.setRewarded(true);
adUnitConfig.setAdPosition(AdPosition.FULLSCREEN);
}
@Override
protected final void onResponseReceived(BidResponse response) {
if (onFetchCompleteListener != null) {
LogUtil.debug(TAG, "On response received");
BidResponseCache.getInstance().putBidResponse(response.getId(), response);
mediationDelegate.setResponseToLocalExtras(response);
mediationDelegate.handleKeywordsUpdate(response.getTargeting());
onFetchCompleteListener.onComplete(FetchDemandResult.SUCCESS);
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/mediation/listeners/OnFetchCompleteListener.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.mediation.listeners;
import androidx.annotation.MainThread;
import org.prebid.mobile.api.data.FetchDemandResult;
public interface OnFetchCompleteListener {
@MainThread
void onComplete(FetchDemandResult result);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/original/MultiformatAdUnitFacade.java | package org.prebid.mobile.api.original;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.AdUnit;
import org.prebid.mobile.BannerParameters;
import org.prebid.mobile.ContentObject;
import org.prebid.mobile.DataObject;
import org.prebid.mobile.NativeParameters;
import org.prebid.mobile.OnCompleteListener;
import org.prebid.mobile.ResultCode;
import org.prebid.mobile.Util;
import org.prebid.mobile.VideoParameters;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.configuration.NativeAdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import org.prebid.mobile.rendering.models.AdPosition;
import org.prebid.mobile.rendering.models.PlacementType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Internal AdUnit implementation that is used for PrebidAdUnit
* with multiformat configuration. It separates logic for multiformat ad unit.
*/
class MultiformatAdUnitFacade extends AdUnit {
@Nullable
private BidResponse bidResponse;
public MultiformatAdUnitFacade(@NotNull String configId, @NonNull PrebidRequest request) {
super(configId);
allowNullableAdObject = true;
setConfigurationBasedOnRequest(request);
}
@Override
protected BidRequesterListener createBidListener(OnCompleteListener originalListener) {
return new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
bidResponse = response;
HashMap<String, String> keywords = response.getTargeting();
Util.apply(keywords, adObject);
originalListener.onComplete(ResultCode.SUCCESS, null);
}
@Override
public void onError(AdException exception) {
bidResponse = null;
Util.apply(null, adObject);
originalListener.onComplete(convertToResultCode(exception), exception.getMessage());
}
};
}
private void setConfigurationBasedOnRequest(
@NonNull PrebidRequest request
) {
if (request.isInterstitial()) {
configuration.setAdPosition(AdPosition.FULLSCREEN);
}
BannerParameters bannerParameters = request.getBannerParameters();
if (bannerParameters != null) {
if (request.isInterstitial()) {
configuration.addAdFormat(AdFormat.INTERSTITIAL);
Integer minWidth = bannerParameters.getInterstitialMinWidthPercentage();
Integer minHeight = bannerParameters.getInterstitialMinHeightPercentage();
if (minWidth != null && minHeight != null) {
configuration.setMinSizePercentage(new AdSize(minWidth, minHeight));
}
} else {
configuration.addAdFormat(AdFormat.BANNER);
}
configuration.setBannerParameters(bannerParameters);
configuration.addSizes(bannerParameters.getAdSizes());
}
VideoParameters videoParameters = request.getVideoParameters();
if (videoParameters != null) {
configuration.addAdFormat(AdFormat.VAST);
if (request.isInterstitial()) {
configuration.setPlacementType(PlacementType.INTERSTITIAL);
}
if (request.isRewarded()) {
configuration.setRewarded(true);
}
configuration.setVideoParameters(videoParameters);
configuration.addSize(videoParameters.getAdSize());
}
NativeParameters nativeParameters = request.getNativeParameters();
if (nativeParameters != null) {
configuration.addAdFormat(AdFormat.NATIVE);
NativeAdUnitConfiguration nativeConfig = nativeParameters.getNativeConfiguration();
configuration.setNativeConfiguration(nativeConfig);
}
ContentObject contentObject = request.getAppContent();
configuration.setAppContent(contentObject);
ArrayList<DataObject> userData = request.getUserData();
configuration.setUserData(userData);
Map<String, Set<String>> extData = request.getExtData();
configuration.setContextDataDictionary(extData);
Set<String> extKeywords = request.getExtKeywords();
configuration.setContextDataKeywords(extKeywords);
}
@Nullable
public BidResponse getBidResponse() {
return bidResponse;
}
@SuppressLint("VisibleForTests")
@Override
public AdUnitConfiguration getConfiguration() {
return super.getConfiguration();
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/original/OnCompleteListenerImpl.java | package org.prebid.mobile.api.original;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.OnCompleteListener;
import org.prebid.mobile.OnCompleteListener2;
import org.prebid.mobile.ResultCode;
import org.prebid.mobile.Util;
import org.prebid.mobile.api.data.BidInfo;
import java.util.Map;
/**
* Listener implementation for multiformat PrebidAdUnit.
*/
class OnCompleteListenerImpl implements OnCompleteListener, OnCompleteListener2 {
@Nullable
private final Object adObject;
@NonNull
private final MultiformatAdUnitFacade adUnit;
@NonNull
private final OnFetchDemandResult listener;
OnCompleteListenerImpl(
@NonNull MultiformatAdUnitFacade adUnit,
@Nullable Object adObject,
@NonNull OnFetchDemandResult listener
) {
this.adObject = adObject;
this.adUnit = adUnit;
this.listener = listener;
}
@Override
public void onComplete(ResultCode resultCode, String message) {
notifyListener(resultCode, message);
}
@Override
public void onComplete(ResultCode resultCode, @Nullable Map<String, String> unmodifiableMap, @Nullable String message) {
notifyListener(resultCode, message);
}
private void notifyListener(ResultCode resultCode, String message) {
BidInfo bidInfo = BidInfo.create(resultCode, adUnit.getBidResponse(), adUnit.getConfiguration());
Util.saveCacheId(bidInfo.getNativeCacheId(), adObject);
listener.onComplete(bidInfo, message);
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/original/OnFetchDemandResult.java | package org.prebid.mobile.api.original;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.api.data.BidInfo;
public interface OnFetchDemandResult {
void onComplete(@NonNull BidInfo bidInfo, @Nullable String message);
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/original/PrebidAdUnit.java | package org.prebid.mobile.api.original;
import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MAX;
import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MIN;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.ResultCode;
import org.prebid.mobile.api.data.BidInfo;
public class PrebidAdUnit {
@NonNull
private final String configId;
@Nullable
private MultiformatAdUnitFacade adUnit;
public PrebidAdUnit(@NonNull String configId) {
this.configId = configId;
}
public void fetchDemand(
PrebidRequest request,
OnFetchDemandResult listener
) {
baseFetchDemand(request, null, listener);
}
public void fetchDemand(
Object adObject,
PrebidRequest request,
OnFetchDemandResult listener
) {
baseFetchDemand(request, adObject, listener);
}
public void setAutoRefreshInterval(
@IntRange(from = AUTO_REFRESH_DELAY_MIN / 1000, to = AUTO_REFRESH_DELAY_MAX / 1000) int seconds
) {
if (adUnit != null) {
adUnit.setAutoRefreshInterval(seconds);
}
}
public void resumeAutoRefresh() {
if (adUnit != null) {
adUnit.resumeAutoRefresh();
}
}
public void stopAutoRefresh() {
if (adUnit != null) {
adUnit.stopAutoRefresh();
}
}
public void destroy() {
if (adUnit != null) {
adUnit.destroy();
}
}
private void baseFetchDemand(
@Nullable PrebidRequest request,
@Nullable Object adObject,
@Nullable OnFetchDemandResult userListener
) {
if (userListener == null) {
LogUtil.error("Parameter OnFetchDemandResult in fetchDemand() must be not null.");
return;
}
if (request == null || requestDoesNotHaveAnyConfiguration(request)) {
userListener.onComplete(BidInfo.create(ResultCode.INVALID_PREBID_REQUEST_OBJECT, null, null), null);
return;
}
if (adUnit != null) {
adUnit.destroy();
}
adUnit = new MultiformatAdUnitFacade(configId, request);
OnCompleteListenerImpl innerListener = new OnCompleteListenerImpl(adUnit, adObject, userListener);
if (adObject != null) {
adUnit.fetchDemand(adObject, innerListener);
} else {
adUnit.fetchDemand(innerListener);
}
}
private boolean requestDoesNotHaveAnyConfiguration(PrebidRequest request) {
return request.getBannerParameters() == null &&
request.getVideoParameters() == null &&
request.getNativeParameters() == null;
}
} |
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/original/PrebidRequest.java | package org.prebid.mobile.api.original;
import org.jetbrains.annotations.Nullable;
import org.prebid.mobile.BannerParameters;
import org.prebid.mobile.ContentObject;
import org.prebid.mobile.DataObject;
import org.prebid.mobile.NativeParameters;
import org.prebid.mobile.VideoParameters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PrebidRequest {
@Nullable
private BannerParameters bannerParameters;
@Nullable
private VideoParameters videoParameters;
@Nullable
private NativeParameters nativeParameters;
private boolean isInterstitial = false;
private boolean isRewarded = false;
@Nullable
private String gpid;
@Nullable
private Map<String, Set<String>> extData;
@Nullable
private Set<String> extKeywords;
@Nullable
private ContentObject appContent;
@Nullable
private ArrayList<DataObject> userData;
public PrebidRequest() {
}
BannerParameters getBannerParameters() {
return bannerParameters;
}
public void setBannerParameters(BannerParameters bannerParameters) {
this.bannerParameters = bannerParameters;
}
VideoParameters getVideoParameters() {
return videoParameters;
}
public void setVideoParameters(VideoParameters videoParameters) {
this.videoParameters = videoParameters;
}
NativeParameters getNativeParameters() {
return nativeParameters;
}
public void setNativeParameters(NativeParameters nativeParameters) {
this.nativeParameters = nativeParameters;
}
boolean isInterstitial() {
return isInterstitial;
}
public void setInterstitial(boolean interstitial) {
this.isInterstitial = interstitial;
}
boolean isRewarded() {
return isRewarded;
}
public void setRewarded(boolean rewarded) {
if (rewarded) {
this.isInterstitial = true;
this.isRewarded = true;
}
}
@Nullable
String getGpid() {
return gpid;
}
public void setGpid(@Nullable String gpid) {
this.gpid = gpid;
}
@Nullable
ContentObject getAppContent() {
return appContent;
}
public void setAppContent(@Nullable ContentObject appContent) {
this.appContent = appContent;
}
@Nullable
Map<String, Set<String>> getExtData() {
return extData;
}
public void setExtData(@Nullable Map<String, Set<String>> extData) {
if (extData == null) {
this.extData = null;
return;
}
this.extData = new HashMap<>(extData);
}
@Nullable
Set<String> getExtKeywords() {
return extKeywords;
}
public void setExtKeywords(@Nullable Set<String> extKeywords) {
if (extKeywords == null) {
this.extKeywords = null;
return;
}
this.extKeywords = new HashSet<>(extKeywords);
}
@Nullable
ArrayList<DataObject> getUserData() {
return userData;
}
public void setUserData(@Nullable ArrayList<DataObject> userData) {
if (userData == null) {
this.userData = null;
return;
}
this.userData = new ArrayList<>(userData);
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/BannerView.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.ContentObject;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.PrebidMobile;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.BannerAdPosition;
import org.prebid.mobile.api.data.VideoPlacementType;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.listeners.BannerViewListener;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.core.R;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.interfaces.BannerEventHandler;
import org.prebid.mobile.rendering.bidding.interfaces.StandaloneBannerEventHandler;
import org.prebid.mobile.rendering.bidding.listeners.BannerEventListener;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import org.prebid.mobile.rendering.bidding.listeners.DisplayViewListener;
import org.prebid.mobile.rendering.bidding.loader.BidLoader;
import org.prebid.mobile.rendering.models.AdPosition;
import org.prebid.mobile.rendering.models.PlacementType;
import org.prebid.mobile.rendering.models.internal.VisibilityTrackerOption;
import org.prebid.mobile.rendering.models.ntv.NativeEventTracker;
import org.prebid.mobile.rendering.utils.broadcast.ScreenStateReceiver;
import org.prebid.mobile.rendering.utils.helpers.VisibilityChecker;
import org.prebid.mobile.rendering.views.webview.mraid.Views;
import java.util.Map;
import java.util.Set;
public class BannerView extends FrameLayout {
private final static String TAG = BannerView.class.getSimpleName();
private final AdUnitConfiguration adUnitConfig = new AdUnitConfiguration();
private BannerEventHandler eventHandler;
private String configId;
private DisplayView displayView;
private BidLoader bidLoader;
private BidResponse bidResponse;
private long minBidLatencyMs = 0;
private long bidStartMs = 0;
private final ScreenStateReceiver screenStateReceiver = new ScreenStateReceiver();
@Nullable private BannerViewListener bannerViewListener;
private int refreshIntervalSec = 0;
private boolean isPrimaryAdServerRequestInProgress;
private boolean adFailed;
private String nativeStylesCreative = null;
//region ==================== Listener implementation
private final DisplayViewListener displayViewListener = new DisplayViewListener() {
@Override
public void onAdLoaded() {
if (bannerViewListener != null) {
bannerViewListener.onAdLoaded(BannerView.this);
}
}
@Override
public void onAdDisplayed() {
if (bannerViewListener != null) {
bannerViewListener.onAdDisplayed(BannerView.this);
eventHandler.trackImpression();
}
}
@Override
public void onAdFailed(AdException exception) {
if (bannerViewListener != null) {
bannerViewListener.onAdFailed(BannerView.this, exception);
}
}
@Override
public void onAdClicked() {
if (bannerViewListener != null) {
bannerViewListener.onAdClicked(BannerView.this);
}
}
@Override
public void onAdClosed() {
if (bannerViewListener != null) {
bannerViewListener.onAdClosed(BannerView.this);
}
}
};
public void requestAd() {
isPrimaryAdServerRequestInProgress = true;
eventHandler.requestAdWithBid(getWinnerBid());
}
public void startTrackViewability() {
if (displayView != null) {
displayView.startTrackViewability();
}
}
private final BidRequesterListener bidRequesterListener = new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
bidResponse = response;
if (bannerViewListener != null) {
if (minBidLatencyMs > 0) {
long bidLatency = System.currentTimeMillis() - bidStartMs;
if (bidLatency < minBidLatencyMs) {
new Handler(Looper.getMainLooper()).postDelayed(() ->
bannerViewListener.onBidResponse(BannerView.this), minBidLatencyMs - bidLatency);
return;
}
}
bannerViewListener.onBidResponse(BannerView.this);
}
}
@Override
public void onError(AdException exception) {
bidResponse = null;
eventHandler.requestAdWithBid(null);
}
};
private final BannerEventListener bannerEventListener = new BannerEventListener() {
@Override
public void onPrebidSdkWin() {
markPrimaryAdRequestFinished();
if (isBidInvalid()) {
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"WinnerBid is null when executing onPrebidSdkWin."
));
return;
}
displayPrebidView();
}
@Override
public void onAdServerWin(View view) {
markPrimaryAdRequestFinished();
notifyAdLoadedListener();
displayAdServerView(view);
}
@Override
public void onAdFailed(AdException exception) {
markPrimaryAdRequestFinished();
if (isBidInvalid()) {
notifyErrorListener(exception);
return;
}
onPrebidSdkWin();
}
@Override
public void onAdClicked() {
if (bannerViewListener != null) {
bannerViewListener.onAdClicked(BannerView.this);
}
}
@Override
public void onAdClosed() {
if (bannerViewListener != null) {
bannerViewListener.onAdClosed(BannerView.this);
}
}
};
//endregion ==================== Listener implementation
/**
* Instantiates an BannerView with the ad details as an attribute.
*
* @param attrs includes:
* <p>
* adUnitID
* refreshIntervalInSec
*/
public BannerView(
@NonNull
Context context,
@Nullable
AttributeSet attrs
) {
super(context, attrs);
eventHandler = new StandaloneBannerEventHandler();
reflectAttrs(attrs);
init();
}
/**
* Instantiates an BannerView for the given configId and adSize.
*/
public BannerView(
Context context,
String configId,
AdSize size
) {
super(context);
eventHandler = new StandaloneBannerEventHandler();
this.configId = configId;
adUnitConfig.addSize(size);
init();
}
/**
* Instantiates an BannerView for the given configId with default size(specified by server)
*/
public BannerView(
Context context,
String configId
) {
super(context);
eventHandler = new StandaloneBannerEventHandler();
this.configId = configId;
init();
}
/**
* Instantiates an BannerView for GAM prebid integration.
*/
public BannerView(
Context context,
String configId,
@NonNull
BannerEventHandler eventHandler
) {
super(context);
this.eventHandler = eventHandler;
this.configId = configId;
init();
}
/**
* Executes ad loading if no request is running.
*/
public void loadAd() {
bidStartMs = System.currentTimeMillis();
if (bidLoader == null) {
LogUtil.error(TAG, "loadAd: Failed. BidLoader is not initialized.");
return;
}
if (isPrimaryAdServerRequestInProgress) {
LogUtil.debug(TAG, "loadAd: Skipped. Loading is in progress.");
return;
}
bidLoader.load();
}
/**
* Cancels BidLoader refresh timer.
*/
public void stopRefresh() {
if (bidLoader != null) {
bidLoader.cancelRefresh();
}
}
/**
* Cleans up resources when destroyed.
*/
public void destroy() {
if (eventHandler != null) {
eventHandler.destroy();
}
if (bidLoader != null) {
bidLoader.destroy();
}
if (displayView != null) {
displayView.destroy();
}
screenStateReceiver.unregister();
}
//region ==================== getters and setters
public void setAutoRefreshDelay(int seconds) {
if (!adUnitConfig.isAdType(AdFormat.BANNER)) {
LogUtil.info(TAG, "Autorefresh is available only for Banner ad type");
return;
}
if (seconds < 0) {
LogUtil.error(TAG, "setRefreshIntervalInSec: Failed. Refresh interval must be >= 0");
return;
}
adUnitConfig.setAutoRefreshDelay(seconds);
}
public int getAutoRefreshDelayInMs() {
return adUnitConfig.getAutoRefreshDelay();
}
public void addAdditionalSizes(AdSize... sizes) {
adUnitConfig.addSizes(sizes);
}
public Set<AdSize> getAdditionalSizes() {
return adUnitConfig.getSizes();
}
public void setBannerListener(BannerViewListener bannerListener) {
bannerViewListener = bannerListener;
}
public void setMinBidLatency(long minBidLatencyMs) {
this.minBidLatencyMs = minBidLatencyMs;
}
public void setVideoPlacementType(VideoPlacementType videoPlacement) {
adUnitConfig.setAdFormat(AdFormat.VAST);
final PlacementType placementType = VideoPlacementType.mapToPlacementType(videoPlacement);
adUnitConfig.setPlacementType(placementType);
}
@Nullable
public VideoPlacementType getVideoPlacementType() {
return VideoPlacementType.mapToVideoPlacementType(adUnitConfig.getPlacementTypeValue());
}
/**
* Sets BannerEventHandler for GAM prebid integration
*
* @param eventHandler instance of GamBannerEventHandler
*/
public void setEventHandler(BannerEventHandler eventHandler) {
this.eventHandler = eventHandler;
}
public void addContextData(
String key,
String value
) {
adUnitConfig.addContextData(key, value);
}
public void updateContextData(
String key,
Set<String> value
) {
adUnitConfig.addContextData(key, value);
}
public void removeContextData(String key) {
adUnitConfig.removeContextData(key);
}
public void clearContextData() {
adUnitConfig.clearContextData();
}
public Map<String, Set<String>> getContextDataDictionary() {
return adUnitConfig.getContextDataDictionary();
}
public void addContextKeyword(String keyword) {
adUnitConfig.addContextKeyword(keyword);
}
public void addContextKeywords(Set<String> keywords) {
adUnitConfig.addContextKeywords(keywords);
}
public void removeContextKeyword(String keyword) {
adUnitConfig.removeContextKeyword(keyword);
}
public Set<String> getContextKeywordsSet() {
return adUnitConfig.getContextKeywordsSet();
}
public void clearContextKeywords() {
adUnitConfig.clearContextKeywords();
}
public void setAdPosition(BannerAdPosition bannerAdPosition) {
final AdPosition adPosition = BannerAdPosition.mapToAdPosition(bannerAdPosition);
adUnitConfig.setAdPosition(adPosition);
}
public BannerAdPosition getAdPosition() {
return BannerAdPosition.mapToDisplayAdPosition(adUnitConfig.getAdPositionValue());
}
public void setPbAdSlot(String adSlot) {
adUnitConfig.setPbAdSlot(adSlot);
}
@Nullable
public String getPbAdSlot() {
return adUnitConfig.getPbAdSlot();
}
public AdUnitConfiguration getAdUnitConfig() {
return adUnitConfig;
}
public void addContent(ContentObject content) {
adUnitConfig.setAppContent(content);
}
//endregion ==================== getters and setters
private void reflectAttrs(AttributeSet attrs) {
if (attrs == null) {
LogUtil.debug(TAG, "reflectAttrs. No attributes provided.");
return;
}
TypedArray typedArray = getContext()
.getTheme()
.obtainStyledAttributes(attrs, R.styleable.BannerView, 0, 0);
try {
configId = typedArray.getString(R.styleable.BannerView_configId);
refreshIntervalSec = typedArray.getInt(R.styleable.BannerView_refreshIntervalSec, 0);
int width = typedArray.getInt(R.styleable.BannerView_adWidth, -1);
int height = typedArray.getInt(R.styleable.BannerView_adHeight, -1);
if (width >= 0 && height >= 0) {
adUnitConfig.addSize(new AdSize(width, height));
}
} finally {
typedArray.recycle();
}
}
private void init() {
initPrebidRenderingSdk();
initAdConfiguration();
initBidLoader();
screenStateReceiver.register(getContext());
}
private void initPrebidRenderingSdk() {
PrebidMobile.initializeSdk(getContext(), null);
}
private void initBidLoader() {
bidLoader = new BidLoader(getContext(), adUnitConfig, bidRequesterListener);
final VisibilityTrackerOption visibilityTrackerOption = new VisibilityTrackerOption(NativeEventTracker.EventType.IMPRESSION);
final VisibilityChecker visibilityChecker = new VisibilityChecker(visibilityTrackerOption);
bidLoader.setBidRefreshListener(() -> {
if (adFailed) {
adFailed = false;
return true;
}
final boolean isWindowVisibleToUser = screenStateReceiver.isScreenOn();
return visibilityChecker.isVisibleForRefresh(this) && isWindowVisibleToUser;
});
}
private void initAdConfiguration() {
adUnitConfig.setConfigId(configId);
adUnitConfig.setAutoRefreshDelay(refreshIntervalSec);
eventHandler.setBannerEventListener(bannerEventListener);
adUnitConfig.setAdFormat(AdFormat.BANNER);
adUnitConfig.addSizes(eventHandler.getAdSizeArray());
}
private void displayPrebidView() {
if (indexOfChild(displayView) != -1) {
displayView.destroy();
displayView = null;
}
removeAllViews();
final Pair<Integer, Integer> sizePair = bidResponse.getWinningBidWidthHeightPairDips(getContext());
displayView = new DisplayView(getContext(), displayViewListener, adUnitConfig, bidResponse);
addView(displayView);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)displayView.getLayoutParams();
params.gravity = Gravity.CENTER;
params.width = sizePair.first;
params.height = sizePair.second;
displayView.setLayoutParams(params);
}
private void displayAdServerView(View view) {
removeAllViews();
if (view == null) {
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"Failed to displayAdServerView. Provided view is null"
));
return;
}
Views.removeFromParent(view);
addView(view);
if (bannerViewListener != null) {
bannerViewListener.onAdDisplayed(BannerView.this);
}
}
private void markPrimaryAdRequestFinished() {
isPrimaryAdServerRequestInProgress = false;
}
private void notifyAdLoadedListener() {
if (bannerViewListener != null) {
bannerViewListener.onAdLoaded(BannerView.this);
}
}
private void notifyErrorListener(AdException exception) {
adFailed = true;
if (bannerViewListener != null) {
bannerViewListener.onAdFailed(BannerView.this, exception);
}
}
private boolean isBidInvalid() {
return bidResponse == null || bidResponse.getWinningBid() == null;
}
public BidResponse getBidResponse() {
return bidResponse;
}
//region ==================== HelperMethods for Unit Tests. Should be used only in tests
@VisibleForTesting
public final void setBidResponse(BidResponse response) {
bidResponse = response;
}
@VisibleForTesting
final Bid getWinnerBid() {
return bidResponse != null ? bidResponse.getWinningBid() : null;
}
@VisibleForTesting
final boolean isPrimaryAdServerRequestInProgress() {
return isPrimaryAdServerRequestInProgress;
}
//endregion ==================== HelperMethods for Unit Tests
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/BaseInterstitialAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.prebid.mobile.ContentObject;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.PrebidMobile;
import org.prebid.mobile.api.data.Position;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.display.InterstitialController;
import org.prebid.mobile.rendering.bidding.interfaces.InterstitialControllerListener;
import org.prebid.mobile.rendering.bidding.listeners.BidRequesterListener;
import org.prebid.mobile.rendering.bidding.loader.BidLoader;
import org.prebid.mobile.rendering.models.AdPosition;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.Set;
import static org.prebid.mobile.api.rendering.BaseInterstitialAdUnit.InterstitialAdUnitState.*;
public abstract class BaseInterstitialAdUnit {
private static final String TAG = BaseInterstitialAdUnit.class.getSimpleName();
protected AdUnitConfiguration adUnitConfig;
private BidLoader bidLoader;
private BidResponse bidResponse;
private InterstitialController interstitialController;
private InterstitialAdUnitState interstitialAdUnitState = READY_FOR_LOAD;
private final WeakReference<Context> weakContext;
private final BidRequesterListener bidRequesterListener = createBidRequesterListener();
private final InterstitialControllerListener controllerListener = createInterstitialControllerListener();
protected BaseInterstitialAdUnit(Context context) {
weakContext = new WeakReference<>(context);
}
abstract void requestAdWithBid(@Nullable Bid bid);
abstract void showGamAd();
abstract void notifyAdEventListener(AdListenerEvent adListenerEvent);
abstract void notifyErrorListener(AdException exception);
/**
* Executes ad loading if no request is running.
*/
public void loadAd() {
if (bidLoader == null) {
LogUtil.error(TAG, "loadAd: Failed. BidLoader is not initialized.");
return;
}
if (!isAdLoadAllowed()) {
LogUtil.debug(TAG, "loadAd: Skipped. InterstitialAdUnitState is: " + interstitialAdUnitState);
return;
}
bidLoader.load();
}
public InterstitialView getInterstitialView() {
if (interstitialController != null) {
return interstitialController.getBidInterstitialView();
}
return null;
}
/**
* @return true if auction winner was defined, false otherwise
*/
public boolean isLoaded() {
return isAuctionWinnerReadyToDisplay();
}
/**
* Executes interstitial display if auction winner is defined.
*/
public void show() {
if (!isAuctionWinnerReadyToDisplay()) {
LogUtil.debug(TAG, "show(): Ad is not yet ready for display!");
return;
}
switch (interstitialAdUnitState) {
case READY_TO_DISPLAY_GAM:
showGamAd();
break;
case READY_TO_DISPLAY_PREBID:
interstitialController.show();
break;
default:
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"show(): Encountered an invalid interstitialAdUnitState - " + interstitialAdUnitState
));
}
}
public void addContextData(
String key,
String value
) {
adUnitConfig.addContextData(key, value);
}
public void updateContextData(
String key,
Set<String> value
) {
adUnitConfig.addContextData(key, value);
}
public void removeContextData(String key) {
adUnitConfig.removeContextData(key);
}
public void clearContextData() {
adUnitConfig.clearContextData();
}
public Map<String, Set<String>> getContextDataDictionary() {
return adUnitConfig.getContextDataDictionary();
}
public void addContextKeyword(String keyword) {
adUnitConfig.addContextKeyword(keyword);
}
public void addContextKeywords(Set<String> keywords) {
adUnitConfig.addContextKeywords(keywords);
}
public void removeContextKeyword(String keyword) {
adUnitConfig.removeContextKeyword(keyword);
}
public Set<String> getContextKeywordsSet() {
return adUnitConfig.getContextKeywordsSet();
}
public void clearContextKeywords() {
adUnitConfig.clearContextKeywords();
}
@Nullable
public String getPbAdSlot() {
return adUnitConfig.getPbAdSlot();
}
public void setPbAdSlot(String adSlot) {
adUnitConfig.setPbAdSlot(adSlot);
}
/**
* Sets delay in seconds to show skip or close button.
*/
public void setSkipDelay(int secondsDelay) {
adUnitConfig.setSkipDelay(secondsDelay);
}
/**
* Sets skip button percentage size in range from 0.05 to 1.
* If value less than 0.05, size will be default.
*/
public void setSkipButtonArea(@FloatRange(from = 0, to = 1.0) double buttonArea) {
adUnitConfig.setSkipButtonArea(buttonArea);
}
/**
* Sets skip button position on the screen. Suitable values TOP_LEFT and TOP_RIGHT.
* Default value TOP_RIGHT.
*/
public void setSkipButtonPosition(Position skipButtonPosition) {
adUnitConfig.setSkipButtonPosition(skipButtonPosition);
}
public void setIsMuted(boolean isMuted) {
adUnitConfig.setIsMuted(isMuted);
}
public void setIsSoundButtonVisible(boolean isSoundButtonVisible) {
adUnitConfig.setIsSoundButtonVisible(isSoundButtonVisible);
}
public void setMaxVideoDuration(int seconds) {
adUnitConfig.setMaxVideoDuration(seconds);
}
/**
* Sets close button percentage size in range from 0.05 to 1.
* If value less than 0.05, size will be default.
*/
public void setCloseButtonArea(@FloatRange(from = 0, to = 1.0) double closeButtonArea) {
adUnitConfig.setCloseButtonArea(closeButtonArea);
}
/**
* Sets close button position on the screen. Suitable values TOP_LEFT and TOP_RIGHT.
* Default value TOP_RIGHT.
*/
public void setCloseButtonPosition(@Nullable Position closeButtonPosition) {
adUnitConfig.setCloseButtonPosition(closeButtonPosition);
}
/**
* Cleans up resources when destroyed.
*/
public void destroy() {
if (bidLoader != null) {
bidLoader.destroy();
}
if (interstitialController != null) {
interstitialController.destroy();
}
}
protected void init(AdUnitConfiguration adUnitConfiguration) {
adUnitConfig = adUnitConfiguration;
adUnitConfig.setAdPosition(AdPosition.FULLSCREEN);
initPrebidRenderingSdk();
initBidLoader();
initInterstitialController();
}
protected void loadPrebidAd() {
if (interstitialController == null) {
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"InterstitialController is not defined. Unable to process bid."
));
return;
}
interstitialController.loadAd(adUnitConfig, bidResponse);
}
@Nullable
protected Context getContext() {
return weakContext.get();
}
protected boolean isBidInvalid() {
return bidResponse == null || bidResponse.getWinningBid() == null;
}
protected void changeInterstitialAdUnitState(InterstitialAdUnitState state) {
interstitialAdUnitState = state;
}
private void initPrebidRenderingSdk() {
PrebidMobile.initializeSdk(getContext(), null);
}
private void initBidLoader() {
bidLoader = new BidLoader(getContext(), adUnitConfig, bidRequesterListener);
}
private void initInterstitialController() {
try {
interstitialController = new InterstitialController(getContext(), controllerListener);
} catch (AdException e) {
notifyErrorListener(e);
}
}
private Bid getWinnerBid() {
return bidResponse != null ? bidResponse.getWinningBid() : null;
}
public BidResponse getBidResponse() {
return bidResponse;
}
private boolean isAuctionWinnerReadyToDisplay() {
return interstitialAdUnitState == READY_TO_DISPLAY_PREBID || interstitialAdUnitState == READY_TO_DISPLAY_GAM;
}
private boolean isAdLoadAllowed() {
return interstitialAdUnitState == READY_FOR_LOAD;
}
@VisibleForTesting
final InterstitialAdUnitState getAdUnitState() {
return interstitialAdUnitState;
}
public void addContent(ContentObject content) {
adUnitConfig.setAppContent(content);
}
private BidRequesterListener createBidRequesterListener() {
return new BidRequesterListener() {
@Override
public void onFetchCompleted(BidResponse response) {
bidResponse = response;
changeInterstitialAdUnitState(LOADING);
requestAdWithBid(getWinnerBid());
}
@Override
public void onError(AdException exception) {
bidResponse = null;
requestAdWithBid(null);
}
};
}
private InterstitialControllerListener createInterstitialControllerListener() {
return new InterstitialControllerListener() {
@Override
public void onInterstitialReadyForDisplay() {
changeInterstitialAdUnitState(READY_TO_DISPLAY_PREBID);
notifyAdEventListener(AdListenerEvent.AD_LOADED);
}
@Override
public void onInterstitialClicked() {
notifyAdEventListener(AdListenerEvent.AD_CLICKED);
}
@Override
public void onInterstitialFailedToLoad(AdException exception) {
changeInterstitialAdUnitState(READY_FOR_LOAD);
notifyErrorListener(exception);
}
@Override
public void onInterstitialDisplayed() {
changeInterstitialAdUnitState(READY_FOR_LOAD);
notifyAdEventListener(AdListenerEvent.AD_DISPLAYED);
}
@Override
public void onInterstitialClosed() {
notifyAdEventListener(AdListenerEvent.AD_CLOSE);
notifyAdEventListener(AdListenerEvent.USER_RECEIVED_PREBID_REWARD);
}
};
}
enum AdListenerEvent {
AD_CLOSE,
AD_CLICKED,
AD_DISPLAYED,
AD_LOADED,
USER_RECEIVED_PREBID_REWARD // only for RewardedAdUnit
}
enum InterstitialAdUnitState {
READY_FOR_LOAD,
LOADING,
PREBID_LOADING,
READY_TO_DISPLAY_GAM,
READY_TO_DISPLAY_PREBID
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/DisplayView.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.display.BidResponseCache;
import org.prebid.mobile.rendering.bidding.listeners.DisplayViewListener;
import org.prebid.mobile.rendering.models.AdDetails;
import org.prebid.mobile.rendering.networking.WinNotifier;
import org.prebid.mobile.rendering.utils.broadcast.local.EventForwardingLocalBroadcastReceiver;
import org.prebid.mobile.rendering.utils.constants.IntentActions;
import org.prebid.mobile.rendering.views.AdViewManager;
import org.prebid.mobile.rendering.views.AdViewManagerListener;
import org.prebid.mobile.rendering.views.interstitial.InterstitialManager;
import org.prebid.mobile.rendering.views.video.VideoViewListener;
public class DisplayView extends FrameLayout {
private final static String TAG = DisplayView.class.getSimpleName();
private static final String CONTENT_DESCRIPTION_AD_VIEW = "adView";
private String impressionEventUrl;
private AdUnitConfiguration adUnitConfiguration;
private DisplayViewListener displayViewListener;
private InterstitialManager interstitialManager;
private AdViewManager adViewManager;
private VideoView videoView;
private EventForwardingLocalBroadcastReceiver eventForwardingReceiver;
private final EventForwardingLocalBroadcastReceiver.EventForwardingBroadcastListener broadcastListener = this::handleBroadcastAction;
private final AdViewManagerListener adViewManagerListener = new AdViewManagerListener() {
@Override
public void adLoaded(AdDetails adDetails) {
// for banner adViewManager.show() will be called automatically
notifyListenerLoaded();
}
@Override
public void viewReadyForImmediateDisplay(View creative) {
removeAllViews();
creative.setContentDescription(CONTENT_DESCRIPTION_AD_VIEW);
addView(creative);
notifyListenerDisplayed();
}
@Override
public void failedToLoad(AdException error) {
notifyListenerError(error);
}
@Override
public void creativeClicked(String url) {
notifyListenerClicked();
}
@Override
public void creativeInterstitialClosed() {
notifyListenerClose();
}
@Override
public void creativeCollapsed() {
notifyListenerClose();
}
};
private final VideoViewListener videoViewListener = new VideoViewListener() {
@Override
public void onLoaded(
@NonNull
VideoView videoAdView,
AdDetails adDetails
) {
videoAdView.setContentDescription(CONTENT_DESCRIPTION_AD_VIEW);
notifyListenerLoaded();
}
@Override
public void onLoadFailed(
@NonNull
VideoView videoAdView,
AdException error
) {
notifyListenerError(error);
}
@Override
public void onDisplayed(
@NonNull
VideoView videoAdView
) {
notifyListenerDisplayed();
}
@Override
public void onClickThroughOpened(
@NonNull
VideoView videoAdView
) {
notifyListenerClicked();
}
@Override
public void onClickThroughClosed(
@NonNull
VideoView videoAdView
) {
notifyListenerClose();
}
};
public DisplayView(
@NonNull
Context context,
DisplayViewListener listener,
@NonNull
AdUnitConfiguration adUnitConfiguration,
@NonNull
BidResponse response
) {
super(context);
interstitialManager = new InterstitialManager();
this.adUnitConfiguration = adUnitConfiguration;
displayViewListener = listener;
WinNotifier winNotifier = new WinNotifier();
winNotifier.notifyWin(response, () -> {
try {
adUnitConfiguration.modifyUsingBidResponse(response);
if (response.isVideo()) {
displayVideoAd(response);
} else {
displayHtmlAd(response);
}
impressionEventUrl = response.getImpressionEventUrl();
} catch (AdException e) {
notifyListenerError(e);
}
});
}
public DisplayView(
@NonNull
Context context,
DisplayViewListener listener,
@NonNull
AdUnitConfiguration adUnitConfiguration,
@NonNull
String responseId
) throws AdException {
this(context, listener, adUnitConfiguration, getBidResponseFromCache(responseId));
}
public void destroy() {
adUnitConfiguration = null;
displayViewListener = null;
interstitialManager = null;
if (videoView != null) {
videoView.destroy();
}
if (adViewManager != null) {
adViewManager.destroy();
adViewManager = null;
}
if (eventForwardingReceiver != null) {
eventForwardingReceiver.unregister(eventForwardingReceiver);
eventForwardingReceiver = null;
}
}
private void displayHtmlAd(BidResponse response) throws AdException {
adViewManager = new AdViewManager(getContext(), adViewManagerListener, this, interstitialManager);
adViewManager.loadBidTransaction(adUnitConfiguration, response);
eventForwardingReceiver = new EventForwardingLocalBroadcastReceiver(
adUnitConfiguration.getBroadcastId(),
broadcastListener
);
eventForwardingReceiver.register(getContext(), eventForwardingReceiver);
}
private void displayVideoAd(BidResponse response) throws AdException {
videoView = new VideoView(getContext(), adUnitConfiguration);
videoView.setVideoViewListener(videoViewListener);
videoView.setVideoPlayerClick(true);
videoView.loadAd(adUnitConfiguration, response);
addView(videoView);
}
private void notifyListenerError(AdException e) {
LogUtil.debug(TAG, "onAdFailed");
if (displayViewListener != null) {
displayViewListener.onAdFailed(e);
}
}
private void notifyListenerClicked() {
LogUtil.debug(TAG, "onAdClicked");
if (displayViewListener != null) {
displayViewListener.onAdClicked();
}
}
private void notifyListenerClose() {
LogUtil.debug(TAG, "onAdClosed");
if (displayViewListener != null) {
displayViewListener.onAdClosed();
}
}
private void notifyListenerDisplayed() {
LogUtil.debug(TAG, "onAdDisplayed");
if (displayViewListener != null) {
displayViewListener.onAdDisplayed();
}
}
private void notifyListenerLoaded() {
LogUtil.debug(TAG, "onAdLoaded");
if (displayViewListener != null) {
displayViewListener.onAdLoaded();
}
}
private void handleBroadcastAction(String action) {
if (IntentActions.ACTION_BROWSER_CLOSE.equals(action)) {
notifyListenerClose();
}
}
private static BidResponse getBidResponseFromCache(String id) throws AdException {
BidResponse cachedResponse = BidResponseCache.getInstance().popBidResponse(id);
if (cachedResponse == null) {
throw new AdException(AdException.INTERNAL_ERROR, "No cached bid response found");
}
return cachedResponse;
}
public void startTrackViewability() {
if (adViewManager != null) {
adViewManager.startTrackViewability();
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/InterstitialAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.data.AdUnitFormat;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.listeners.InterstitialAdUnitListener;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.interfaces.InterstitialEventHandler;
import org.prebid.mobile.rendering.bidding.interfaces.StandaloneInterstitialEventHandler;
import org.prebid.mobile.rendering.bidding.listeners.InterstitialEventListener;
import java.util.EnumSet;
import static org.prebid.mobile.api.rendering.BaseInterstitialAdUnit.InterstitialAdUnitState.READY_FOR_LOAD;
import static org.prebid.mobile.api.rendering.BaseInterstitialAdUnit.InterstitialAdUnitState.READY_TO_DISPLAY_GAM;
public class InterstitialAdUnit extends BaseInterstitialAdUnit {
private static final String TAG = InterstitialAdUnit.class.getSimpleName();
/**
* Handler that is responsible for requesting, displaying and destroying of
* primary ad (e.g. GAM). Also it tracks impression and sets listener.
*/
private final InterstitialEventHandler eventHandler;
/**
* Listener that must be applied to InterstitialEventHandler.
* It is responsible for onAdServerWin or onPrebidSdkWin.
* Also, onAdDisplayed, onAdFailed, onAdClosed.
*/
private final InterstitialEventListener interstitialEventListener = createEventListener();
/**
* Interstitial ad units events listener (like onAdLoaded, onAdFailed...)
*/
@Nullable private InterstitialAdUnitListener adUnitEventsListener;
/**
* Instantiates an HTML InterstitialAdUnit for the given configurationId.
*/
public InterstitialAdUnit(
Context context,
String configId
) {
this(context, configId, EnumSet.of(AdUnitFormat.DISPLAY), null);
}
/**
* Instantiates an InterstitialAdUnit for the given configurationId and adUnitType.
*/
public InterstitialAdUnit(
Context context,
String configId,
EnumSet<AdUnitFormat> adUnitFormats
) {
this(context, configId, adUnitFormats, null);
}
/**
* Instantiates an InterstitialAdUnit for HTML GAM prebid integration.
*/
public InterstitialAdUnit(
Context context,
String configId,
InterstitialEventHandler eventHandler
) {
this(context, configId, EnumSet.of(AdUnitFormat.DISPLAY), eventHandler);
}
/**
* Instantiates an InterstitialAdUnit for GAM prebid integration with given adUnitType.
*/
public InterstitialAdUnit(
Context context,
String configId,
@NonNull EnumSet<AdUnitFormat> adUnitFormats,
InterstitialEventHandler eventHandler
) {
super(context);
if (eventHandler == null) {
this.eventHandler = createStandaloneEventHandler();
} else {
this.eventHandler = eventHandler;
}
this.eventHandler.setInterstitialEventListener(interstitialEventListener);
AdUnitConfiguration adUnitConfiguration = new AdUnitConfiguration();
adUnitConfiguration.setConfigId(configId);
adUnitConfiguration.setAdUnitFormats(adUnitFormats);
init(adUnitConfiguration);
}
@Override
void showGamAd() {
eventHandler.show();
}
@Override
void requestAdWithBid(@Nullable Bid bid) {
eventHandler.requestAdWithBid(bid);
}
@Override
void notifyAdEventListener(AdListenerEvent adListenerEvent) {
if (adUnitEventsListener == null) {
LogUtil.debug(
TAG,
"notifyAdEventListener: Failed. AdUnitListener is null. Passed listener event: " + adListenerEvent
);
return;
}
switch (adListenerEvent) {
case AD_CLOSE:
adUnitEventsListener.onAdClosed(InterstitialAdUnit.this);
break;
case AD_LOADED:
adUnitEventsListener.onAdLoaded(InterstitialAdUnit.this);
break;
case AD_DISPLAYED:
adUnitEventsListener.onAdDisplayed(InterstitialAdUnit.this);
break;
case AD_CLICKED:
adUnitEventsListener.onAdClicked(InterstitialAdUnit.this);
break;
}
}
@Override
void notifyErrorListener(AdException exception) {
if (adUnitEventsListener != null) {
adUnitEventsListener.onAdFailed(InterstitialAdUnit.this, exception);
}
}
public void setInterstitialAdUnitListener(@Nullable InterstitialAdUnitListener adUnitEventsListener) {
this.adUnitEventsListener = adUnitEventsListener;
}
public void setMinSizePercentage(AdSize minSizePercentage) {
adUnitConfig.setMinSizePercentage(minSizePercentage);
}
public void destroy() {
super.destroy();
if (eventHandler != null) {
eventHandler.destroy();
}
}
private StandaloneInterstitialEventHandler createStandaloneEventHandler() {
return new StandaloneInterstitialEventHandler();
}
private InterstitialEventListener createEventListener() {
return new InterstitialEventListener() {
@Override
public void onPrebidSdkWin() {
if (isBidInvalid()) {
changeInterstitialAdUnitState(READY_FOR_LOAD);
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"WinnerBid is null when executing onPrebidSdkWin."
));
return;
}
loadPrebidAd();
}
@Override
public void onAdServerWin() {
changeInterstitialAdUnitState(READY_TO_DISPLAY_GAM);
notifyAdEventListener(AdListenerEvent.AD_LOADED);
}
@Override
public void onAdFailed(AdException exception) {
if (isBidInvalid()) {
changeInterstitialAdUnitState(READY_FOR_LOAD);
notifyErrorListener(exception);
return;
}
onPrebidSdkWin();
}
@Override
public void onAdClosed() {
notifyAdEventListener(AdListenerEvent.AD_CLOSE);
}
@Override
public void onAdDisplayed() {
changeInterstitialAdUnitState(READY_FOR_LOAD);
notifyAdEventListener(AdListenerEvent.AD_DISPLAYED);
}
};
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/InterstitialView.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import android.content.res.Configuration;
import android.util.Log;
import android.view.View;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.core.R;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.bidding.interfaces.InterstitialViewListener;
import org.prebid.mobile.rendering.interstitial.DialogEventListener;
import org.prebid.mobile.rendering.models.AdDetails;
import org.prebid.mobile.rendering.models.internal.InternalFriendlyObstruction;
import org.prebid.mobile.rendering.utils.constants.IntentActions;
import org.prebid.mobile.rendering.utils.helpers.InsetsUtils;
import org.prebid.mobile.rendering.views.AdViewManager;
import org.prebid.mobile.rendering.views.AdViewManagerListener;
import org.prebid.mobile.rendering.views.base.BaseAdView;
import org.prebid.mobile.rendering.views.interstitial.InterstitialVideo;
import java.util.Arrays;
import java.util.List;
public class InterstitialView extends BaseAdView {
private static final String TAG = InterstitialView.class.getSimpleName();
private InterstitialViewListener listener;
protected InterstitialVideo interstitialVideo;
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
List<View> views = Arrays.asList(
findViewById(R.id.iv_close_interstitial),
findViewById(R.id.iv_skip),
findViewById(R.id.rl_count_down),
findViewById(R.id.tv_learn_more)
);
for (View view : views) {
InsetsUtils.resetMargins(view);
InsetsUtils.addCutoutAndNavigationInsets(view);
}
}
//region ========== Listener Area
private final AdViewManagerListener onAdViewManagerListener = new AdViewManagerListener() {
@Override
public void adLoaded(final AdDetails adDetails) {
listener.onAdLoaded(InterstitialView.this, adDetails);
}
@Override
public void viewReadyForImmediateDisplay(View view) {
if (adViewManager.isNotShowingEndCard()) {
listener.onAdDisplayed(InterstitialView.this);
}
removeAllViews();
addView(view);
}
@Override
public void failedToLoad(AdException error) {
notifyErrorListeners(error);
}
@Override
public void adCompleted() {
listener.onAdCompleted(InterstitialView.this);
if (interstitialVideo != null && interstitialVideo.shouldShowCloseButtonOnComplete()) {
interstitialVideo.changeCloseViewVisibility(View.VISIBLE);
}
}
@Override
public void creativeClicked(String url) {
listener.onAdClicked(InterstitialView.this);
}
@Override
public void creativeInterstitialClosed() {
LogUtil.debug(TAG, "interstitialAdClosed");
handleActionClose();
}
};
//endregion ========== Listener Area
public InterstitialView(Context context) throws AdException {
super(context);
init();
}
public void setPubBackGroundOpacity(float opacity) {
interstitialManager.getInterstitialDisplayProperties().setPubBackGroundOpacity(opacity);
}
public void loadAd(
AdUnitConfiguration adUnitConfiguration,
BidResponse bidResponse
) {
adViewManager.loadBidTransaction(adUnitConfiguration, bidResponse);
}
public void setInterstitialViewListener(InterstitialViewListener listener) {
this.listener = listener;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (interstitialVideo != null) {
if (!hasWindowFocus) {
interstitialVideo.pauseVideo();
} else {
interstitialVideo.resumeVideo();
}
}
}
@Override
public void destroy() {
// Because user can click back, even before the adview is created.
// so, activity's destroy() calling adview's destry should not crash
super.destroy();
if (interstitialVideo != null) {
interstitialVideo.hide();
interstitialVideo.cancel();
interstitialVideo.removeViews();
}
}
public void showAsInterstitialFromRoot() {
try {
interstitialManager.configureInterstitialProperties(adViewManager.getAdConfiguration());
interstitialManager.displayAdViewInInterstitial(getContext(), InterstitialView.this);
} catch (final Exception e) {
LogUtil.error(TAG, "Interstitial failed to show:" + Log.getStackTraceString(e));
notifyErrorListeners(new AdException(AdException.INTERNAL_ERROR, e.getMessage()));
}
}
public void showVideoAsInterstitial() {
try {
final AdUnitConfiguration adConfiguration = adViewManager.getAdConfiguration();
interstitialManager.configureInterstitialProperties(adConfiguration);
interstitialVideo = new InterstitialVideo(
getContext(),
InterstitialView.this,
interstitialManager,
adConfiguration
);
interstitialVideo.setHasEndCard(adViewManager.hasNextCreative());
interstitialVideo.setDialogListener(this::handleDialogEvent);
interstitialVideo.show();
} catch (final Exception e) {
LogUtil.error(TAG, "Video interstitial failed to show:" + Log.getStackTraceString(e));
notifyErrorListeners(new AdException(AdException.INTERNAL_ERROR, e.getMessage()));
}
}
public void closeInterstitialVideo() {
if (interstitialVideo != null) {
if (interstitialVideo.isShowing()) {
interstitialVideo.close();
}
interstitialVideo = null;
}
}
@Override
protected void init() throws AdException {
try {
super.init();
setAdViewManagerValues();
registerEventBroadcast();
} catch (Exception e) {
throw new AdException(AdException.INIT_ERROR, "AdView initialization failed: " + Log.getStackTraceString(e));
}
}
@Override
protected void notifyErrorListeners(final AdException adException) {
if (listener != null) {
listener.onAdFailed(InterstitialView.this, adException);
}
}
@Override
protected void handleBroadcastAction(String action) {
if (IntentActions.ACTION_BROWSER_CLOSE.equals(action)) {
listener.onAdClickThroughClosed(InterstitialView.this);
}
}
protected void setAdViewManagerValues() throws AdException {
adViewManager = new AdViewManager(getContext(), onAdViewManagerListener, this, interstitialManager);
AdUnitConfiguration adConfiguration = adViewManager.getAdConfiguration();
adConfiguration.setAutoRefreshDelay(0);
}
protected InternalFriendlyObstruction[] formInterstitialObstructionsArray() {
InternalFriendlyObstruction[] obstructionArray = new InternalFriendlyObstruction[5];
View closeInterstitial = findViewById(R.id.iv_close_interstitial);
View skipInterstitial = findViewById(R.id.iv_skip);
View countDownTimer = findViewById(R.id.rl_count_down);
View actionButton = findViewById(R.id.tv_learn_more);
obstructionArray[0] = new InternalFriendlyObstruction(closeInterstitial, InternalFriendlyObstruction.Purpose.CLOSE_AD, null);
obstructionArray[1] = new InternalFriendlyObstruction(skipInterstitial, InternalFriendlyObstruction.Purpose.CLOSE_AD, null);
obstructionArray[2] = new InternalFriendlyObstruction(countDownTimer, InternalFriendlyObstruction.Purpose.OTHER, "CountDownTimer");
obstructionArray[3] = new InternalFriendlyObstruction(actionButton, InternalFriendlyObstruction.Purpose.OTHER, "Action button");
View dialogRoot = closeInterstitial.getRootView();
View navigationBar = dialogRoot.findViewById(android.R.id.navigationBarBackground);
obstructionArray[4] = new InternalFriendlyObstruction(navigationBar, InternalFriendlyObstruction.Purpose.OTHER, "Bottom navigation bar");
return obstructionArray;
}
private void handleDialogEvent(DialogEventListener.EventType eventType) {
if (eventType == DialogEventListener.EventType.SHOWN) {
adViewManager.addObstructions((formInterstitialObstructionsArray()));
} else if (eventType == DialogEventListener.EventType.CLOSED) {
handleActionClose();
} else if (eventType == DialogEventListener.EventType.MUTE) {
adViewManager.mute();
} else if (eventType == DialogEventListener.EventType.UNMUTE) {
adViewManager.unmute();
}
}
private void handleActionClose() {
if (adViewManager.isInterstitialClosed()) {
adViewManager.trackCloseEvent();
return;
}
adViewManager.resetTransactionState();
listener.onAdClosed(InterstitialView.this);
}
public AdViewManager getAdManager() {
return adViewManager;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/RewardedAdUnit.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import androidx.annotation.Nullable;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.listeners.RewardedAdUnitListener;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.interfaces.RewardedEventHandler;
import org.prebid.mobile.rendering.bidding.interfaces.StandaloneRewardedVideoEventHandler;
import org.prebid.mobile.rendering.bidding.listeners.RewardedVideoEventListener;
public class RewardedAdUnit extends BaseInterstitialAdUnit {
private static final String TAG = RewardedAdUnit.class.getSimpleName();
private final RewardedEventHandler eventHandler;
@Nullable private RewardedAdUnitListener rewardedAdUnitListener;
@Nullable private Object userReward;
//region ==================== Listener implementation
private final RewardedVideoEventListener eventListener = new RewardedVideoEventListener() {
@Override
public void onPrebidSdkWin() {
if (isBidInvalid()) {
changeInterstitialAdUnitState(InterstitialAdUnitState.READY_FOR_LOAD);
notifyErrorListener(new AdException(
AdException.INTERNAL_ERROR,
"WinnerBid is null when executing onPrebidSdkWin."
));
return;
}
loadPrebidAd();
}
@Override
public void onAdServerWin(Object userReward) {
RewardedAdUnit.this.userReward = userReward;
changeInterstitialAdUnitState(InterstitialAdUnitState.READY_TO_DISPLAY_GAM);
notifyAdEventListener(AdListenerEvent.AD_LOADED);
}
@Override
public void onAdFailed(AdException exception) {
if (isBidInvalid()) {
changeInterstitialAdUnitState(InterstitialAdUnitState.READY_FOR_LOAD);
notifyErrorListener(exception);
return;
}
onPrebidSdkWin();
}
@Override
public void onAdClicked() {
notifyAdEventListener(AdListenerEvent.AD_CLICKED);
}
@Override
public void onAdClosed() {
notifyAdEventListener(AdListenerEvent.AD_CLOSE);
}
@Override
public void onAdDisplayed() {
changeInterstitialAdUnitState(InterstitialAdUnitState.READY_FOR_LOAD);
notifyAdEventListener(AdListenerEvent.AD_DISPLAYED);
}
@Override
public void onUserEarnedReward() {
if (rewardedAdUnitListener != null) {
rewardedAdUnitListener.onUserEarnedReward(RewardedAdUnit.this);
}
}
};
//endregion ==================== Listener implementation
public RewardedAdUnit(
Context context,
String configId,
RewardedEventHandler eventHandler
) {
super(context);
this.eventHandler = eventHandler;
this.eventHandler.setRewardedEventListener(eventListener);
AdUnitConfiguration adUnitConfiguration = new AdUnitConfiguration();
adUnitConfiguration.setConfigId(configId);
adUnitConfiguration.setAdFormat(AdFormat.VAST);
adUnitConfiguration.setRewarded(true);
init(adUnitConfiguration);
}
public RewardedAdUnit(
Context context,
String configId
) {
this(context, configId, new StandaloneRewardedVideoEventHandler());
}
@Override
public void loadAd() {
super.loadAd();
userReward = null;
}
@Override
public void destroy() {
super.destroy();
if (eventHandler != null) {
eventHandler.destroy();
}
}
//region ==================== getters and setters
public void setRewardedAdUnitListener(
@Nullable
RewardedAdUnitListener rewardedAdUnitListener
) {
this.rewardedAdUnitListener = rewardedAdUnitListener;
}
@Nullable
public Object getUserReward() {
return userReward;
}
//endregion ==================== getters and setters
@Override
void requestAdWithBid(
@Nullable
Bid bid
) {
eventHandler.requestAdWithBid(bid);
}
@Override
void showGamAd() {
eventHandler.show();
}
@Override
void notifyAdEventListener(AdListenerEvent adListenerEvent) {
if (rewardedAdUnitListener == null) {
LogUtil.debug(
TAG,
"notifyAdEventListener: Failed. AdUnitListener is null. Passed listener event: " + adListenerEvent
);
return;
}
switch (adListenerEvent) {
case AD_CLOSE:
rewardedAdUnitListener.onAdClosed(RewardedAdUnit.this);
break;
case AD_LOADED:
rewardedAdUnitListener.onAdLoaded(RewardedAdUnit.this);
break;
case AD_DISPLAYED:
rewardedAdUnitListener.onAdDisplayed(RewardedAdUnit.this);
break;
case AD_CLICKED:
rewardedAdUnitListener.onAdClicked(RewardedAdUnit.this);
break;
case USER_RECEIVED_PREBID_REWARD:
rewardedAdUnitListener.onUserEarnedReward(RewardedAdUnit.this);
break;
}
}
@Override
void notifyErrorListener(AdException exception) {
if (rewardedAdUnitListener != null) {
rewardedAdUnitListener.onAdFailed(RewardedAdUnit.this, exception);
}
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/VideoView.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import androidx.core.content.ContextCompat;
import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.models.AdDetails;
import org.prebid.mobile.rendering.models.CreativeVisibilityTracker;
import org.prebid.mobile.rendering.models.internal.InternalFriendlyObstruction;
import org.prebid.mobile.rendering.models.internal.VisibilityTrackerOption;
import org.prebid.mobile.rendering.models.internal.VisibilityTrackerResult;
import org.prebid.mobile.rendering.models.ntv.NativeEventTracker;
import org.prebid.mobile.rendering.utils.constants.IntentActions;
import org.prebid.mobile.rendering.utils.helpers.Utils;
import org.prebid.mobile.rendering.video.VideoCreativeView;
import org.prebid.mobile.rendering.views.AdViewManager;
import org.prebid.mobile.rendering.views.AdViewManagerListener;
import org.prebid.mobile.rendering.views.base.BaseAdView;
import org.prebid.mobile.rendering.views.video.VideoViewListener;
import org.prebid.mobile.rendering.views.webview.mraid.Views;
public class VideoView extends BaseAdView {
private final static String TAG = VideoView.class.getSimpleName();
private VideoViewListener listener;
private CreativeVisibilityTracker visibilityTracker;
private final CreativeVisibilityTracker.VisibilityTrackerListener visibilityTrackerListener = this::handleVisibilityChange;
private State videoViewState = State.UNDEFINED;
private boolean enableVideoPlayerClick;
private boolean enableAutoPlay = true;
//region ========== Listener Area
private final AdViewManagerListener onAdViewManagerListener = new AdViewManagerListener() {
@Override
public void adLoaded(final AdDetails adDetails) {
listener.onLoaded(VideoView.this, adDetails);
changeState(State.PLAYBACK_NOT_STARTED);
if (enableAutoPlay) {
startVisibilityTracking();
}
}
@Override
public void viewReadyForImmediateDisplay(View view) {
if (adViewManager.isNotShowingEndCard()) {
listener.onDisplayed(VideoView.this);
}
removeAllViews();
if (adViewManager.hasEndCard()) {
showEndCardCreative(view);
} else {
showVideoCreative(view);
}
}
@Override
public void failedToLoad(AdException error) {
notifyErrorListeners(error);
}
@Override
public void videoCreativePlaybackFinished() {
stopVisibilityTracking();
changeState(State.PLAYBACK_FINISHED);
listener.onPlayBackCompleted(VideoView.this);
if (adViewManager.isNotShowingEndCard()) {
showWatchAgain();
}
}
@Override
public void creativeClicked(String url) {
listener.onClickThroughOpened(VideoView.this);
}
@Override
public void creativeMuted() {
listener.onVideoMuted();
}
@Override
public void creativeUnMuted() {
listener.onVideoUnMuted();
}
@Override
public void creativePaused() {
listener.onPlaybackPaused();
}
@Override
public void creativeResumed() {
listener.onPlaybackResumed();
}
};
//endregion ========== Listener Area
protected VideoView(Context context) throws AdException {
super(context);
init();
}
public VideoView(
Context context,
AdUnitConfiguration adUnitConfiguration
) throws AdException {
super(context);
prepareAdConfiguration(adUnitConfiguration);
init();
}
void loadAd(
AdUnitConfiguration adUnitConfiguration,
BidResponse bidResponse
) {
adViewManager.loadBidTransaction(adUnitConfiguration, bidResponse);
}
public void loadAd(
AdUnitConfiguration adConfiguration,
String vastXml
) {
stopVisibilityTracking();
changeState(State.UNDEFINED);
adViewManager.loadVideoTransaction(adConfiguration, vastXml);
}
@Override
public void destroy() {
super.destroy();
stopVisibilityTracking();
// if (videoDialog != null) {
// videoDialog.hide();
// videoDialog.cancel();
// videoDialog = null;
// }
}
public void mute(boolean enabled) {
if (enabled) {
adViewManager.mute();
} else {
adViewManager.unmute();
}
}
public void setVideoViewListener(VideoViewListener listener) {
this.listener = listener;
}
public void setVideoPlayerClick(boolean enable) {
enableVideoPlayerClick = enable;
}
public void setAutoPlay(boolean enable) {
enableAutoPlay = enable;
if (!enable) {
stopVisibilityTracking();
}
}
public void pause() {
if (!canPause()) {
LogUtil.debug(TAG, "pause() can't pause " + videoViewState);
return;
}
changeState(State.PAUSED_BY_USER);
adViewManager.pause();
}
public void resume() {
if (!canResume()) {
LogUtil.debug(TAG, "resume() can't resume " + videoViewState);
return;
}
changeState(State.PLAYING);
adViewManager.resume();
}
public void play() {
if (!canPlay()) {
LogUtil.debug(TAG, "play() can't play " + videoViewState);
return;
}
changeState(State.PLAYING);
adViewManager.show();
}
@Override
protected void init() throws AdException {
try {
super.init();
setAdViewManagerValues();
setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.black));
registerEventBroadcast();
} catch (Exception e) {
throw new AdException(AdException.INIT_ERROR, "VideoAdView initialization failed: " + Log.getStackTraceString(e));
}
}
@Override
protected void handleBroadcastAction(String action) {
switch (action) {
case IntentActions.ACTION_BROWSER_CLOSE:
listener.onClickThroughClosed(VideoView.this);
break;
}
}
protected void setAdViewManagerValues() throws AdException {
adViewManager = new AdViewManager(getContext(), onAdViewManagerListener, this, interstitialManager);
}
@Override
protected void handleWindowFocusChange(boolean hasWindowFocus) {
LogUtil.debug(TAG, "handleWindowFocusChange() called with: hasWindowFocus = [" + hasWindowFocus + "]");
// visibility checker will handle resume
if (enableAutoPlay) {
return;
}
handlePlaybackBasedOnVisibility(hasWindowFocus);
}
@Override
public void notifyErrorListeners(final AdException adException) {
listener.onLoadFailed(VideoView.this, adException);
}
private void prepareAdConfiguration(AdUnitConfiguration adUnitConfiguration) {
adUnitConfiguration.setAutoRefreshDelay(0);
adUnitConfiguration.setBuiltInVideo(true);
adUnitConfiguration.setVideoInitialVolume(0.0f);
}
private void showVideoCreative(View view) {
VideoCreativeView videoCreativeView = (VideoCreativeView) view;
if (enableVideoPlayerClick) {
videoCreativeView.enableVideoPlayerClick();
}
videoCreativeView.showVolumeControls();
addVideoControlObstruction(videoCreativeView.getVolumeControlView(), "Volume button");
addView(view);
}
private void showEndCardCreative(View creativeView) {
// if (isFullScreen()) {
// videoDialog.showBannerCreative(creativeView);
// }
// else {
Views.removeFromParent(creativeView);
FrameLayout.LayoutParams layoutParams = new LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
);
creativeView.setLayoutParams(layoutParams);
addView(creativeView);
// }
}
private void showWatchAgain() {
View watchAgainButton = Utils.createWatchAgainView(getContext());
if (watchAgainButton == null) {
LogUtil.debug(TAG, "showWatchAgain: Failed. WatchAgainView is null");
return;
}
addVideoControlObstruction(watchAgainButton, "WatchAgain button");
Views.removeFromParent(watchAgainButton);
watchAgainButton.setOnClickListener(v -> {
changeState(State.PLAYBACK_NOT_STARTED);
startVisibilityTracking();
});
// if (isFullScreen()) {
// videoDialog.dismiss();
// }
addView(watchAgainButton);
}
private void addVideoControlObstruction(
View view,
String description
) {
if (view == null) {
return;
}
InternalFriendlyObstruction obstruction = new InternalFriendlyObstruction(
view,
InternalFriendlyObstruction.Purpose.VIDEO_CONTROLS,
description
);
adViewManager.addObstructions(obstruction);
}
private void startVisibilityTracking() {
stopVisibilityTracking();
final VisibilityTrackerOption visibilityTrackerOption = new VisibilityTrackerOption(NativeEventTracker.EventType.IMPRESSION);
visibilityTracker = new CreativeVisibilityTracker(
this,
visibilityTrackerOption,
true
);
visibilityTracker.setVisibilityTrackerListener(visibilityTrackerListener);
visibilityTracker.startVisibilityCheck(getContext());
}
private void stopVisibilityTracking() {
if (visibilityTracker != null) {
visibilityTracker.stopVisibilityCheck();
}
}
private void handleVisibilityChange(VisibilityTrackerResult result) {
final boolean isVisible = result.isVisible();
if (isVisible && canPlay()) {
play();
LogUtil.debug(TAG, "handleVisibilityChange: auto show " + videoViewState);
return;
}
handlePlaybackBasedOnVisibility(isVisible);
}
private void handlePlaybackBasedOnVisibility(boolean isVisible) {
if (!isVisible && canPause()) {
adViewManager.pause();
changeState(State.PAUSED_AUTO);
LogUtil.debug(TAG, "handleVisibilityChange: auto pause " + videoViewState);
} else if (isVisible && isInState(State.PAUSED_AUTO)) {
adViewManager.resume();
changeState(State.PLAYING);
LogUtil.debug(TAG, "handleVisibilityChange: auto resume " + videoViewState);
}
}
private void changeState(State undefined) {
videoViewState = undefined;
}
private boolean canPlay() {
return isInState(State.PLAYBACK_NOT_STARTED);
}
private boolean canPause() {
return isInState(State.PLAYING);
}
private boolean canResume() {
return isInState(State.PAUSED_AUTO) || isInState(State.PAUSED_BY_USER);
}
private boolean isInState(State state) {
return videoViewState == state;
}
enum State {
UNDEFINED,
PLAYBACK_NOT_STARTED,
PLAYING,
PAUSED_BY_USER,
PAUSED_AUTO,
PLAYBACK_FINISHED
}
// private VideoDialog videoDialog;
// private ViewParent viewParentBeforeExpand;
// private ViewGroup.LayoutParams layoutParamsBeforeExpand;
// private final VideoDialogListener videoDialogListener = new VideoDialogListener() {
// @Override
// public void onVideoDialogClosed() {
// if (adViewManager.isInterstitialClosed()) {
// adViewManager.trackCloseEvent();
// return;
// }
// adViewManager.resetTransactionState(); //?
//
// listener.adInterstitialDidClose(VideoView.this);
// }
// };
// private void resetViewToInitialState() {
// videoDialog = null;
// VideoView videoAdView = VideoView.this;
//
// adViewManager.returnFromVideo(videoAdView);
//
// removeView(findViewById(R.id.iv_close_interstitial));
//
// Views.removeFromParent(videoAdView);
//
// if (layoutParamsBeforeExpand != null) {
// setLayoutParams(layoutParamsBeforeExpand);
// }
//
// if (viewParentBeforeExpand instanceof ViewGroup) {
// ((ViewGroup) viewParentBeforeExpand).addView(videoAdView);
// }
// }
//
// @VisibleForTesting
// protected void createDialog(Context context, final VideoCreativeView view) {
// viewParentBeforeExpand = getParent();
// layoutParamsBeforeExpand = getLayoutParams();
//
// Views.removeFromParent(this);
//
// videoDialog = new VideoDialog(context, view, adViewManager, interstitialManager, this);
// videoDialog.setOnDismissListener(new VideoView.VideoDialogDismissListener(this));
// videoDialog.setVideoDialogListener(videoDialogListener);
// videoDialog.show();
// }
// private void showFullScreen() {
// View currentView = getChildAt(0);
// if (adViewManager.canShowFullScreen() && videoDialog == null && currentView instanceof VideoCreativeView) {
// createDialog(getContext(), (VideoCreativeView) currentView);
// }
// }
//
// private boolean checkForWatchAgain() {
// return findViewById(R.id.btn_watch_again) != null;
// }
//
// private boolean isFullScreen() {
// return videoDialog != null && videoDialog.isShowing();
// }
// protected static class VideoDialogDismissListener implements DialogInterface.OnDismissListener {
// private final WeakReference<VideoView> weakVideoAdView;
//
// public VideoDialogDismissListener(VideoView videoDialog) {
// weakVideoAdView = new WeakReference<>(videoDialog);
// }
//
// @Override
// public void onDismiss(DialogInterface dialog) {
// VideoView videoAdView = weakVideoAdView.get();
// if (videoAdView == null) {
// Log.debug(TAG, "VideoDialog.onDismiss(): Unable to perform dismiss action. VideoAdView is null");
// return;
// }
// videoAdView.resetViewToInitialState();
// }
// }
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/listeners/BannerViewListener.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering.listeners;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.BannerView;
/**
* Listener interface representing BannerView events.
* All methods will be invoked on the main thread.
*/
public interface BannerViewListener {
/**
* Executed when the bid response is received.
*
* @param bannerView view of the corresponding event.
*/
void onBidResponse(BannerView bannerView);
/**
* Executed when the ad is loaded and is ready for display.
*
* @param bannerView view of the corresponding event.
*/
void onAdLoaded(BannerView bannerView);
/**
* Executed when the ad is displayed on screen.
*
* @param bannerView view of the corresponding event.
*/
void onAdDisplayed(BannerView bannerView);
/**
* Executed when an error is encountered on initialization / loading or display step.
*
* @param bannerView view of the corresponding event.
* @param exception exception containing detailed message and error type.
*/
void onAdFailed(BannerView bannerView, AdException exception);
/**
* Executed when bannerView is clicked.
*
* @param bannerView view of the corresponding event.
*/
void onAdClicked(BannerView bannerView);
/**
* Executed when modal window (e.g. browser) on top of bannerView is closed.
*
* @param bannerView view of the corresponding event.
*/
void onAdClosed(BannerView bannerView);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/listeners/InterstitialAdUnitListener.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering.listeners;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.InterstitialAdUnit;
/**
* Listener interface representing InterstitialAdUnit events.
* All methods will be invoked on the main thread.
*/
public interface InterstitialAdUnitListener {
/**
* Executed when the ad is loaded and is ready for display.
*
* @param interstitialAdUnit view of the corresponding event.
*/
void onAdLoaded(InterstitialAdUnit interstitialAdUnit);
/**
* Executed when the ad is displayed on screen.
*
* @param interstitialAdUnit view of the corresponding event.
*/
void onAdDisplayed(InterstitialAdUnit interstitialAdUnit);
/**
* Executed when an error is encountered on initialization / loading or display step.
*
* @param interstitialAdUnit view of the corresponding event.
* @param exception exception containing detailed message and error type.
*/
void onAdFailed(InterstitialAdUnit interstitialAdUnit, AdException exception);
/**
* Executed when interstitialAdUnit is clicked.
*
* @param interstitialAdUnit view of the corresponding event.
*/
void onAdClicked(InterstitialAdUnit interstitialAdUnit);
/**
* Executed when interstitialAdUnit is closed.
*
* @param interstitialAdUnit view of the corresponding event.
*/
void onAdClosed(InterstitialAdUnit interstitialAdUnit);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/api/rendering/listeners/RewardedAdUnitListener.java | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.api.rendering.listeners;
import org.prebid.mobile.api.exceptions.AdException;
import org.prebid.mobile.api.rendering.RewardedAdUnit;
/**
* Listener interface representing RewardedAdUnit events.
* All methods will be invoked on the main thread.
*/
public interface RewardedAdUnitListener {
/**
* Executed when the ad is loaded and is ready for display.
*
* @param rewardedAdUnit view of the corresponding event. Contains reward instance inside. Prebod reward is always null.
*/
void onAdLoaded(RewardedAdUnit rewardedAdUnit);
/**
* Executed when the ad is displayed on screen.
*
* @param rewardedAdUnit view of the corresponding event.
*/
void onAdDisplayed(RewardedAdUnit rewardedAdUnit);
/**
* Executed when an error is encountered on initialization / loading or display step.
*
* @param rewardedAdUnit view of the corresponding event.
* @param exception exception containing detailed message and error type.
*/
void onAdFailed(RewardedAdUnit rewardedAdUnit, AdException exception);
/**
* Executed when rewardedAdUnit is clicked.
*
* @param rewardedAdUnit view of the corresponding event.
*/
void onAdClicked(RewardedAdUnit rewardedAdUnit);
/**
* Executed when rewardedAdUnit is closed.
*
* @param rewardedAdUnit view of the corresponding event.
*/
void onAdClosed(RewardedAdUnit rewardedAdUnit);
/**
* Executed when user receives reward.
*
* @param rewardedAdUnit view of the corresponding event. Contains reward instance inside. Prebid reward is always null.
*/
void onUserEarnedReward(RewardedAdUnit rewardedAdUnit);
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/configuration/AdUnitConfiguration.java | package org.prebid.mobile.configuration;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.prebid.mobile.*;
import org.prebid.mobile.api.data.AdFormat;
import org.prebid.mobile.api.data.AdUnitFormat;
import org.prebid.mobile.api.data.Position;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
import org.prebid.mobile.rendering.interstitial.InterstitialSizes;
import org.prebid.mobile.rendering.models.AdPosition;
import org.prebid.mobile.rendering.models.PlacementType;
import org.prebid.mobile.rendering.utils.helpers.Utils;
import org.prebid.mobile.rendering.video.ExoPlayerView;
import java.util.*;
public class AdUnitConfiguration {
public static final String TAG = "AdUnitConfiguration";
public static final int SKIP_OFFSET_NOT_ASSIGNED = -1;
private boolean isRewarded;
private boolean isBuiltInVideo = false;
private boolean isMuted = false;
private boolean isSoundButtonVisible = false;
private boolean isOriginalAdUnit = false;
private int videoSkipOffset = SKIP_OFFSET_NOT_ASSIGNED;
private int autoRefreshDelayInMillis = 0;
private int skipDelay = 10;
private final int broadcastId = Utils.generateRandomInt();
private float videoInitialVolume = ExoPlayerView.DEFAULT_INITIAL_VIDEO_VOLUME;
private double closeButtonArea = 0;
private double skipButtonArea = 0;
private int maxVideoDuration = 3600;
private String configId;
private String pbAdSlot;
private String interstitialSize;
private String impressionUrl;
private Position closeButtonPosition = Position.TOP_RIGHT;
private Position skipButtonPosition = Position.TOP_RIGHT;
private AdSize minSizePercentage;
private PlacementType placementType;
private AdPosition adPosition;
private ContentObject appContent;
private BannerParameters bannerParameters;
private VideoParameters videoParameters;
private NativeAdUnitConfiguration nativeConfiguration;
private final EnumSet<AdFormat> adFormats = EnumSet.noneOf(AdFormat.class);
private final HashSet<AdSize> adSizes = new HashSet<>();
@NonNull
private ArrayList<DataObject> userDataObjects = new ArrayList<>();
@NonNull
private Map<String, Set<String>> contextDataDictionary = new HashMap<>();
@NonNull
private Set<String> contextKeywordsSet = new HashSet<>();
public void modifyUsingBidResponse(@Nullable BidResponse bidResponse) {
if (bidResponse != null) {
impressionUrl = bidResponse.getImpressionEventUrl();
}
}
public void setConfigId(String configId) {
this.configId = configId;
}
public String getConfigId() {
return configId;
}
public void setAppContent(@Nullable ContentObject content) {
if (content != null) {
appContent = content;
}
}
public ContentObject getAppContent() {
return appContent;
}
public void setPbAdSlot(String pbAdSlot) {
this.pbAdSlot = pbAdSlot;
}
public String getPbAdSlot() {
return pbAdSlot;
}
public void addUserData(DataObject dataObject) {
if (dataObject != null) {
userDataObjects.add(dataObject);
}
}
public void setUserData(@Nullable ArrayList<DataObject> userData) {
if (userData != null) {
userDataObjects = userData;
}
}
public void setContextDataDictionary(@Nullable Map<String, Set<String>> contextData){
if (contextData != null) {
contextDataDictionary = contextData;
}
}
public void setContextDataKeywords(@Nullable Set<String> contextDataKeywords){
if (contextDataKeywords != null) {
contextKeywordsSet = contextDataKeywords;
}
}
@NonNull
public ArrayList<DataObject> getUserData() {
return userDataObjects;
}
public void clearUserData() {
userDataObjects.clear();
}
public void addContextData(
String key,
String value
) {
if (key != null && value != null) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add(value);
contextDataDictionary.put(key, hashSet);
}
}
public void addContextData(
String key,
Set<String> value
) {
if (key != null && value != null) {
contextDataDictionary.put(key, value);
}
}
public void removeContextData(String key) {
contextDataDictionary.remove(key);
}
@NonNull
public Map<String, Set<String>> getContextDataDictionary() {
return contextDataDictionary;
}
public void clearContextData() {
contextDataDictionary.clear();
}
public void addContextKeyword(String keyword) {
if (keyword != null) {
contextKeywordsSet.add(keyword);
}
}
public void addContextKeywords(Set<String> keywords) {
if (keywords != null) {
contextKeywordsSet.addAll(keywords);
}
}
public void removeContextKeyword(String key) {
if (key != null) {
contextKeywordsSet.remove(key);
}
}
@NonNull
public Set<String> getContextKeywordsSet() {
return contextKeywordsSet;
}
public void clearContextKeywords() {
contextKeywordsSet.clear();
}
public void setMinSizePercentage(@Nullable AdSize minSizePercentage) {
this.minSizePercentage = minSizePercentage;
}
@Nullable
public AdSize getMinSizePercentage() {
return minSizePercentage;
}
public void addSize(@Nullable AdSize size) {
if (size != null) {
adSizes.add(size);
}
}
public void addSizes(AdSize... sizes) {
adSizes.addAll(Arrays.asList(sizes));
}
public void addSizes(@Nullable Set<AdSize> sizes) {
if (sizes != null) {
adSizes.addAll(sizes);
}
}
@NonNull
public HashSet<AdSize> getSizes() {
return adSizes;
}
public void setBannerParameters(BannerParameters parameters) {
bannerParameters = parameters;
}
public BannerParameters getBannerParameters() {
return bannerParameters;
}
public void setVideoParameters(VideoParameters parameters) {
videoParameters = parameters;
}
public VideoParameters getVideoParameters() {
return videoParameters;
}
public void setBuiltInVideo(boolean builtInVideo) {
isBuiltInVideo = builtInVideo;
}
public boolean isBuiltInVideo() {
return isBuiltInVideo;
}
public void setIsMuted(boolean isMuted) {
this.isMuted = isMuted;
}
public boolean isMuted() {
return isMuted;
}
public void setIsSoundButtonVisible(boolean isSoundButtonVisible) {
this.isSoundButtonVisible = isSoundButtonVisible;
}
public boolean isSoundButtonVisible() {
return isSoundButtonVisible;
}
public void setAutoRefreshDelay(int autoRefreshDelayInSeconds) {
if (autoRefreshDelayInSeconds < 0) {
LogUtil.error(TAG, "Auto refresh delay can't be less then 0.");
return;
}
if (autoRefreshDelayInSeconds == 0) {
LogUtil.debug(TAG, "Only one request, without auto refresh.");
autoRefreshDelayInMillis = 0;
return;
}
autoRefreshDelayInMillis = Utils.clampAutoRefresh(autoRefreshDelayInSeconds);
}
public int getAutoRefreshDelay() {
return autoRefreshDelayInMillis;
}
public void setVideoSkipOffset(int videoSkipOffset) {
this.videoSkipOffset = videoSkipOffset;
}
public int getVideoSkipOffset() {
return videoSkipOffset;
}
public void addAdFormat(@Nullable AdFormat adFormat) {
if (adFormat == null) return;
if (adFormat == AdFormat.NATIVE) {
nativeConfiguration = new NativeAdUnitConfiguration();
}
adFormats.add(adFormat);
}
/**
* Clears ad formats list and adds only one ad format.
*/
public void setAdFormat(@Nullable AdFormat adFormat) {
if (adFormat == null) return;
if (adFormat == AdFormat.NATIVE) {
nativeConfiguration = new NativeAdUnitConfiguration();
}
adFormats.clear();
adFormats.add(adFormat);
}
/**
* Clears previous ad formats and adds AdFormats corresponding to AdUnitFormat types.
*/
public void setAdUnitFormats(@Nullable EnumSet<AdUnitFormat> adUnitFormats) {
if (adUnitFormats == null) return;
adFormats.clear();
adFormats.addAll(AdFormat.fromSet(adUnitFormats, true));
}
/**
* Clears previous ad formats and adds AdFormats corresponding to AdUnitFormat types.
*/
public void setAdFormats(@Nullable EnumSet<AdFormat> formats) {
if (formats == null) return;
if (formats.contains(AdFormat.NATIVE)) {
nativeConfiguration = new NativeAdUnitConfiguration();
}
adFormats.clear();
adFormats.addAll(formats);
}
public void setSkipDelay(int seconds) {
this.skipDelay = seconds;
}
public int getSkipDelay() {
return skipDelay;
}
public double getSkipButtonArea() {
return skipButtonArea;
}
public void setSkipButtonArea(double skipButtonArea) {
this.skipButtonArea = skipButtonArea;
}
@NonNull
public Position getSkipButtonPosition() {
return skipButtonPosition;
}
public void setSkipButtonPosition(@Nullable Position skipButtonPosition) {
if (skipButtonPosition != null) {
this.skipButtonPosition = skipButtonPosition;
}
}
@NonNull
public EnumSet<AdFormat> getAdFormats() {
return adFormats;
}
public boolean isAdType(AdFormat type) {
return adFormats.contains(type);
}
public void setRewarded(boolean rewarded) {
isRewarded = rewarded;
}
public boolean isRewarded() {
return isRewarded;
}
public void setCloseButtonArea(@FloatRange(from = 0, to = 1.0) double closeButtonArea) {
this.closeButtonArea = closeButtonArea;
}
public double getCloseButtonArea() {
return closeButtonArea;
}
public void setInterstitialSize(@Nullable InterstitialSizes.InterstitialSize size) {
if (size != null) {
interstitialSize = size.getSize();
}
}
public void setInterstitialSize(@Nullable String size) {
interstitialSize = size;
}
public void setInterstitialSize(
int width,
int height
) {
interstitialSize = width + "x" + height;
}
@Nullable
public String getInterstitialSize() {
return interstitialSize;
}
public void setCloseButtonPosition(@Nullable Position closeButtonPosition) {
if (closeButtonPosition != null) {
this.closeButtonPosition = closeButtonPosition;
}
}
@NonNull
public Position getCloseButtonPosition() {
return closeButtonPosition;
}
public void setVideoInitialVolume(float videoInitialVolume) {
this.videoInitialVolume = videoInitialVolume;
}
public float getVideoInitialVolume() {
return videoInitialVolume;
}
public void setPlacementType(@Nullable PlacementType placementType) {
this.placementType = placementType;
}
public int getPlacementTypeValue() {
return placementType != null
? placementType.getValue()
: PlacementType.UNDEFINED.getValue();
}
public boolean isPlacementTypeValid() {
return getPlacementTypeValue() != PlacementType.UNDEFINED.getValue();
}
public void setAdPosition(@Nullable AdPosition adPosition) {
this.adPosition = adPosition;
}
public int getAdPositionValue() {
return adPosition != null ? adPosition.getValue() : AdPosition.UNDEFINED.getValue();
}
public boolean isAdPositionValid() {
return AdPosition.UNDEFINED.getValue() != getAdPositionValue();
}
public int getBroadcastId() {
return broadcastId;
}
public void setMaxVideoDuration(int seconds) {
this.maxVideoDuration = seconds;
}
@Nullable
public Integer getMaxVideoDuration() {
return maxVideoDuration;
}
@Nullable
public NativeAdUnitConfiguration getNativeConfiguration() {
return nativeConfiguration;
}
public boolean isOriginalAdUnit() {
return isOriginalAdUnit;
}
public void setNativeConfiguration(NativeAdUnitConfiguration nativeConfiguration) {
this.nativeConfiguration = nativeConfiguration;
}
public void setIsOriginalAdUnit(boolean originalAdUnit) {
isOriginalAdUnit = originalAdUnit;
}
public String getImpressionUrl() {
return impressionUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AdUnitConfiguration that = (AdUnitConfiguration) o;
return configId != null ? configId.equals(that.configId) : that.configId == null;
}
@Override
public int hashCode() {
return configId != null ? configId.hashCode() : 0;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/configuration/NativeAdUnitConfiguration.java | package org.prebid.mobile.configuration;
import org.json.JSONObject;
import org.prebid.mobile.NativeAdUnit;
import org.prebid.mobile.NativeAsset;
import org.prebid.mobile.NativeEventTracker;
import java.util.ArrayList;
import java.util.List;
public class NativeAdUnitConfiguration {
private final ArrayList<NativeAsset> nativeAssets = new ArrayList<>();
private final ArrayList<NativeEventTracker> nativeEventTrackers = new ArrayList<>();
private NativeAdUnit.CONTEXT_TYPE contextType;
private NativeAdUnit.CONTEXTSUBTYPE contextSubtype;
private NativeAdUnit.PLACEMENTTYPE placementType;
private int placementCount = 1;
private int sequence = 0;
private boolean aUrlSupport = false;
private boolean dUrlSupport = false;
private boolean privacy = false;
private JSONObject ext;
public void addEventTracker(NativeEventTracker tracker) {
nativeEventTrackers.add(tracker);
}
public List<NativeEventTracker> getEventTrackers() {
return nativeEventTrackers;
}
public void clearEventTrackers() {
nativeEventTrackers.clear();
}
public void addAsset(NativeAsset nativeAsset) {
nativeAssets.add(nativeAsset);
}
public ArrayList<NativeAsset> getAssets() {
return nativeAssets;
}
public void clearAssets() {
nativeAssets.clear();
}
public void setContextType(NativeAdUnit.CONTEXT_TYPE contextType) {
this.contextType = contextType;
}
public NativeAdUnit.CONTEXT_TYPE getContextType() {
return contextType;
}
public void setContextSubtype(NativeAdUnit.CONTEXTSUBTYPE contextSubtype) {
this.contextSubtype = contextSubtype;
}
public NativeAdUnit.CONTEXTSUBTYPE getContextSubtype() {
return contextSubtype;
}
public void setPlacementType(NativeAdUnit.PLACEMENTTYPE placementType) {
this.placementType = placementType;
}
public NativeAdUnit.PLACEMENTTYPE getPlacementType() {
return placementType;
}
public void setPlacementCount(int placementCount) {
this.placementCount = placementCount;
}
public int getPlacementCount() {
return placementCount;
}
public void setSeq(int seq) {
this.sequence = seq;
}
public int getSeq() {
return sequence;
}
public void setAUrlSupport(boolean support) {
aUrlSupport = support;
}
public boolean getAUrlSupport() {
return aUrlSupport;
}
public void setDUrlSupport(boolean support) {
dUrlSupport = support;
}
public boolean getDUrlSupport() {
return dUrlSupport;
}
public void setPrivacy(boolean privacy) {
this.privacy = privacy;
}
public boolean getPrivacy() {
return privacy;
}
public void setExt(JSONObject ext) {
this.ext = ext;
}
public JSONObject getExt() {
return ext;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/http/HTTPGet.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.http;
import android.os.Looper;
import org.prebid.mobile.Util;
import org.prebid.mobile.tasksmanager.TasksManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public abstract class HTTPGet {
public HTTPGet() {
super();
}
abstract protected void onPostExecute(HTTPResponse response);
public void execute() {
if (Looper.myLooper() == Looper.getMainLooper()) {
TasksManager.getInstance().executeOnBackgroundThread(new Runnable() {
@Override
public void run() {
HTTPResponse response = makeHttpRequest();
onPostExecute(response);
}
});
} else {
HTTPResponse response = makeHttpRequest();
onPostExecute(response);
}
}
protected abstract String getUrl();
private HttpURLConnection createConnection(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(false);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
return connection;
}
private void setConnectionParams(HttpURLConnection connection) throws ProtocolException {
connection.setConnectTimeout(Util.HTTP_CONNECTION_TIMEOUT);
connection.setReadTimeout(Util.HTTP_SOCKET_TIMEOUT);
}
protected HTTPResponse makeHttpRequest() {
HTTPResponse out = new HTTPResponse();
HttpURLConnection connection = null;
try {
URL reqUrl = new URL(getUrl());
if (reqUrl.getHost() == null) {
out.setSucceeded(false);
return out;
}
// Create and connect to HTTP service
connection = createConnection(reqUrl);
setConnectionParams(connection);
connection.connect();
//Response parsing
StringBuilder builder = new StringBuilder();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
is.close();
String responseString = builder.toString();
out.setHeaders(connection.getHeaderFields());
out.setResponseBody(responseString);
boolean isStatusOK = (connection.getResponseCode()
== HttpURLConnection.HTTP_OK);
out.setSucceeded(isStatusOK);
} catch (MalformedURLException e) {
out.setSucceeded(false);
out.setErrorCode(HttpErrorCode.URI_SYNTAX_ERROR);
} catch (IOException e) {
out.setSucceeded(false);
out.setErrorCode(HttpErrorCode.TRANSPORT_ERROR);
} catch (Exception e) {
out.setSucceeded(false);
out.setErrorCode(HttpErrorCode.UNKNOWN_ERROR);
e.printStackTrace();
}
return out;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/http/HTTPResponse.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.http;
import java.util.List;
import java.util.Map;
public class HTTPResponse {
private boolean succeeded;
private String responseBody;
private Map<String, List<String>> headers;
private HttpErrorCode errorCode;
public HTTPResponse() {
}
public HTTPResponse(boolean succeeded, String responseBody, Map<String, List<String>> headers) {
this.succeeded = succeeded;
this.responseBody = responseBody;
this.headers = headers;
}
public boolean getSucceeded() {
return succeeded;
}
public void setSucceeded(boolean succeeded) {
this.succeeded = succeeded;
}
public void setErrorCode(HttpErrorCode errorCode) {
this.errorCode = errorCode;
}
public HttpErrorCode getErrorCode() {
return errorCode;
}
public String getResponseBody() {
return responseBody;
}
public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
}
|
0 | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile | java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/http/HttpErrorCode.java | /*
* Copyright 2020-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.http;
public enum HttpErrorCode {
CONNECTION_FAILURE,
URI_SYNTAX_ERROR,
NO_HTTP_RESPONSE,
HTTP_PROTOCOL_ERROR,
TRANSPORT_ERROR,
UNKNOWN_ERROR
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.