file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
44,958 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.threadpool;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.node.Node;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* A builder for scaling executors.
*
* The {@link #build} method will instantiate a java {@link ExecutorService} thread pool that starts with the specified minimum number of
* threads and then scales up to the specified max number of threads as needed for excess work, scaling back when the burst of activity
* stops. As opposed to the {@link FixedExecutorBuilder} that keeps a fixed number of threads alive.
*/
public final class ScalingExecutorBuilder extends ExecutorBuilder<ScalingExecutorBuilder.ScalingExecutorSettings> {
private final Setting<Integer> coreSetting;
private final Setting<Integer> maxSetting;
private final Setting<TimeValue> keepAliveSetting;
private final boolean rejectAfterShutdown;
/**
* Construct a scaling executor builder; the settings will have the
* key prefix "thread_pool." followed by the executor name.
*
* @param name the name of the executor
* @param core the minimum number of threads in the pool
* @param max the maximum number of threads in the pool
* @param keepAlive the time that spare threads above {@code core}
* threads will be kept alive
* @param rejectAfterShutdown set to {@code true} if the executor should reject tasks after shutdown
*/
public ScalingExecutorBuilder(
final String name,
final int core,
final int max,
final TimeValue keepAlive,
final boolean rejectAfterShutdown
) {
this(name, core, max, keepAlive, rejectAfterShutdown, "thread_pool." + name);
}
/**
* Construct a scaling executor builder; the settings will have the
* specified key prefix.
*
* @param name the name of the executor
* @param core the minimum number of threads in the pool
* @param max the maximum number of threads in the pool
* @param keepAlive the time that spare threads above {@code core}
* threads will be kept alive
* @param prefix the prefix for the settings keys
* @param rejectAfterShutdown set to {@code true} if the executor should reject tasks after shutdown
*/
public ScalingExecutorBuilder(
final String name,
final int core,
final int max,
final TimeValue keepAlive,
final boolean rejectAfterShutdown,
final String prefix
) {
super(name);
this.coreSetting = Setting.intSetting(settingsKey(prefix, "core"), core, Setting.Property.NodeScope);
this.maxSetting = Setting.intSetting(settingsKey(prefix, "max"), max, Setting.Property.NodeScope);
this.keepAliveSetting = Setting.timeSetting(settingsKey(prefix, "keep_alive"), keepAlive, Setting.Property.NodeScope);
this.rejectAfterShutdown = rejectAfterShutdown;
}
@Override
public List<Setting<?>> getRegisteredSettings() {
return Arrays.asList(coreSetting, maxSetting, keepAliveSetting);
}
@Override
ScalingExecutorSettings getSettings(Settings settings) {
final String nodeName = Node.NODE_NAME_SETTING.get(settings);
final int coreThreads = coreSetting.get(settings);
final int maxThreads = maxSetting.get(settings);
final TimeValue keepAlive = keepAliveSetting.get(settings);
return new ScalingExecutorSettings(nodeName, coreThreads, maxThreads, keepAlive);
}
ThreadPool.ExecutorHolder build(final ScalingExecutorSettings settings, final ThreadContext threadContext) {
TimeValue keepAlive = settings.keepAlive;
int core = settings.core;
int max = settings.max;
final ThreadPool.Info info = new ThreadPool.Info(name(), ThreadPool.ThreadPoolType.SCALING, core, max, keepAlive, null);
final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(EsExecutors.threadName(settings.nodeName, name()));
final ExecutorService executor = EsExecutors.newScaling(
settings.nodeName + "/" + name(),
core,
max,
keepAlive.millis(),
TimeUnit.MILLISECONDS,
rejectAfterShutdown,
threadFactory,
threadContext
);
return new ThreadPool.ExecutorHolder(executor, info);
}
@Override
String formatInfo(ThreadPool.Info info) {
return String.format(
Locale.ROOT,
"name [%s], core [%d], max [%d], keep alive [%s]",
info.getName(),
info.getMin(),
info.getMax(),
info.getKeepAlive()
);
}
static class ScalingExecutorSettings extends ExecutorBuilder.ExecutorSettings {
private final int core;
private final int max;
private final TimeValue keepAlive;
ScalingExecutorSettings(final String nodeName, final int core, final int max, final TimeValue keepAlive) {
super(nodeName);
this.core = core;
this.max = max;
this.keepAlive = keepAlive;
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/threadpool/ScalingExecutorBuilder.java |
44,959 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search.builder;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.action.search.SearchContextId;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.xcontent.ObjectParser;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;
/**
* A search request with a point in time will execute using the reader contexts associated with that point time
* instead of the latest reader contexts.
*/
public final class PointInTimeBuilder implements Writeable, ToXContentFragment {
private static final ParseField ID_FIELD = new ParseField("id");
private static final ParseField KEEP_ALIVE_FIELD = new ParseField("keep_alive");
private static final ObjectParser<XContentParams, Void> PARSER;
static {
PARSER = new ObjectParser<>(SearchSourceBuilder.POINT_IN_TIME.getPreferredName(), XContentParams::new);
PARSER.declareString((params, id) -> params.encodedId = new BytesArray(Base64.getUrlDecoder().decode(id)), ID_FIELD);
PARSER.declareField(
(params, keepAlive) -> params.keepAlive = keepAlive,
(p, c) -> TimeValue.parseTimeValue(p.text(), KEEP_ALIVE_FIELD.getPreferredName()),
KEEP_ALIVE_FIELD,
ObjectParser.ValueType.STRING
);
}
private static final class XContentParams {
private BytesReference encodedId;
private TimeValue keepAlive;
}
private final BytesReference encodedId;
private transient SearchContextId searchContextId; // lazily decoded from the encodedId
private TimeValue keepAlive;
public PointInTimeBuilder(BytesReference pitID) {
this.encodedId = Objects.requireNonNull(pitID, "Point in time ID must be provided");
}
public PointInTimeBuilder(StreamInput in) throws IOException {
if (in.getTransportVersion().onOrAfter(TransportVersions.BINARY_PIT_ID)) {
encodedId = in.readBytesReference();
} else {
encodedId = new BytesArray(Base64.getUrlDecoder().decode(in.readString()));
}
keepAlive = in.readOptionalTimeValue();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getTransportVersion().onOrAfter(TransportVersions.BINARY_PIT_ID)) {
out.writeBytesReference(encodedId);
} else {
out.writeString(Base64.getUrlEncoder().encodeToString(BytesReference.toBytes(encodedId)));
}
out.writeOptionalTimeValue(keepAlive);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(ID_FIELD.getPreferredName(), Base64.getUrlEncoder().encodeToString(BytesReference.toBytes(encodedId)));
if (keepAlive != null) {
builder.field(KEEP_ALIVE_FIELD.getPreferredName(), keepAlive.getStringRep());
}
return builder;
}
public static PointInTimeBuilder fromXContent(XContentParser parser) throws IOException {
final XContentParams params = PARSER.parse(parser, null);
if (params.encodedId == null) {
throw new IllegalArgumentException("point in time id is not provided");
}
return new PointInTimeBuilder(params.encodedId).setKeepAlive(params.keepAlive);
}
/**
* Returns the encoded id of this point in time
*/
public BytesReference getEncodedId() {
return encodedId;
}
/**
* Returns the search context of this point in time from its encoded id.
*/
public SearchContextId getSearchContextId(NamedWriteableRegistry namedWriteableRegistry) {
if (searchContextId == null) {
searchContextId = SearchContextId.decode(namedWriteableRegistry, encodedId);
}
return searchContextId;
}
/**
* If specified, the search layer will keep this point in time around for at least the given keep-alive.
* Otherwise, the point in time will be kept around until the original keep alive elapsed.
*/
public PointInTimeBuilder setKeepAlive(TimeValue keepAlive) {
this.keepAlive = keepAlive;
return this;
}
/**
* If specified, the search layer will keep this point in time around for at least the given keep-alive.
* Otherwise, the point in time will be kept around until the original keep alive elapsed.
*/
public PointInTimeBuilder setKeepAlive(String keepAlive) {
return setKeepAlive(TimeValue.parseTimeValue(keepAlive, "keep_alive"));
}
@Nullable
public TimeValue getKeepAlive() {
return keepAlive;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final PointInTimeBuilder that = (PointInTimeBuilder) o;
return Objects.equals(encodedId, that.encodedId) && Objects.equals(keepAlive, that.keepAlive);
}
@Override
public int hashCode() {
return Objects.hash(encodedId, keepAlive);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/search/builder/PointInTimeBuilder.java |
44,960 | 404: Not Found | apache/dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java |
44,961 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.http;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.core.TimeValue;
import java.util.List;
import java.util.function.Function;
import static org.elasticsearch.common.settings.Setting.boolSetting;
import static org.elasticsearch.common.settings.Setting.intSetting;
import static org.elasticsearch.common.settings.Setting.listSetting;
import static org.elasticsearch.common.settings.Setting.stringListSetting;
public final class HttpTransportSettings {
public static final Setting<Boolean> SETTING_CORS_ENABLED = Setting.boolSetting("http.cors.enabled", false, Property.NodeScope);
public static final Setting<String> SETTING_CORS_ALLOW_ORIGIN = new Setting<>(
"http.cors.allow-origin",
"",
(value) -> value,
Property.NodeScope
);
public static final Setting<Integer> SETTING_CORS_MAX_AGE = intSetting("http.cors.max-age", 1728000, Property.NodeScope);
public static final Setting<String> SETTING_CORS_ALLOW_METHODS = new Setting<>(
"http.cors.allow-methods",
"OPTIONS,HEAD,GET,POST,PUT,DELETE",
(value) -> value,
Property.NodeScope
);
public static final Setting<String> SETTING_CORS_ALLOW_HEADERS = new Setting<>(
"http.cors.allow-headers",
"X-Requested-With,Content-Type,Content-Length,Authorization,Accept,User-Agent,X-Elastic-Client-Meta",
(value) -> value,
Property.NodeScope
);
public static final Setting<String> SETTING_CORS_EXPOSE_HEADERS = new Setting<>(
"http.cors.expose-headers",
"X-elastic-product",
(value) -> value,
Property.NodeScope
);
public static final Setting<Boolean> SETTING_CORS_ALLOW_CREDENTIALS = Setting.boolSetting(
"http.cors.allow-credentials",
false,
Property.NodeScope
);
public static final Setting<Integer> SETTING_PIPELINING_MAX_EVENTS = intSetting(
"http.pipelining.max_events",
10000,
Property.NodeScope
);
public static final Setting<Boolean> SETTING_HTTP_COMPRESSION = Setting.boolSetting("http.compression", true, Property.NodeScope);
// we intentionally use a different compression level as Netty here as our benchmarks have shown that a compression level of 3 is the
// best compromise between reduction in network traffic and added latency. For more details please check #7309.
public static final Setting<Integer> SETTING_HTTP_COMPRESSION_LEVEL = intSetting("http.compression_level", 3, Property.NodeScope);
public static final Setting<List<String>> SETTING_HTTP_HOST = stringListSetting("http.host", Property.NodeScope);
public static final Setting<List<String>> SETTING_HTTP_PUBLISH_HOST = listSetting(
"http.publish_host",
SETTING_HTTP_HOST,
Function.identity(),
Property.NodeScope
);
public static final Setting<List<String>> SETTING_HTTP_BIND_HOST = listSetting(
"http.bind_host",
SETTING_HTTP_HOST,
Function.identity(),
Property.NodeScope
);
public static final Setting<PortsRange> SETTING_HTTP_PORT = new Setting<>(
"http.port",
"9200-9300",
PortsRange::new,
Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_PUBLISH_PORT = intSetting("http.publish_port", -1, -1, Property.NodeScope);
public static final Setting<Boolean> SETTING_HTTP_DETAILED_ERRORS_ENABLED = Setting.boolSetting(
"http.detailed_errors.enabled",
true,
Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_CONTENT_LENGTH = Setting.byteSizeSetting(
"http.max_content_length",
new ByteSizeValue(100, ByteSizeUnit.MB),
ByteSizeValue.ZERO,
ByteSizeValue.ofBytes(Integer.MAX_VALUE),
Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_CHUNK_SIZE = Setting.byteSizeSetting(
"http.max_chunk_size",
new ByteSizeValue(8, ByteSizeUnit.KB),
Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_HEADER_SIZE = Setting.byteSizeSetting(
"http.max_header_size",
new ByteSizeValue(16, ByteSizeUnit.KB),
Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_MAX_WARNING_HEADER_COUNT = intSetting(
"http.max_warning_header_count",
-1,
-1,
Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_WARNING_HEADER_SIZE = Setting.byteSizeSetting(
"http.max_warning_header_size",
ByteSizeValue.MINUS_ONE,
Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_INITIAL_LINE_LENGTH = Setting.byteSizeSetting(
"http.max_initial_line_length",
new ByteSizeValue(4, ByteSizeUnit.KB),
Property.NodeScope
);
public static final Setting<TimeValue> SETTING_HTTP_SERVER_SHUTDOWN_GRACE_PERIOD = Setting.positiveTimeSetting(
"http.shutdown_grace_period",
TimeValue.timeValueMillis(0),
Setting.Property.NodeScope
);
public static final Setting<TimeValue> SETTING_HTTP_SERVER_SHUTDOWN_POLL_PERIOD = Setting.positiveTimeSetting(
"http.shutdown_poll_period",
TimeValue.timeValueMinutes(5),
Setting.Property.NodeScope
);
// don't reset cookies by default, since I don't think we really need to
// note, parsing cookies was fixed in netty 3.5.1 regarding stack allocation, but still, currently, we don't need cookies
public static final Setting<Boolean> SETTING_HTTP_RESET_COOKIES = Setting.boolSetting("http.reset_cookies", false, Property.NodeScope);
// A default of 0 means that by default there is no read timeout
public static final Setting<TimeValue> SETTING_HTTP_READ_TIMEOUT = Setting.timeSetting(
"http.read_timeout",
new TimeValue(0),
new TimeValue(0),
Property.NodeScope
);
// Tcp socket settings
public static final Setting<Boolean> SETTING_HTTP_TCP_NO_DELAY = boolSetting(
"http.tcp.no_delay",
NetworkService.TCP_NO_DELAY,
Setting.Property.NodeScope
);
public static final Setting<Boolean> SETTING_HTTP_TCP_KEEP_ALIVE = boolSetting(
"http.tcp.keep_alive",
NetworkService.TCP_KEEP_ALIVE,
Setting.Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_TCP_KEEP_IDLE = intSetting(
"http.tcp.keep_idle",
NetworkService.TCP_KEEP_IDLE,
-1,
300,
Setting.Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_TCP_KEEP_INTERVAL = intSetting(
"http.tcp.keep_interval",
NetworkService.TCP_KEEP_INTERVAL,
-1,
300,
Setting.Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_TCP_KEEP_COUNT = intSetting(
"http.tcp.keep_count",
NetworkService.TCP_KEEP_COUNT,
-1,
Setting.Property.NodeScope
);
public static final Setting<Boolean> SETTING_HTTP_TCP_REUSE_ADDRESS = boolSetting(
"http.tcp.reuse_address",
NetworkService.TCP_REUSE_ADDRESS,
Setting.Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_TCP_SEND_BUFFER_SIZE = Setting.byteSizeSetting(
"http.tcp.send_buffer_size",
NetworkService.TCP_SEND_BUFFER_SIZE,
Setting.Property.NodeScope
);
public static final Setting<ByteSizeValue> SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE = Setting.byteSizeSetting(
"http.tcp.receive_buffer_size",
NetworkService.TCP_RECEIVE_BUFFER_SIZE,
Setting.Property.NodeScope
);
public static final Setting<List<String>> SETTING_HTTP_TRACE_LOG_INCLUDE = Setting.stringListSetting(
"http.tracer.include",
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
public static final Setting<List<String>> SETTING_HTTP_TRACE_LOG_EXCLUDE = Setting.stringListSetting(
"http.tracer.exclude",
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
public static final Setting<Boolean> SETTING_HTTP_CLIENT_STATS_ENABLED = boolSetting(
"http.client_stats.enabled",
true,
Property.Dynamic,
Property.NodeScope
);
public static final Setting<Integer> SETTING_HTTP_CLIENT_STATS_MAX_CLOSED_CHANNEL_COUNT = intSetting(
"http.client_stats.closed_channels.max_count",
10000,
Property.NodeScope
);
public static final Setting<TimeValue> SETTING_HTTP_CLIENT_STATS_MAX_CLOSED_CHANNEL_AGE = Setting.timeSetting(
"http.client_stats.closed_channels.max_age",
TimeValue.timeValueMinutes(5),
Property.NodeScope
);
private HttpTransportSettings() {}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/http/HttpTransportSettings.java |
44,962 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.search;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskId;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.action.ValidateActions.addValidationError;
public final class OpenPointInTimeRequest extends ActionRequest implements IndicesRequest.Replaceable {
private String[] indices;
private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS;
private TimeValue keepAlive;
private int maxConcurrentShardRequests = SearchRequest.DEFAULT_MAX_CONCURRENT_SHARD_REQUESTS;
@Nullable
private String routing;
@Nullable
private String preference;
private QueryBuilder indexFilter;
public static final IndicesOptions DEFAULT_INDICES_OPTIONS = SearchRequest.DEFAULT_INDICES_OPTIONS;
public OpenPointInTimeRequest(String... indices) {
this.indices = Objects.requireNonNull(indices, "[index] is not specified");
}
public OpenPointInTimeRequest(StreamInput in) throws IOException {
super(in);
this.indices = in.readStringArray();
this.indicesOptions = IndicesOptions.readIndicesOptions(in);
this.keepAlive = in.readTimeValue();
this.routing = in.readOptionalString();
this.preference = in.readOptionalString();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_9_X)) {
this.maxConcurrentShardRequests = in.readVInt();
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
this.indexFilter = in.readOptionalNamedWriteable(QueryBuilder.class);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(indices);
indicesOptions.writeIndicesOptions(out);
out.writeTimeValue(keepAlive);
out.writeOptionalString(routing);
out.writeOptionalString(preference);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_9_X)) {
out.writeVInt(maxConcurrentShardRequests);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
out.writeOptionalWriteable(indexFilter);
}
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (indices == null || indices.length == 0) {
validationException = addValidationError("[index] is not specified", validationException);
}
if (keepAlive == null) {
validationException = addValidationError("[keep_alive] is not specified", validationException);
}
return validationException;
}
@Override
public String[] indices() {
return indices;
}
@Override
public OpenPointInTimeRequest indices(String... indices) {
this.indices = indices;
return this;
}
@Override
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public OpenPointInTimeRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = Objects.requireNonNull(indicesOptions, "[indices_options] parameter must be non null");
return this;
}
public TimeValue keepAlive() {
return keepAlive;
}
/**
* Set keep alive for the point in time
*/
public OpenPointInTimeRequest keepAlive(TimeValue keepAlive) {
this.keepAlive = keepAlive;
return this;
}
public String routing() {
return routing;
}
public OpenPointInTimeRequest routing(String routing) {
this.routing = routing;
return this;
}
public String preference() {
return preference;
}
public OpenPointInTimeRequest preference(String preference) {
this.preference = preference;
return this;
}
/**
* Similar to {@link SearchRequest#getMaxConcurrentShardRequests()}, this returns the number of shard requests that should be
* executed concurrently on a single node . This value should be used as a protection mechanism to reduce the number of shard
* requests fired per open point-in-time request. The default is {@code 5}
*/
public int maxConcurrentShardRequests() {
return maxConcurrentShardRequests;
}
/**
* Similar to {@link SearchRequest#setMaxConcurrentShardRequests(int)}, this sets the number of shard requests that should be
* executed concurrently on a single node. This value should be used as a protection mechanism to reduce the number of shard
* requests fired per open point-in-time request.
*/
public void maxConcurrentShardRequests(int maxConcurrentShardRequests) {
if (maxConcurrentShardRequests < 1) {
throw new IllegalArgumentException("maxConcurrentShardRequests must be >= 1");
}
this.maxConcurrentShardRequests = maxConcurrentShardRequests;
}
public void indexFilter(QueryBuilder indexFilter) {
this.indexFilter = indexFilter;
}
public QueryBuilder indexFilter() {
return indexFilter;
}
@Override
public boolean allowsRemoteIndices() {
return true;
}
@Override
public boolean includeDataStreams() {
return true;
}
@Override
public String getDescription() {
return "open search context: indices [" + String.join(",", indices) + "] keep_alive [" + keepAlive + "]";
}
@Override
public String toString() {
return "OpenPointInTimeRequest{"
+ "indices="
+ Arrays.toString(indices)
+ ", keepAlive="
+ keepAlive
+ ", maxConcurrentShardRequests="
+ maxConcurrentShardRequests
+ ", routing='"
+ routing
+ '\''
+ ", preference='"
+ preference
+ '\''
+ '}';
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
return new SearchTask(id, type, action, this::getDescription, parentTaskId, headers);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OpenPointInTimeRequest that = (OpenPointInTimeRequest) o;
return maxConcurrentShardRequests == that.maxConcurrentShardRequests
&& Arrays.equals(indices, that.indices)
&& indicesOptions.equals(that.indicesOptions)
&& keepAlive.equals(that.keepAlive)
&& Objects.equals(routing, that.routing)
&& Objects.equals(preference, that.preference);
}
@Override
public int hashCode() {
int result = Objects.hash(indicesOptions, keepAlive, maxConcurrentShardRequests, routing, preference);
result = 31 * result + Arrays.hashCode(indices);
return result;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/action/search/OpenPointInTimeRequest.java |
44,963 | /*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.rxjava3.schedulers;
import java.util.concurrent.*;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.functions.Supplier;
import io.reactivex.rxjava3.internal.schedulers.*;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
/**
* Static factory methods for returning standard {@link Scheduler} instances.
* <p>
* The initial and runtime values of the various scheduler types can be overridden via the
* {@code RxJavaPlugins.setInit(scheduler name)SchedulerHandler()} and
* {@code RxJavaPlugins.set(scheduler name)SchedulerHandler()} respectively.
* Note that overriding any initial {@code Scheduler} via the {@link RxJavaPlugins}
* has to happen before the {@code Schedulers} class is accessed.
* <p>
* <strong>Supported system properties ({@code System.getProperty()}):</strong>
* <ul>
* <li>{@code rx3.io-keep-alive-time} (long): sets the keep-alive time of the {@link #io()} {@code Scheduler} workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li>
* <li>{@code rx3.io-priority} (int): sets the thread priority of the {@link #io()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* <li>{@code rx3.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the
* {@link #io()} {@code Scheduler} to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li>
* <li>{@code rx3.computation-threads} (int): sets the number of threads in the {@link #computation()} {@code Scheduler}, default is the number of available CPUs</li>
* <li>{@code rx3.computation-priority} (int): sets the thread priority of the {@link #computation()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* <li>{@code rx3.newthread-priority} (int): sets the thread priority of the {@link #newThread()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* <li>{@code rx3.single-priority} (int): sets the thread priority of the {@link #single()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* <li>{@code rx3.purge-enabled} (boolean): enables purging of all {@code Scheduler}'s backing thread pools, default is {@code true}</li>
* <li>{@code rx3.scheduler.use-nanotime} (boolean): {@code true} instructs {@code Scheduler} to use {@link System#nanoTime()} for {@link Scheduler#now(TimeUnit)},
* instead of default {@link System#currentTimeMillis()} ({@code false})</li>
* </ul>
*/
public final class Schedulers {
@NonNull
static final Scheduler SINGLE;
@NonNull
static final Scheduler COMPUTATION;
@NonNull
static final Scheduler IO;
@NonNull
static final Scheduler TRAMPOLINE;
@NonNull
static final Scheduler NEW_THREAD;
static final class SingleHolder {
static final Scheduler DEFAULT = new SingleScheduler();
}
static final class ComputationHolder {
static final Scheduler DEFAULT = new ComputationScheduler();
}
static final class IoHolder {
static final Scheduler DEFAULT = new IoScheduler();
}
static final class NewThreadHolder {
static final Scheduler DEFAULT = new NewThreadScheduler();
}
static {
SINGLE = RxJavaPlugins.initSingleScheduler(new SingleTask());
COMPUTATION = RxJavaPlugins.initComputationScheduler(new ComputationTask());
IO = RxJavaPlugins.initIoScheduler(new IOTask());
TRAMPOLINE = TrampolineScheduler.instance();
NEW_THREAD = RxJavaPlugins.initNewThreadScheduler(new NewThreadTask());
}
/** Utility class. */
private Schedulers() {
throw new IllegalStateException("No instances!");
}
/**
* Returns a default, shared {@link Scheduler} instance intended for computational work.
* <p>
* This can be used for event-loops, processing callbacks and other computational work.
* <p>
* It is not recommended to perform blocking, IO-bound work on this scheduler. Use {@link #io()} instead.
* <p>
* The default instance has a backing pool of single-threaded {@link ScheduledExecutorService} instances equal to
* the number of available processors ({@link java.lang.Runtime#availableProcessors()}) to the Java VM.
* <p>
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}.
* <p>
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker} instances, although
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or
* execute those tasks "unexpectedly".
* <p>
* If the {@link RxJavaPlugins#setFailOnNonBlockingScheduler(boolean)} is set to {@code true}, attempting to execute
* operators that block while running on this scheduler will throw an {@link IllegalStateException}.
* <p>
* You can control certain properties of this standard scheduler via system properties that have to be set
* before the {@code Schedulers} class is referenced in your code.
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong>
* <ul>
* <li>{@code rx3.computation-threads} (int): sets the number of threads in the {@code computation()} {@code Scheduler}, default is the number of available CPUs</li>
* <li>{@code rx3.computation-priority} (int): sets the thread priority of the {@code computation()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* </ul>
* <p>
* The default value of this scheduler can be overridden at initialization time via the
* {@link RxJavaPlugins#setInitComputationSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method.
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will
* result in a {@link NullPointerException}.
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance
* via the {@link RxJavaPlugins#setComputationSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method.
* <p>
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the
* {@link RxJavaPlugins#createComputationScheduler(ThreadFactory)} method. Note that such custom
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the
* (J2EE) container to unload properly.
* <p>Operators on the base reactive classes that use this scheduler are marked with the
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#COMPUTATION COMPUTATION})
* annotation.
* @return a {@code Scheduler} meant for computation-bound work
*/
@NonNull
public static Scheduler computation() {
return RxJavaPlugins.onComputationScheduler(COMPUTATION);
}
/**
* Returns a default, shared {@link Scheduler} instance intended for IO-bound work.
* <p>
* This can be used for asynchronously performing blocking IO.
* <p>
* The implementation is backed by a pool of single-threaded {@link ScheduledExecutorService} instances
* that will try to reuse previously started instances used by the worker
* returned by {@link io.reactivex.rxjava3.core.Scheduler#createWorker()} but otherwise will start a new backing
* {@link ScheduledExecutorService} instance. Note that this scheduler may create an unbounded number
* of worker threads that can result in system slowdowns or {@link OutOfMemoryError}. Therefore, for casual uses
* or when implementing an operator, the Worker instances must be disposed via {@link io.reactivex.rxjava3.core.Scheduler.Worker#dispose()}.
* <p>
* It is not recommended to perform computational work on this scheduler. Use {@link #computation()} instead.
* <p>
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}.
* <p>
* You can control certain properties of this standard scheduler via system properties that have to be set
* before the {@code Schedulers} class is referenced in your code.
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong>
* <ul>
* <li>{@code rx3.io-keep-alive-time} (long): sets the keep-alive time of the {@code io()} {@code Scheduler} workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li>
* <li>{@code rx3.io-priority} (int): sets the thread priority of the {@code io()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* <li>{@code rx3.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the
* {@code #io()} {@code Scheduler} to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li>
* </ul>
* <p>
* The default value of this scheduler can be overridden at initialization time via the
* {@link RxJavaPlugins#setInitIoSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method.
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will
* result in a {@link NullPointerException}.
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance
* via the {@link RxJavaPlugins#setIoSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method.
* <p>
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the
* {@link RxJavaPlugins#createIoScheduler(ThreadFactory)} method. Note that such custom
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the
* (J2EE) container to unload properly.
* <p>Operators on the base reactive classes that use this scheduler are marked with the
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#IO IO})
* annotation.
* <p>
* When the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} is disposed,
* the underlying worker can be released to the cached worker pool in two modes:
* <ul>
* <li>In <em>eager</em> mode (default), the underlying worker is returned immediately to the cached worker pool
* and can be reused much quicker by operators. The drawback is that if the currently running task doesn't
* respond to interruption in time or at all, this may lead to delays or deadlock with the reuse use of the
* underlying worker.
* </li>
* <li>In <em>scheduled</em> mode (enabled via the system parameter {@code rx3.io-scheduled-release}
* set to {@code true}), the underlying worker is returned to the cached worker pool only after the currently running task
* has finished. This can help prevent premature reuse of the underlying worker and likely won't lead to delays or
* deadlock with such reuses. The drawback is that the delay in release may lead to an excess amount of underlying
* workers being created.
* </li>
* </ul>
* @return a {@code Scheduler} meant for IO-bound work
*/
@NonNull
public static Scheduler io() {
return RxJavaPlugins.onIoScheduler(IO);
}
/**
* Returns a default, shared {@link Scheduler} instance whose {@link io.reactivex.rxjava3.core.Scheduler.Worker}
* instances queue work and execute them in a FIFO manner on one of the participating threads.
* <p>
* The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread
* without any queueing and the timed overloads use blocking sleep as well.
* <p>
* Note that this scheduler can't be reliably used to return the execution of
* tasks to the "main" thread. Such behavior requires a blocking-queueing scheduler currently not provided
* by RxJava itself but may be found in external libraries.
* <p>
* This scheduler can't be overridden via an {@link RxJavaPlugins} method.
* @return a {@code Scheduler} that queues work on the current thread
*/
@NonNull
public static Scheduler trampoline() {
return TRAMPOLINE;
}
/**
* Returns a default, shared {@link Scheduler} instance that creates a new {@link Thread} for each unit of work.
* <p>
* The default implementation of this scheduler creates a new, single-threaded {@link ScheduledExecutorService} for
* each invocation of the {@link Scheduler#scheduleDirect(Runnable)} (plus its overloads) and {@link Scheduler#createWorker()}
* methods, thus an unbounded number of worker threads may be created that can
* result in system slowdowns or {@link OutOfMemoryError}. Therefore, for casual uses or when implementing an operator,
* the Worker instances must be disposed via {@link io.reactivex.rxjava3.core.Scheduler.Worker#dispose()}.
* <p>
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}.
* <p>
* You can control certain properties of this standard scheduler via system properties that have to be set
* before the {@code Schedulers} class is referenced in your code.
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong>
* <ul>
* <li>{@code rx3.newthread-priority} (int): sets the thread priority of the {@code newThread()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* </ul>
* <p>
* The default value of this scheduler can be overridden at initialization time via the
* {@link RxJavaPlugins#setInitNewThreadSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method.
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will
* result in a {@link NullPointerException}.
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance
* via the {@link RxJavaPlugins#setNewThreadSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method.
* <p>
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the
* {@link RxJavaPlugins#createNewThreadScheduler(ThreadFactory)} method. Note that such custom
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the
* (J2EE) container to unload properly.
* <p>Operators on the base reactive classes that use this scheduler are marked with the
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#NEW_THREAD NEW_TRHEAD})
* annotation.
* @return a {@code Scheduler} that creates new threads
*/
@NonNull
public static Scheduler newThread() {
return RxJavaPlugins.onNewThreadScheduler(NEW_THREAD);
}
/**
* Returns a default, shared, single-thread-backed {@link Scheduler} instance for work
* requiring strongly-sequential execution on the same background thread.
* <p>
* Uses:
* <ul>
* <li>event loop</li>
* <li>support {@code Schedulers.from(}{@link Executor}{@code )} and {@code from(}{@link ExecutorService}{@code )} with delayed scheduling</li>
* <li>support benchmarks that pipeline data from some thread to another thread and
* avoid core-bashing of computation's round-robin nature</li>
* </ul>
* <p>
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}.
* <p>
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker} instances, although
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or
* execute those tasks "unexpectedly".
* <p>
* If the {@link RxJavaPlugins#setFailOnNonBlockingScheduler(boolean)} is set to {@code true}, attempting to execute
* operators that block while running on this scheduler will throw an {@link IllegalStateException}.
* <p>
* You can control certain properties of this standard scheduler via system properties that have to be set
* before the {@code Schedulers} class is referenced in your code.
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong>
* <ul>
* <li>{@code rx3.single-priority} (int): sets the thread priority of the {@code single()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
* </ul>
* <p>
* The default value of this scheduler can be overridden at initialization time via the
* {@link RxJavaPlugins#setInitSingleSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method.
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will
* result in a {@link NullPointerException}.
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance
* via the {@link RxJavaPlugins#setSingleSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method.
* <p>
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the
* {@link RxJavaPlugins#createSingleScheduler(ThreadFactory)} method. Note that such custom
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the
* (J2EE) container to unload properly.
* <p>Operators on the base reactive classes that use this scheduler are marked with the
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#SINGLE SINGLE})
* annotation.
* @return a {@code Scheduler} that shares a single backing thread.
* @since 2.0
*/
@NonNull
public static Scheduler single() {
return RxJavaPlugins.onSingleScheduler(SINGLE);
}
/**
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()}
* calls to it.
* <p>
* If the provided executor doesn't support any of the more specific standard Java executor
* APIs, tasks scheduled by this scheduler can't be interrupted when they are
* executing but only prevented from running prior to that. In addition, tasks scheduled with
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* Tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the
* {@link #from(Executor, boolean)} overload to enable task interruption via this wrapper.
* <p>
* If the provided executor supports the standard Java {@link ExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the provided executor. Note, however, if the provided
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled
* with a time delay close to each other may end up executing in different order than
* the original schedule() call was issued. This limitation may be lifted in a future patch.
* <p>
* The implementation of the Worker of this wrapper {@code Scheduler} is eager and will execute as many
* non-delayed tasks as it can, which may result in a longer than expected occupation of a
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness
* in case the worker runs on a shared underlying thread of the {@code Executor}.
* See {@link #from(Executor, boolean, boolean)} to create a wrapper that uses the underlying {@code Executor}
* more fairly.
* <p>
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided
* executor's lifecycle must be managed externally:
* <pre><code>
* ExecutorService exec = Executors.newSingleThreadedExecutor();
* try {
* Scheduler scheduler = Schedulers.from(exec);
* Flowable.just(1)
* .subscribeOn(scheduler)
* .map(v -> v + 1)
* .observeOn(scheduler)
* .blockingSubscribe(System.out::println);
* } finally {
* exec.shutdown();
* }
* </code></pre>
* <p>
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException}
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService})
* because such circumstances prevent RxJava from progressing flow-related activities correctly.
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
* the {@code RejectedExecutionException} is routed to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work.
* <p>
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or
* execute those tasks "unexpectedly".
* <p>
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance.
* <p>
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method
* before the {@code Schedulers} class itself is accessed.
* @param executor
* the executor to wrap
* @return the new {@code Scheduler} wrapping the {@code Executor}
* @see #from(Executor, boolean, boolean)
*/
@NonNull
public static Scheduler from(@NonNull Executor executor) {
return from(executor, false, false);
}
/**
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()}
* calls to it.
* <p>
* The tasks scheduled by the returned {@code Scheduler} and its {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker}
* can be optionally interrupted.
* <p>
* If the provided executor doesn't support any of the more specific standard Java executor
* APIs, tasks scheduled with a time delay or periodically will use the
* {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* If the provided executor supports the standard Java {@link ExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the provided executor. Note, however, if the provided
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled
* with a time delay close to each other may end up executing in different order than
* the original schedule() call was issued. This limitation may be lifted in a future patch.
* <p>
* The implementation of the {@code Worker} of this wrapper {@code Scheduler} is eager and will execute as many
* non-delayed tasks as it can, which may result in a longer than expected occupation of a
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness
* in case the worker runs on a shared underlying thread of the {@code Executor}.
* See {@link #from(Executor, boolean, boolean)} to create a wrapper that uses the underlying {@code Executor}
* more fairly.
* <p>
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided
* executor's lifecycle must be managed externally:
* <pre><code>
* ExecutorService exec = Executors.newSingleThreadedExecutor();
* try {
* Scheduler scheduler = Schedulers.from(exec, true);
* Flowable.just(1)
* .subscribeOn(scheduler)
* .map(v -> v + 1)
* .observeOn(scheduler)
* .blockingSubscribe(System.out::println);
* } finally {
* exec.shutdown();
* }
* </code></pre>
* <p>
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException}
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService})
* because such circumstances prevent RxJava from progressing flow-related activities correctly.
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
* the {@code RejectedExecutionException} is routed to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work.
* <p>
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or
* execute those tasks "unexpectedly".
* <p>
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance.
* <p>
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method
* before the {@code Schedulers} class itself is accessed.
* <p>History: 2.2.6 - experimental
* @param executor
* the executor to wrap
* @param interruptibleWorker if {@code true}, the tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} will
* be interrupted when the task is disposed.
* @return the new {@code Scheduler} wrapping the {@code Executor}
* @since 3.0.0
* @see #from(Executor, boolean, boolean)
*/
@NonNull
public static Scheduler from(@NonNull Executor executor, boolean interruptibleWorker) {
return from(executor, interruptibleWorker, false);
}
/**
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()}
* calls to it.
* <p>
* The tasks scheduled by the returned {@code Scheduler} and its {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker}
* can be optionally interrupted.
* <p>
* If the provided executor doesn't support any of the more specific standard Java executor
* APIs, tasks scheduled with a time delay or periodically will use the
* {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* If the provided executor supports the standard Java {@link ExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting
* before posting the actual task to the given executor.
* <p>
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API,
* tasks scheduled by this scheduler can be cancelled/interrupted by calling
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with
* a time delay or periodically will use the provided executor. Note, however, if the provided
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled
* with a time delay close to each other may end up executing in different order than
* the original schedule() call was issued. This limitation may be lifted in a future patch.
* <p>
* The implementation of the Worker of this wrapper {@code Scheduler} can operate in both eager (non-fair) and
* fair modes depending on the specified parameter. In <em>eager</em> mode, it will execute as many
* non-delayed tasks as it can, which may result in a longer than expected occupation of a
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness
* in case the worker runs on a shared underlying thread of the {@code Executor}. In <em>fair</em> mode,
* non-delayed tasks will still be executed in a FIFO and non-overlapping manner, but after each task,
* the execution for the next task is rescheduled with the same underlying {@code Executor}, allowing interleaving
* from both the same {@code Scheduler} or other external usages of the underlying {@code Executor}.
* <p>
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided
* executor's lifecycle must be managed externally:
* <pre><code>
* ExecutorService exec = Executors.newSingleThreadedExecutor();
* try {
* Scheduler scheduler = Schedulers.from(exec, true, true);
* Flowable.just(1)
* .subscribeOn(scheduler)
* .map(v -> v + 1)
* .observeOn(scheduler)
* .blockingSubscribe(System.out::println);
* } finally {
* exec.shutdown();
* }
* </code></pre>
* <p>
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException}
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService})
* because such circumstances prevent RxJava from progressing flow-related activities correctly.
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
* the {@code RejectedExecutionException} is routed to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work.
* <p>
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or
* execute those tasks "unexpectedly".
* <p>
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance.
* <p>
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method
* before the {@code Schedulers} class itself is accessed.
*
* @param executor
* the executor to wrap
* @param interruptibleWorker if {@code true}, the tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} will
* be interrupted when the task is disposed.
* @param fair if {@code true}, tasks submitted to the {@code Scheduler} or {@code Worker} will be executed by the underlying {@code Executor} one after the other, still
* in a FIFO and non-overlapping manner, but allows interleaving with other tasks submitted to the underlying {@code Executor}.
* If {@code false}, the underlying FIFO scheme will execute as many tasks as it can before giving up the underlying {@code Executor} thread.
* @return the new {@code Scheduler} wrapping the {@code Executor}
* @since 3.0.0
*/
@NonNull
public static Scheduler from(@NonNull Executor executor, boolean interruptibleWorker, boolean fair) {
return RxJavaPlugins.createExecutorScheduler(executor, interruptibleWorker, fair);
}
/**
* Shuts down the standard {@link Scheduler}s.
* <p>The operation is idempotent and thread-safe.
*/
public static void shutdown() {
computation().shutdown();
io().shutdown();
newThread().shutdown();
single().shutdown();
trampoline().shutdown();
}
/**
* Starts the standard {@link Scheduler}s.
* <p>The operation is idempotent and thread-safe.
*/
public static void start() {
computation().start();
io().start();
newThread().start();
single().start();
trampoline().start();
}
static final class IOTask implements Supplier<Scheduler> {
@Override
public Scheduler get() {
return IoHolder.DEFAULT;
}
}
static final class NewThreadTask implements Supplier<Scheduler> {
@Override
public Scheduler get() {
return NewThreadHolder.DEFAULT;
}
}
static final class SingleTask implements Supplier<Scheduler> {
@Override
public Scheduler get() {
return SingleHolder.DEFAULT;
}
}
static final class ComputationTask implements Supplier<Scheduler> {
@Override
public Scheduler get() {
return ComputationHolder.DEFAULT;
}
}
}
| ReactiveX/RxJava | src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java |
44,964 | /*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.handler.codec.dns;
import io.netty.util.internal.UnstableApi;
/**
* A DNS resource record.
*/
@UnstableApi
public interface DnsRecord {
/**
* DNS resource record class: {@code IN}
*/
int CLASS_IN = 0x0001;
/**
* DNS resource record class: {@code CSNET}
*/
int CLASS_CSNET = 0x0002;
/**
* DNS resource record class: {@code CHAOS}
*/
int CLASS_CHAOS = 0x0003;
/**
* DNS resource record class: {@code HESIOD}
*/
int CLASS_HESIOD = 0x0004;
/**
* DNS resource record class: {@code NONE}
*/
int CLASS_NONE = 0x00fe;
/**
* DNS resource record class: {@code ANY}
*/
int CLASS_ANY = 0x00ff;
/**
* Returns the name of this resource record.
*/
String name();
/**
* Returns the type of this resource record.
*/
DnsRecordType type();
/**
* Returns the class of this resource record.
*
* @return the class value, usually one of the following:
* <ul>
* <li>{@link #CLASS_IN}</li>
* <li>{@link #CLASS_CSNET}</li>
* <li>{@link #CLASS_CHAOS}</li>
* <li>{@link #CLASS_HESIOD}</li>
* <li>{@link #CLASS_NONE}</li>
* <li>{@link #CLASS_ANY}</li>
* </ul>
*/
int dnsClass();
/**
* Returns the time to live after reading for this resource record.
*/
long timeToLive();
}
| netty/netty | codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java |
44,965 | package com.baeldung.pmd;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class UnitTestNamingConventionRule extends AbstractJavaRule {
private static List<String> allowedEndings = Arrays.asList(
"IntegrationTest",
"IntTest",
"ManualTest",
"JdbcTest",
"LiveTest",
"UnitTest",
"jmhTest");
@Override
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
String className = node.getSimpleName();
Objects.requireNonNull(className);
if (className.endsWith("SpringContextTest")) {
return data;
}
if (className.endsWith("Tests")
|| (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
addViolation(data, node);
}
return data;
}
}
| eugenp/tutorials | custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java |
44,966 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml.process;
import java.io.Closeable;
import java.io.IOException;
import java.time.ZonedDateTime;
/**
* Interface representing a native C++ process
*/
public interface NativeProcess extends Closeable {
/**
* Is the process ready to receive data?
* @return {@code true} if the process is ready to receive data
*/
boolean isReady();
/**
* Write the record to the process. The record parameter should not be encoded
* (i.e. length encoded) the implementation will apply the correct encoding.
*
* @param record Plain array of strings, implementors of this class should
* encode the record appropriately
* @throws IOException If the write failed
*/
void writeRecord(String[] record) throws IOException;
/**
* Ask the process to persist its state in the background
* @throws IOException If writing the request fails
*/
void persistState() throws IOException;
/**
* Ask the process to persist state, even if it is unchanged.
* @param snapshotTimestampMs The snapshot timestamp in milliseconds
* @param snapshotId The id of the snapshot to save
* @param snapshotDescription the snapshot description
* @throws IOException if writing the request fails
*/
void persistState(long snapshotTimestampMs, String snapshotId, String snapshotDescription) throws IOException;
/**
* Flush the output data stream
*/
void flushStream() throws IOException;
/**
* Kill the process. Do not wait for it to stop gracefully.
* @param awaitCompletion Indicates whether to wait for the process to die. Even if this
* is set to <code>true</code> the process will not complete gracefully.
*/
void kill(boolean awaitCompletion) throws IOException;
/**
* The time the process was started
* @return Process start time
*/
ZonedDateTime getProcessStartTime();
/**
* Returns true if the process still running.
* Methods instructing the process are essentially
* asynchronous; the command will be continue to execute in the process after
* the call has returned.
* This method tests whether something catastrophic
* occurred in the process during its execution.
* @return True if the process is still running
*/
boolean isProcessAlive();
/**
* Check whether the process terminated given a grace period.
*
* Processing errors are highly likely caused by the process being unexpectedly
* terminated.
*
* Workaround: As we can not easily check if the process is alive, we rely on
* the logPipe being ended. As the loghandler runs in another thread which
* might fall behind this one, we give it a grace period.
*
* @return false if process has ended for sure, true if it probably still runs
*/
boolean isProcessAliveAfterWaiting();
/**
* Read any content in the error output buffer.
* @return An error message or empty String if no error.
*/
String readError();
}
| elastic/elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeProcess.java |
44,967 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.channel;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.AbstractConstant;
import io.netty.util.ConstantPool;
import io.netty.util.internal.ObjectUtil;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* A {@link ChannelOption} allows to configure a {@link ChannelConfig} in a type-safe
* way. Which {@link ChannelOption} is supported depends on the actual implementation
* of {@link ChannelConfig} and may depend on the nature of the transport it belongs
* to.
*
* @param <T> the type of the value which is valid for the {@link ChannelOption}
*/
public class ChannelOption<T> extends AbstractConstant<ChannelOption<T>> {
private static final ConstantPool<ChannelOption<Object>> pool = new ConstantPool<ChannelOption<Object>>() {
@Override
protected ChannelOption<Object> newConstant(int id, String name) {
return new ChannelOption<Object>(id, name);
}
};
/**
* Returns the {@link ChannelOption} of the specified name.
*/
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> valueOf(String name) {
return (ChannelOption<T>) pool.valueOf(name);
}
/**
* Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
*/
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> valueOf(Class<?> firstNameComponent, String secondNameComponent) {
return (ChannelOption<T>) pool.valueOf(firstNameComponent, secondNameComponent);
}
/**
* Returns {@code true} if a {@link ChannelOption} exists for the given {@code name}.
*/
public static boolean exists(String name) {
return pool.exists(name);
}
/**
* Creates a new {@link ChannelOption} for the given {@code name} or fail with an
* {@link IllegalArgumentException} if a {@link ChannelOption} for the given {@code name} exists.
*
* @deprecated use {@link #valueOf(String)}.
*/
@Deprecated
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> newInstance(String name) {
return (ChannelOption<T>) pool.newInstance(name);
}
public static final ChannelOption<ByteBufAllocator> ALLOCATOR = valueOf("ALLOCATOR");
public static final ChannelOption<RecvByteBufAllocator> RCVBUF_ALLOCATOR = valueOf("RCVBUF_ALLOCATOR");
public static final ChannelOption<MessageSizeEstimator> MESSAGE_SIZE_ESTIMATOR = valueOf("MESSAGE_SIZE_ESTIMATOR");
public static final ChannelOption<Integer> CONNECT_TIMEOUT_MILLIS = valueOf("CONNECT_TIMEOUT_MILLIS");
/**
* @deprecated Use {@link MaxMessagesRecvByteBufAllocator}
* and {@link MaxMessagesRecvByteBufAllocator#maxMessagesPerRead(int)}.
*/
@Deprecated
public static final ChannelOption<Integer> MAX_MESSAGES_PER_READ = valueOf("MAX_MESSAGES_PER_READ");
public static final ChannelOption<Integer> MAX_MESSAGES_PER_WRITE = valueOf("MAX_MESSAGES_PER_WRITE");
public static final ChannelOption<Integer> WRITE_SPIN_COUNT = valueOf("WRITE_SPIN_COUNT");
/**
* @deprecated Use {@link #WRITE_BUFFER_WATER_MARK}
*/
@Deprecated
public static final ChannelOption<Integer> WRITE_BUFFER_HIGH_WATER_MARK = valueOf("WRITE_BUFFER_HIGH_WATER_MARK");
/**
* @deprecated Use {@link #WRITE_BUFFER_WATER_MARK}
*/
@Deprecated
public static final ChannelOption<Integer> WRITE_BUFFER_LOW_WATER_MARK = valueOf("WRITE_BUFFER_LOW_WATER_MARK");
public static final ChannelOption<WriteBufferWaterMark> WRITE_BUFFER_WATER_MARK =
valueOf("WRITE_BUFFER_WATER_MARK");
public static final ChannelOption<Boolean> ALLOW_HALF_CLOSURE = valueOf("ALLOW_HALF_CLOSURE");
public static final ChannelOption<Boolean> AUTO_READ = valueOf("AUTO_READ");
/**
* If {@code true} then the {@link Channel} is closed automatically and immediately on write failure.
* The default value is {@code true}.
*/
public static final ChannelOption<Boolean> AUTO_CLOSE = valueOf("AUTO_CLOSE");
public static final ChannelOption<Boolean> SO_BROADCAST = valueOf("SO_BROADCAST");
public static final ChannelOption<Boolean> SO_KEEPALIVE = valueOf("SO_KEEPALIVE");
public static final ChannelOption<Integer> SO_SNDBUF = valueOf("SO_SNDBUF");
public static final ChannelOption<Integer> SO_RCVBUF = valueOf("SO_RCVBUF");
public static final ChannelOption<Boolean> SO_REUSEADDR = valueOf("SO_REUSEADDR");
public static final ChannelOption<Integer> SO_LINGER = valueOf("SO_LINGER");
public static final ChannelOption<Integer> SO_BACKLOG = valueOf("SO_BACKLOG");
public static final ChannelOption<Integer> SO_TIMEOUT = valueOf("SO_TIMEOUT");
public static final ChannelOption<Integer> IP_TOS = valueOf("IP_TOS");
public static final ChannelOption<InetAddress> IP_MULTICAST_ADDR = valueOf("IP_MULTICAST_ADDR");
public static final ChannelOption<NetworkInterface> IP_MULTICAST_IF = valueOf("IP_MULTICAST_IF");
public static final ChannelOption<Integer> IP_MULTICAST_TTL = valueOf("IP_MULTICAST_TTL");
public static final ChannelOption<Boolean> IP_MULTICAST_LOOP_DISABLED = valueOf("IP_MULTICAST_LOOP_DISABLED");
public static final ChannelOption<Boolean> TCP_NODELAY = valueOf("TCP_NODELAY");
/**
* Client-side TCP FastOpen. Sending data with the initial TCP handshake.
*/
public static final ChannelOption<Boolean> TCP_FASTOPEN_CONNECT = valueOf("TCP_FASTOPEN_CONNECT");
/**
* Server-side TCP FastOpen. Configures the maximum number of outstanding (waiting to be accepted) TFO connections.
*/
public static final ChannelOption<Integer> TCP_FASTOPEN = valueOf(ChannelOption.class, "TCP_FASTOPEN");
@Deprecated
public static final ChannelOption<Boolean> DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION =
valueOf("DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION");
public static final ChannelOption<Boolean> SINGLE_EVENTEXECUTOR_PER_GROUP =
valueOf("SINGLE_EVENTEXECUTOR_PER_GROUP");
/**
* Creates a new {@link ChannelOption} with the specified unique {@code name}.
*/
private ChannelOption(int id, String name) {
super(id, name);
}
@Deprecated
protected ChannelOption(String name) {
this(pool.nextId(), name);
}
/**
* Validate the value which is set for the {@link ChannelOption}. Sub-classes
* may override this for special checks.
*/
public void validate(T value) {
ObjectUtil.checkNotNull(value, "value");
}
}
| netty/netty | transport/src/main/java/io/netty/channel/ChannelOption.java |
44,968 | /*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you 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:
*
* https://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 io.netty.handler.codec.dns;
import io.netty.util.internal.UnstableApi;
/**
* A DNS question.
*/
@UnstableApi
public interface DnsQuestion extends DnsRecord {
/**
* An unused property. This method will always return {@code 0}.
*/
@Override
long timeToLive();
}
| netty/netty | codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java |
44,969 | /*
* Copyright 2002-2017 the original author or authors.
*
* 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
*
* https://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.springframework.jms.connection;
import jakarta.jms.CompletionListener;
import jakarta.jms.Destination;
import jakarta.jms.JMSException;
import jakarta.jms.Message;
import jakarta.jms.MessageProducer;
import jakarta.jms.Queue;
import jakarta.jms.QueueSender;
import jakarta.jms.Topic;
import jakarta.jms.TopicPublisher;
import org.springframework.lang.Nullable;
/**
* JMS MessageProducer decorator that adapts calls to a shared MessageProducer
* instance underneath, managing QoS settings locally within the decorator.
*
* @author Juergen Hoeller
* @since 2.5.3
*/
class CachedMessageProducer implements MessageProducer, QueueSender, TopicPublisher {
private final MessageProducer target;
@Nullable
private Boolean originalDisableMessageID;
@Nullable
private Boolean originalDisableMessageTimestamp;
@Nullable
private Long originalDeliveryDelay;
private int deliveryMode;
private int priority;
private long timeToLive;
public CachedMessageProducer(MessageProducer target) throws JMSException {
this.target = target;
this.deliveryMode = target.getDeliveryMode();
this.priority = target.getPriority();
this.timeToLive = target.getTimeToLive();
}
@Override
public void setDisableMessageID(boolean disableMessageID) throws JMSException {
if (this.originalDisableMessageID == null) {
this.originalDisableMessageID = this.target.getDisableMessageID();
}
this.target.setDisableMessageID(disableMessageID);
}
@Override
public boolean getDisableMessageID() throws JMSException {
return this.target.getDisableMessageID();
}
@Override
public void setDisableMessageTimestamp(boolean disableMessageTimestamp) throws JMSException {
if (this.originalDisableMessageTimestamp == null) {
this.originalDisableMessageTimestamp = this.target.getDisableMessageTimestamp();
}
this.target.setDisableMessageTimestamp(disableMessageTimestamp);
}
@Override
public boolean getDisableMessageTimestamp() throws JMSException {
return this.target.getDisableMessageTimestamp();
}
@Override
public void setDeliveryDelay(long deliveryDelay) throws JMSException {
if (this.originalDeliveryDelay == null) {
this.originalDeliveryDelay = this.target.getDeliveryDelay();
}
this.target.setDeliveryDelay(deliveryDelay);
}
@Override
public long getDeliveryDelay() throws JMSException {
return this.target.getDeliveryDelay();
}
@Override
public void setDeliveryMode(int deliveryMode) {
this.deliveryMode = deliveryMode;
}
@Override
public int getDeliveryMode() {
return this.deliveryMode;
}
@Override
public void setPriority(int priority) {
this.priority = priority;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
@Override
public long getTimeToLive() {
return this.timeToLive;
}
@Override
public Destination getDestination() throws JMSException {
return this.target.getDestination();
}
@Override
public Queue getQueue() throws JMSException {
return (Queue) this.target.getDestination();
}
@Override
public Topic getTopic() throws JMSException {
return (Topic) this.target.getDestination();
}
@Override
public void send(Message message) throws JMSException {
this.target.send(message, this.deliveryMode, this.priority, this.timeToLive);
}
@Override
public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
this.target.send(message, deliveryMode, priority, timeToLive);
}
@Override
public void send(Destination destination, Message message) throws JMSException {
this.target.send(destination, message, this.deliveryMode, this.priority, this.timeToLive);
}
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
this.target.send(destination, message, deliveryMode, priority, timeToLive);
}
@Override
public void send(Message message, CompletionListener completionListener) throws JMSException {
this.target.send(message, this.deliveryMode, this.priority, this.timeToLive, completionListener);
}
@Override
public void send(Message message, int deliveryMode, int priority, long timeToLive,
CompletionListener completionListener) throws JMSException {
this.target.send(message, deliveryMode, priority, timeToLive, completionListener);
}
@Override
public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException {
this.target.send(destination, message, this.deliveryMode, this.priority, this.timeToLive, completionListener);
}
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority,
long timeToLive, CompletionListener completionListener) throws JMSException {
this.target.send(destination, message, deliveryMode, priority, timeToLive, completionListener);
}
@Override
public void send(Queue queue, Message message) throws JMSException {
this.target.send(queue, message, this.deliveryMode, this.priority, this.timeToLive);
}
@Override
public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
this.target.send(queue, message, deliveryMode, priority, timeToLive);
}
@Override
public void publish(Message message) throws JMSException {
this.target.send(message, this.deliveryMode, this.priority, this.timeToLive);
}
@Override
public void publish(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
this.target.send(message, deliveryMode, priority, timeToLive);
}
@Override
public void publish(Topic topic, Message message) throws JMSException {
this.target.send(topic, message, this.deliveryMode, this.priority, this.timeToLive);
}
@Override
public void publish(Topic topic, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
this.target.send(topic, message, deliveryMode, priority, timeToLive);
}
@Override
public void close() throws JMSException {
// It's a cached MessageProducer... reset properties only.
if (this.originalDisableMessageID != null) {
this.target.setDisableMessageID(this.originalDisableMessageID);
this.originalDisableMessageID = null;
}
if (this.originalDisableMessageTimestamp != null) {
this.target.setDisableMessageTimestamp(this.originalDisableMessageTimestamp);
this.originalDisableMessageTimestamp = null;
}
if (this.originalDeliveryDelay != null) {
this.target.setDeliveryDelay(this.originalDeliveryDelay);
this.originalDeliveryDelay = null;
}
}
@Override
public String toString() {
return "Cached JMS MessageProducer: " + this.target;
}
}
| spring-projects/spring-framework | spring-jms/src/main/java/org/springframework/jms/connection/CachedMessageProducer.java |
44,977 | package ai.engine;
import d.file.Dir;
import d.prop.OProps;
import d.utils.DateHelper;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class AiProps extends OProps {
static final public String KEY_dirFiles = "dirFiles";
static final public String KEY_dbMySQLdump = "db.mySqlDump";
static final public String KEY_dbBackupDir = "db.dirBackup";
// static final public String KEY_emailAccount = "email.account";
// static final public String KEY_emailPassword = "email.password";
static private boolean m_bOnDrakatorServer;
public AiProps(File f) throws Exception {
createAddProp(KEY_dirFiles, "aisFiles", "Φάκελος αρχείων");
////////////////////////////
createAddProp ("db", null, "db");
createAddProp (KEY_dbMySQLdump, "C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin\\mysqldump", "mySqlDump");
createAddProp (KEY_dbBackupDir, "/backup/dbs", "backup dir");
////////////////////////////
createAddProp("email", null, "email");
load_keepSchema(f,true);
// IPropEditor.setDefaultEditor(this, KEY_dirFiles);
// IPropEditor.setDefaultEditor(this, KEY_dbMySQLdump);
// IPropEditor.setDefaultEditor(this, KEY_dbBackupDir);
}
///////////////////////////
///////////////////////////
public String getDirFiles () throws Exception {
String dir = getStr(KEY_dirFiles);
Dir.createThisDirectory (dir);
return dir;
}
public File getDirFilesF () throws Exception {
return new File(getDirFiles());
}
public void setDbBackupDir (String val) throws Exception {
setStr(KEY_dbBackupDir, val);
}
public String getDbBackupDir (boolean bQuoted) throws Exception {
String s = getStr(KEY_dbBackupDir);
if (bQuoted)
s = checkPathQuotes (s);
return s;
}
public String getStingTimeStamp (Date date)
{
StringBuffer sb = new StringBuffer();
Calendar c = DateHelper.getCalendarFromDate(date);
String s = String.valueOf(c.get(Calendar.YEAR));
sb.append (s + "_");
s = String.valueOf(c.get(Calendar.MONTH)+1);
while (s.length() < 2)
s = "0"+s;
sb.append (s + "_");
s = String.valueOf(c.get(Calendar.DATE));
while (s.length() < 2)
s = "0"+s;
sb.append (s);
return sb.toString ();
}
public void setDbMySqlDump (String val) throws Exception {
setStr(KEY_dbMySQLdump, val);
}
public String getDbMySqlDump (boolean bQuoted) throws Exception {
String s = getStr(KEY_dbMySQLdump);
if (bQuoted)
s = checkPathQuotes (s);
return s;
}
// public void setEmailAccount (String val) throws Exception {
// setStr(KEY_emailAccount, val);
// }
// public String getEmailAccount () throws Exception {
// return getStr(KEY_emailAccount);
// }
//
// public void setEmailPassword (String val) throws Exception {
// setStr(KEY_emailPassword, val);
// }
// public String getEmailPassword () throws Exception {
// return getStr(KEY_emailPassword);
// }
static public String checkPathQuotes (String path) {
if (path.contains(" ") && !path.contains("\""))
path = "\""+path+"\"";
return path;
}
}
| drakator/ais | src/main/java/ai/engine/AiProps.java |
44,979 | package com.amaxilatis.metis.server.service;
import com.amaxilatis.metis.model.FileJobResult;
import com.amaxilatis.metis.server.config.MetisProperties;
import com.amaxilatis.metis.server.model.ImageFileInfo;
import com.amaxilatis.metis.server.util.FileUtils;
import com.amaxilatis.metis.util.FileNameUtils;
import com.drew.lang.Charsets;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import static com.amaxilatis.metis.server.util.ResultsUtils.*;
import static com.amaxilatis.metis.util.FileNameUtils.createDirectories;
import static com.amaxilatis.metis.util.FileNameUtils.deleteIfExists;
import static com.amaxilatis.metis.util.FileNameUtils.getResultFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
@Slf4j
@Service
@RequiredArgsConstructor
public class FileService {
public static final String FOLDER_TITLE = "Φάκελος";
public static final String CHECKS_TITLE = "Έλεγχοι";
public static final String FILE_TITLE = "ΑΡΧΕΙΟ";
public static final String CHECK_TITLE = "ΕΛΕΓΧΟΣ %d";
public static final String NOTES_TITLE = "ΠΑΡΑΤΗΡΗΣΕΙΣ %d";
public static final String CHECK_OK = "ΟΚ";
public static final String CHECK_NOK = "ΛΑΘΟΣ";
private final MetisProperties props;
final ExecutorService tpe = Executors.newFixedThreadPool(1);
public String getResultsLocation() {
return props.getResultsLocation();
}
public String getHistogramLocation() {
return props.getHistogramLocation();
}
public String getCloudMaskLocation() {
return props.getCloudMaskLocation();
}
public String getUncompressedLocation() {
return props.getUncompressedLocation();
}
public String getFilesLocation() {
return props.getFilesLocation();
}
public void createTempReport(final String name) {
writeToFile(name, "", false);
}
public void append(final String name, final String text) {
writeToFile(name, text);
}
public void append(final String name, final List<String> parts) {
writeToFile(name, StringUtils.join(parts, ","));
}
public String csv2xlsxName(final String name) {
return name.replace(".csv", ".xlsx");
}
public String csv2xlsx(final String name) {
final String xlsxFileName = csv2xlsxName(name);
final File outFile = new File(xlsxFileName);
try (final FileOutputStream fos = new FileOutputStream(outFile)) {
final Workbook wb = new XSSFWorkbook();
final Sheet sheet = wb.createSheet("report");
boolean first = true;
try (CSVReader reader = new CSVReader(new FileReader(name, Charsets.UTF_8))) {
List<String[]> r = reader.readAll();
for (String[] strings : r) {
Row row;
if (first) {
row = appendRow(sheet, 1);
first = false;
} else {
row = appendRow(sheet);
}
Arrays.stream(strings).forEach(s -> appendCell(row, s));
}
r.forEach(x -> {
});
} catch (CsvException e) {
log.error(e.getMessage(), e);
}
wb.write(fos);
wb.close();
return xlsxFileName;
} catch (IOException e) {
log.error(e.getMessage(), e);
boolean result = outFile.delete();
log.error("delete outFile {} {}", outFile.getName(), result);
}
return null;
}
private void writeToFile(final String name, final String text) {
writeToFile(name, text, true);
}
@Synchronized
private void writeToFile(final String name, final String text, final boolean append) {
try {
final FileWriter myWriter = new FileWriter(name, Charsets.UTF_8, append);
myWriter.write(text + "\n");
myWriter.flush();
myWriter.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
private static Row appendRow(final Sheet sheet) {
return appendRow(sheet, 1);
}
private static Row appendRow(final Sheet sheet, final int rowOffset) {
return sheet.createRow(sheet.getLastRowNum() + rowOffset);
}
private static void appendCell(final Row row, final List<String> text) {
text.forEach(s -> appendCell(row, s));
}
private static void appendCell(final Row row, final String text) {
final Cell cell = row.createCell(row.getLastCellNum() == -1 ? 0 : row.getLastCellNum());
cell.setCellValue(text);
}
final Map<String, SortedSet<ImageFileInfo>> images = new HashMap<>();
final SortedSet<ImageFileInfo> imagesDirs = new TreeSet<>();
final ObjectMapper mapper = new ObjectMapper();
@PostConstruct
public void init() {
checkAndCreateDirectory(props.getReportLocation());
checkAndCreateDirectory(props.getResultsLocation());
checkAndCreateDirectory(props.getThumbnailLocation());
checkAndCreateDirectory(props.getHistogramLocation());
checkAndCreateDirectory(props.getCloudMaskLocation());
checkAndCreateDirectory(props.getUncompressedLocation());
updateImageDirs(true, false);
}
/**
* Checks if the required directory exists and creates it if needed.
*
* @param location the directory to create
* @return true if the directory exists or is created, false if there was an error.
*/
private boolean checkAndCreateDirectory(final String location) {
return createDirectories(new File(location));
}
/**
* Updates the list of available image directories and image files.
*
* @param generateThumbnails flag to generate or not thumbnails for the detected images.
* @param cleanupNonExisting flag to delete or not non-existing dataset result directories (thumbnails, cloud masks, histograms).
*/
public void updateImageDirs(final boolean generateThumbnails, final boolean cleanupNonExisting) {
long start = System.currentTimeMillis();
imagesDirs.clear();
images.clear();
log.debug("[updateImageDirs] filesLocation[{}]: {}", new File(props.getFilesLocation()).exists(), props.getFilesLocation());
final File[] imageDirectoryList = new File(props.getFilesLocation()).listFiles(File::isDirectory);
log.debug("[updateImageDirs] imageDirectoryList: {}", Arrays.toString(imageDirectoryList));
if (imageDirectoryList != null) {
Arrays.stream(imageDirectoryList).forEach(imagesDirectory -> {
final String imagesDirectoryName = imagesDirectory.getName();
log.debug("[updateImageDirs] imagesDirectory: {}", imagesDirectoryName);
images.put(imagesDirectoryName, new TreeSet<>());
final File[] filesList = imagesDirectory.listFiles((dir, name) -> StringUtils.endsWithAny(name.toLowerCase(), ".tif", "jp2"));
if (filesList != null) {
final Set<ImageFileInfo> imageSet = Arrays.stream(filesList).map(image -> {
final String imageName = image.getName();
if (generateThumbnails) {
tpe.execute(() -> getImageThumbnail(imagesDirectoryName, imageName));
}
log.trace("[updateImageDirs] imagesDirectory: {} image: {}", imagesDirectoryName, imageName);
return ImageFileInfo.builder().name(imageName).hash(getStringHash(imageName)).build();
}).collect(Collectors.toSet());
if (!imageSet.isEmpty()) {
images.get(imagesDirectoryName).addAll(imageSet);
imagesDirs.add(ImageFileInfo.builder().name(imagesDirectoryName).hash(getStringHash(imagesDirectoryName)).count(imageSet.size()).build());
checkAndCreateDirectory(props.getResultsLocation() + "/" + imagesDirectoryName);
checkAndCreateDirectory(props.getThumbnailLocation() + "/" + imagesDirectoryName);
checkAndCreateDirectory(props.getHistogramLocation() + "/" + imagesDirectoryName);
checkAndCreateDirectory(props.getCloudMaskLocation() + "/" + imagesDirectoryName);
checkAndCreateDirectory(props.getUncompressedLocation() + "/" + imagesDirectoryName);
}
}
});
//cleanup results from deleted files
Arrays.stream(imageDirectoryList).forEach(this::cleanupDirectoryResults);
if (cleanupNonExisting) {
//cleanup results from no longer existing dataset directories
log.info("cleanup results from no longer existing dataset directories");
cleanupResultsForNoLongerValidDirectories(props.getThumbnailLocation());
cleanupResultsForNoLongerValidDirectories(props.getCloudMaskLocation());
cleanupResultsForNoLongerValidDirectories(props.getHistogramLocation());
}
} else {
log.warn("[updateImageDirs] imageDirectoryList is null!!!");
}
log.info("[updateImageDirs] time:{}", (System.currentTimeMillis() - start));
}
/**
* Removes the directories inside the location that do not exist in the images' directory.
*
* @param location the location to clean up.
*/
private void cleanupResultsForNoLongerValidDirectories(final String location) {
final File locationFile = new File(location);
if (locationFile.exists() && locationFile.isDirectory()) {
Arrays.stream(Objects.requireNonNull(locationFile.listFiles())).filter(File::isDirectory).filter(file -> !images.containsKey(file.getName())).forEach(file -> {
try {
log.info("need to delete mask and thumbnail files for directory {}", file.getName());
deleteDirectory(file);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
});
}
}
/**
* Cleans old result files from the specified directory.
*
* @param imagesDirectory the directory contains the images results.
*/
private void cleanupDirectoryResults(final File imagesDirectory) {
final String imagesDirectoryName = imagesDirectory.getName();
final File files = new File(props.getResultsLocation(), imagesDirectoryName);
final File[] flist = files.listFiles();
if (flist != null) {
Arrays.stream(flist).forEach(file -> {
if (file.getName().endsWith(".result")) {
final String[] parts = file.getName().split("\\.");
final String filename = parts[0] + "." + parts[1];
if (!new File(new File(props.getFilesLocation(), imagesDirectoryName), filename).exists()) {
final boolean deleted = file.delete();
log.warn("removed[{}] old result[{}] for file {}", deleted, file.getName(), filename);
}
}
});
}
}
@Scheduled(fixedRate = 600000L)
public void runAllImages() {
images.forEach((directoryName, value) -> value.forEach(imageFileInfo -> {
if (!Files.exists(Paths.get(getImageThumbnailFilename(directoryName, imageFileInfo.getName())))) {
tpe.execute(() -> getImageThumbnail(directoryName, imageFileInfo.getName()));
}
}));
}
public SortedSet<ImageFileInfo> getImagesDirs() {
return imagesDirs;
}
public SortedSet<ImageFileInfo> listImages(final String directory) {
return images.get(directory);
}
public String getStringHash(final String name) {
return URLEncoder.encode(name, Charsets.UTF_8);
}
public String getStringFromHash(final String hash) {
//return Base64.decode(hash.replaceAll("-", "="));
return URLDecoder.decode(hash, Charsets.UTF_8);
}
public void clean(final String directory, final List<Integer> tasks) {
File filesDir = new File(props.getFilesLocation());
File filesSubDir = new File(filesDir, directory);
final List<File> fileList = new ArrayList<>();
Arrays.stream(Objects.requireNonNull(filesSubDir.listFiles())).filter(file -> file.getName().endsWith(".tif")).forEach(fileList::add);
tasks.forEach(task -> fileList.forEach(file -> cleanFileResults(directory, file, task)));
}
private void cleanFileResults(final String directory, final File file, final int task) {
File resultsDir = new File(props.getResultsLocation(), directory);
deleteIfExists(new File(resultsDir, FileNameUtils.getResultName(file, task)));
if (task == 4) {
deleteIfExists(new File(FileNameUtils.getImageCloudCoverMaskFilename(props.getCloudMaskLocation(), file.getParentFile().getName(), file.getName())));
deleteIfExists(new File(FileNameUtils.getImageNIRMaskFilename(props.getCloudMaskLocation(), file.getParentFile().getName(), file.getName())));
deleteIfExists(new File(FileNameUtils.getImageNDWIMaskFilename(props.getCloudMaskLocation(), file.getParentFile().getName(), file.getName())));
deleteIfExists(new File(FileNameUtils.getImageBSIMaskFilename(props.getCloudMaskLocation(), file.getParentFile().getName(), file.getName())));
deleteIfExists(new File(FileNameUtils.getImageWaterMaskFilename(props.getCloudMaskLocation(), file.getParentFile().getName(), file.getName())));
}
if (task == 5) {
deleteIfExists(new File(FileNameUtils.getImageHistogramFilename(props.getHistogramLocation(), file.getParentFile().getName(), file.getName())));
}
if (task == 9) {
deleteIfExists(new File(FileNameUtils.getImageColorBalanceMaskFilename(props.getHistogramLocation(), file.getParentFile().getName(), file.getName())));
}
}
public List<FileJobResult> getImageResults(final String decodedImageDir, final String decodedImage) {
File resultsDir = new File(props.getResultsLocation(), decodedImageDir);
File image = new File(resultsDir, decodedImage);
List<FileJobResult> results = new ArrayList<>();
for (int task = 0; task < 10; task++) {
File f = new File(resultsDir, FileNameUtils.getResultName(image, task));
if (f.exists()) {
try {
results.add(parseResult(f));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return results;
}
private FileJobResult parseResult(final File f) throws IOException {
return mapper.readValue(f, FileJobResult.class);
}
@Async
public void deleteFile(final String resultFile) {
try {
Thread.sleep(30000);
Files.deleteIfExists(Path.of(resultFile));
} catch (Exception e) {
log.warn(e.getMessage());
}
}
/**
* Returns the full path to the image's file.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's file.
*/
String getImageFilename(final String dir, final String name) {
return FileNameUtils.getImageFilename(props.getFilesLocation(), dir, name);
}
/**
* Returns the full path to the image's thumbnail.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's thumbnail file.
*/
String getImageThumbnailFilename(final String dir, final String name) {
return FileNameUtils.getImageThumbnailFilename(props.getThumbnailLocation(), dir, name);
}
/**
* Returns the full path to the image's histogram.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's histogram file.
*/
String getImageHistogramFilename(final String dir, final String name) {
return FileNameUtils.getImageHistogramFilename(props.getHistogramLocation(), dir, name);
}
/**
* Returns the full path to the image's color balance mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's color balance mask file.
*/
String getImageColorBalanceFilename(final String dir, final String name) {
return FileNameUtils.getImageColorBalanceMaskFilename(props.getHistogramLocation(), dir, name);
}
/**
* Returns the full path to the image's cloud coverage mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's cloud coverage mask file.
*/
String getImageCloudCoverFilename(final String dir, final String name) {
return FileNameUtils.getImageCloudCoverMaskFilename(props.getCloudMaskLocation(), dir, name);
}
/**
* Returns the full path to the image's NIR mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's NIR mask file.
*/
String getImageMaskNIRFilename(final String dir, final String name) {
return FileNameUtils.getImageNIRMaskFilename(props.getCloudMaskLocation(), dir, name);
}
/**
* Returns the full path to the image's NDWI mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's NDWI mask file.
*/
String getImageMaskNDWIFilename(final String dir, final String name) {
return FileNameUtils.getImageNDWIMaskFilename(props.getCloudMaskLocation(), dir, name);
}
/**
* Returns the full path to the image's BSI mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's BSI mask file.
*/
String getImageMaskBSIFilename(final String dir, final String name) {
return FileNameUtils.getImageBSIMaskFilename(props.getCloudMaskLocation(), dir, name);
}
/**
* Returns the full path to the image's WATER mask.
*
* @param dir the directory of the image.
* @param name the name of the image.
* @return the full path to the image's WATER mask file.
*/
String getImageMaskWaterFilename(final String dir, final String name) {
return FileNameUtils.getImageWaterMaskFilename(props.getCloudMaskLocation(), dir, name);
}
/**
* Get or create and get the thumbnail of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the thumbnail of the image.
*/
public File getImageThumbnail(final String directory, final String name) {
final File thumbnailFile = new File(getImageThumbnailFilename(directory, name));
log.debug("[thumbnail|{}|{}] {}", directory, name, thumbnailFile.getAbsolutePath());
//check if directory exists
if (!thumbnailFile.getParentFile().exists()) {
createDirectories(thumbnailFile.getParentFile());
}
//check if file exists
if (thumbnailFile.exists()) {
return thumbnailFile;
} else {
long start = System.currentTimeMillis();
try {
FileUtils.makeThumbnail(new File(getImageFilename(directory, name)), thumbnailFile, 450, 339);
log.info("[{}][thumbnail-create] dir:{} took:{}", name, directory, (System.currentTimeMillis() - start));
return thumbnailFile;
} catch (IOException e) {
return null;
}
}
}
/**
* Get or create and get the histogram of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the histogram of the image.
*/
public File getImageHistogram(final String directory, final String name) {
final File histogramFile = new File(getImageHistogramFilename(directory, name));
log.debug("[{}][histogram] dir:{} path:{}", name, directory, histogramFile.getAbsolutePath());
//check if directory exists
if (!histogramFile.getParentFile().exists()) {
createDirectories(histogramFile.getParentFile());
}
//check if file exists
if (histogramFile.exists()) {
return histogramFile;
} else {
return null;
}
}
/**
* Get or create and get the color balance of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the color balance of the image.
*/
public File getImageColorBalance(final String directory, final String name) {
final File colorBalanceFile = new File(getImageColorBalanceFilename(directory, name));
log.debug("[{}][colorBalance] dir:{} path:{}", name, directory, colorBalanceFile.getAbsolutePath());
//check if directory exists
if (!colorBalanceFile.getParentFile().exists()) {
createDirectories(colorBalanceFile.getParentFile());
}
//check if file exists
if (colorBalanceFile.exists()) {
return colorBalanceFile;
} else {
return null;
}
}
/**
* Get or create and get the NIR of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the NIR mask of the image.
*/
public File getImageMaskNIR(final String directory, final String name) {
final File maskNIRFile = new File(getImageMaskNIRFilename(directory, name));
log.debug("[{}][nir] dir:{} path:{}", name, directory, maskNIRFile.getAbsolutePath());
//check if directory exists
if (!maskNIRFile.getParentFile().exists()) {
maskNIRFile.getParentFile().mkdir();
}
//check if file exists
if (maskNIRFile.exists()) {
return maskNIRFile;
} else {
return null;
}
}
/**
* Get or create and get the NDWI of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the NDWI mask of the image.
*/
public File getImageMaskNDWI(final String directory, final String name) {
final File maskNDWIFile = new File(getImageMaskNDWIFilename(directory, name));
log.debug("[{}][ndwi] dir:{} path:{}", name, directory, maskNDWIFile.getAbsolutePath());
//check if directory exists
if (!maskNDWIFile.getParentFile().exists()) {
maskNDWIFile.getParentFile().mkdir();
}
//check if file exists
if (maskNDWIFile.exists()) {
return maskNDWIFile;
} else {
return null;
}
}
/**
* Get or create and get the BSI of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the BSI mask of the image.
*/
public File getImageMaskBSI(final String directory, final String name) {
final File maskBSIFile = new File(getImageMaskBSIFilename(directory, name));
log.debug("[{}][bsi] dir:{} path:{}", name, directory, maskBSIFile.getAbsolutePath());
//check if directory exists
if (!maskBSIFile.getParentFile().exists()) {
maskBSIFile.getParentFile().mkdir();
}
//check if file exists
if (maskBSIFile.exists()) {
return maskBSIFile;
} else {
return null;
}
}
/**
* Get or create and get the WATER of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the WATER mask of the image.
*/
public File getImageMaskWater(final String directory, final String name) {
final File maskWaterFile = new File(getImageMaskWaterFilename(directory, name));
log.debug("[{}][water] dir:{} path:{}", name, directory, maskWaterFile.getAbsolutePath());
//check if directory exists
if (!maskWaterFile.getParentFile().exists()) {
maskWaterFile.getParentFile().mkdir();
}
//check if file exists
if (maskWaterFile.exists()) {
return maskWaterFile;
} else {
return null;
}
}
/**
* Get or create and get the cloud coverage mask of the image.
*
* @param directory the directory of the image.
* @param name the name of the image.
* @return the file containing the cloud coverage mask of the image.
*/
public File getImageCloudCover(final String directory, final String name) {
final File cloudCoverFile = new File(getImageCloudCoverFilename(directory, name));
log.debug("[{}][cloudCover] dir:{} path:{}", name, directory, cloudCoverFile.getAbsolutePath());
//check if directory exists
if (!cloudCoverFile.getParentFile().exists()) {
cloudCoverFile.getParentFile().mkdir();
}
//check if file exists
if (cloudCoverFile.exists()) {
return cloudCoverFile;
} else {
return null;
}
}
public File generateDirectoryReportXlsx(final String name) {
final String xlsxFileName = "report_metis-" + name + "-" + System.currentTimeMillis() + ".xlsx";
final File outFile = new File(props.getReportLocation(), xlsxFileName);
try (final FileOutputStream fos = new FileOutputStream(outFile)) {
final Workbook wb = new XSSFWorkbook();
final Sheet sheet = wb.createSheet("report");
final Row folderRow = appendRow(sheet, 1);
appendCell(folderRow, FOLDER_TITLE);
appendCell(folderRow, name);
final Row checksRow = appendRow(sheet, 1);
appendCell(checksRow, CHECKS_TITLE);
appendCell(checksRow, "1-2-3-4-5-6-7-8-9");
final Row titleRow = appendRow(sheet, 1);
appendCell(titleRow, FILE_TITLE);
for (int i = 1; i < 10; i++) {
appendCell(titleRow, String.format(CHECK_TITLE, i));
}
resultsTitles.forEach(s -> appendCell(titleRow, s));
for (int i = 1; i < 10; i++) {
appendCell(titleRow, String.format(NOTES_TITLE, i));
}
final File[] fileList = new File(props.getResultsLocation(), name).listFiles();
if (fileList != null) {
Arrays.stream(fileList) //for all files
.map(File::getName) //extract name
.map(FileNameUtils::extractImageNameFromResult) //extract image name
.distinct() //unique
.forEach(filename -> {
final Row fileRow = appendRow(sheet, 1);
appendCell(fileRow, filename);
final List<FileJobResult> results = new ArrayList<>();
for (int i = 0; i < 9; i++) {
final File resultFile = getResultFile(props.getResultsLocation(), new File(props.getFilesLocation() + "/" + name + "/", filename), i + 1);
if (resultFile.exists()) {
try {
results.add(mapper.readValue(resultFile, FileJobResult.class));
} catch (IOException e) {
//ignore
}
} else {
}
}
for (int i = 0; i < 9; i++) {
FileJobResult result = getTaskById(results, i + 1);
if (result != null) {
appendCell(fileRow, result.getResult() ? CHECK_OK : CHECK_NOK);
} else {
appendCell(fileRow, "");
}
}
appendCell(fileRow, getN1XPixelSizeWorld(results));
appendCell(fileRow, getN1YPixelSizeWorld(results));
appendCell(fileRow, getN1XPixelSize(results));
appendCell(fileRow, getN1YPixelSize(results));
appendCell(fileRow, getN2BitSize(results));
appendCell(fileRow, getN3SamplesPerPixel(results));
appendCell(fileRow, getN3SamplesPerPixelColor(results));
appendCell(fileRow, getN3HasAlpha(results));
appendCell(fileRow, getN4CloudCoverage(results));
appendCell(fileRow, getN5TopClipping(results));
appendCell(fileRow, getN5BottomClipping(results));
appendCell(fileRow, getN6MajorBinCenterLum(results));
appendCell(fileRow, getN7CoefficientOfVariation(results));
appendCell(fileRow, getN8Compression(results));
appendCell(fileRow, getN9ColorBalance(results));
appendCell(fileRow, getN9RedSnr(results));
appendCell(fileRow, getN9GreenSnr(results));
appendCell(fileRow, getN9BlueSnr(results));
for (int i = 0; i < 9; i++) {
FileJobResult result = getTaskById(results, i + 1);
if (result != null) {
appendCell(fileRow, result.getNote());
} else {
appendCell(fileRow, "");
}
}
});
}
wb.write(fos);
wb.close();
return outFile;
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
| amaxilat/opekepe-metis | server/src/main/java/com/amaxilatis/metis/server/service/FileService.java |
45,005 | //package gr.aueb.cf.ch10;
//
//import java.util.Arrays;
//import java.util.Scanner;
//
//public class MobileContactsApp {
// final static Scanner in = new Scanner(System.in);
// final static String[][] contacts = new String[500][3];
// static int pivot = -1;
//
// public static void main(String[] args) {
//
// }
//
// /**
// * Controllers
// */
//
// public static String insertContactController(String[] contact) {
// String response = "";
// String[] errorsArray;
// if (contact == null) return "nullError";
//
// try {
// errorsArray = validateInsertContact(contact);
// if (!errorsArray[0].isEmpty() || !errorsArray[1].isEmpty() || !errorsArray[2].isEmpty()) {
// for (String message : errorsArray) {
// response += message + "\n";
// }
// return response; //failure
// }
// insertContactService(contact);
// response = "OK"; //success
// } catch (Exception e) {
// return e.getMessage(); //exception
// }
// return response;
// }
//
// public static String[] validateInsertContact(String[] contact) {
// String[] errorsArray = new String[] {"", "", ""};
// if (!contact[0].matches("\\s+") || contact[0].length() < 2) { // εντοπιζει αν έχει εναν ή περισσοτερους μη κενους χαρακτηρες
// errorsArray[0] = "Invalid first name";
// }
// if (!contact[1].matches("\\s+") || contact[1].length() < 2) { // εντοπιζει αν έχει εναν ή περισσοτερους μη κενους χαρακτηρες
// errorsArray[1] = "Invalid last name";
// }
// if (!contact[2].matches("\\s+") || contact[2].length() != 10) { // εντοπιζει αν έχει εναν ή περισσοτερους μη κενους χαρακτηρες
// errorsArray[2] = "Invalid phone number";
// }
//
// }
//
//
// /**
// * service layer
// */
//
// public static String[] getContactByPhoneNumberService(String phoneNumber) {
// String[] contact;
//
// try {
// contact = getByPhoneNumber(phoneNumber);
// if (contact.length == 0) {
// throw new Exception("Contact not found");
// }
// return contact;
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
// }
//
// public static void insertContactService(String... contact) {
// boolean isInserted = false;
// if (contact.length != 3) return;
//
// try {
// isInserted = insertContact(contact[0], contact[1], contact[2]);
// if (!isInserted) {
// throw new Exception("Contact already exists");
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
// }
//
// public static void updateContact(String... contact) {
// boolean isUpdated = false;
// if (contact.length != 3) return;
//
// try {
// isUpdated = insertContact(contact[0], contact[1], contact[2]);
// if (!isUpdated) {
// throw new Exception("Contact doesn't exist");
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
// }
//
// public static void deleteContactService(String phoneNumber) {
// boolean isDeleted = false;
//
// try {
// isDeleted = deleteContact(phoneNumber);
// if (!isDeleted) {
// throw new Exception("Contact doesn't exist")
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
// }
// public static String[][] getAllContactsService() {
// String[][] allContacts;
//
// try {
// allContacts = getAllContacts();
// if (allContacts.length == 0) {
// throw new Exception("List is Empty");
// }
// return allContacts;
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
// }
//
// /*
// * CRUD methods - CRUD layer
// */
//
// public static int getContactIndexByPhoneNumber(String phoneNumber) {
// for (int i = 0; i <= pivot) {
// if (contacts[i][2].equals(phoneNumber)) {
// return i;
// }
// }
// return -1;
// }
//
// public static boolean isFull(String[][] contacts) {
// return (pivot == contacts.length -1);
// }
// public static boolean insertContact(String firstname, String lastname, String phoneNumber) {
// if (isFull(contacts)) return false;
//
// if (getContactIndexByPhoneNumber(phoneNumber) != -1) {
// return false;
// }
// pivot++;
// contacts[pivot][0] = firstname;
// contacts[pivot][1] = lastname;
// contacts[pivot][2] = phoneNumber;
// return true;
// }
//
// public static boolean updateContact(String firstname, String lastname, String phoneNumber) {
// int positionToUpdate = getContactIndexByPhoneNumber(phoneNumber);
// if (positionToUpdate == -1) {
// return false;
// }
//
// contacts[positionToUpdate][0] = firstname;
// contacts[positionToUpdate][1] = lastname;
// return true;
// }
//
// public static boolean deleteContact(String phoneNumber) {
// int positionToDelete = getContactIndexByPhoneNumber(phoneNumber);
//
// if (positionToDelete == -1) {
// return false;
// }
//
// System.arraycopy((contacts, positionToDelete + 1, contacts, positionToDelete Pivot - positionToDelete));
// pivot--;
// return true;
// }
//
// public static String[] getByPhoneNumber(String phoneNumber) {
// int position = getContactIndexByPhoneNumber(phoneNumber);
//
// return (position == -1) ? new String[] {} : contacts[position];
// }
//
// public static String[][] getAllContacts() {
// return Arrays.copyOf(contacts, pivot + 1);
// }
//}
| MytilinisV/codingfactorytestbed | ch10/MobileContactsApp.java |
45,018 | package modul_1_3;
/*
10.11 Primtal
Skriv et program der udregner alle primtal under 1.000.000 og udskriver det
største.
Gør dette ved at implementere Eratosthenes Si
Kvadratroden af i udregnes som java.lang.Math.sqrt(i).
WIKI:
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2.
The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime.[1]
This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime.[2]
Once all the multiples of each discovered prime have been marked as composites, the remaining unmarked numbers are primes.
The earliest known reference to the sieve (Ancient Greek: κόσκινον Ἐρατοσθένους, kóskinon Eratosthénous) is in Nicomachus of Gerasa's Introduction to Arithmetic,[3]
an early 2nd cent. CE book which attributes it to Eratosthenes of Cyrene, a 3rd cent. BCE Greek mathematician,
though describing the sieving by odd numbers instead of by primes.[4]
One of a number of prime number sieves, it is one of the most efficient ways to find all of the smaller primes.
It may be used to find primes in arithmetic progressions.[5]
A prime number is a natural number that has exactly two distinct natural number divisors: the number 1 and itself.
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
Initially, let p equal 2, the smallest prime number.
Enumerate the multiples of p by counting in increments of p from 2p to n, and mark them in the list (these will be 2p, 3p, 4p, ...;
the p itself should not be marked).
Find the smallest number in the list greater than p that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number
(which is the next prime), and repeat from step 3.
When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n.
The main idea here is that every value given to p will be prime, because if it were composite it would be marked as a multiple of some other,
smaller prime. Note that some of the numbers may be marked more than once (e.g., 15 will be marked both for 3 and 5).
As a refinement, it is sufficient to mark the numbers in step 3 starting from p2, as all the smaller multiples of p will have already been marked at that point.
This means that the algorithm is allowed to terminate in step 4 when p2 is greater than n.[1]
Another refinement is to initially list odd numbers only, (3, 5, ..., n), and count in increments of 2p in step 3, thus marking only odd multiples of p.
This actually appears in the original algorithm.[1][4] This can be generalized with wheel factorization,
forming the initial list only from numbers coprime with the first few primes and not just from odds (i.e., numbers coprime with 2),
and counting in the correspondingly adjusted increments so that only such multiples of p are generated that are coprime with those small primes,
in the first place.[7]
*/
import java.util.Arrays;
public class Prime {
public static void main(String[] args) { // NOTE This method is finding all NOT PRIMES
// It is doing this by making a list of all multiples of primes.
// since multiples of divisors larger than the sqrt of n are not neccesary they are already there, since they have smaller divisors.
// I.E. First not prime 4 is 2*2, second not prime is 6 (2*2*2 or 3*2) etc
int n = 1_000_000;
double sqrtn = java.lang.Math.sqrt(n);// we need the sqrt because any divisor greater than this would be detected
// by its smaller "partner divisor" i.e n = 81, 3*27, 9*9 , 27*3 (already detected)
boolean[] is_Prime = new boolean[n]; // an array with primes
Arrays.fill(is_Prime, true); // starts with all true - so we only fill in the not primes
for (int i = 2; i < sqrtn; i++) {
if (is_Prime[i]) {
for (int j = i * i; j < n; j = j + i) {
is_Prime[j] = false;
}
}
}
for (int k = n - 1; k > 1; k--) {
if (is_Prime[k]) {
System.out.println("Highest prime is: " + (k));
break;
}
}
/*
// Following is a total printout from top to buttom.
for (int k = n - 1; k > 1; k--) {
if (is_Prime[k]) {
System.out.println(k);
}
}
*/
}
}
| djarnis2/oop-exercises | src/modul_1_3/Prime.java |
45,058 | package gr.aueb.cf.ch4;
/**
* ΣΕ φθίνουσα σειρά
*/
public class Stars10Descending {
public static void main(String[] args) {
for (int i =1; i <= 10; i++) {
for (int j = i; j <= 10; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
| kyrkyp/CodingFactoryJava | src/gr/aueb/cf/ch4/Stars10Descending.java |
45,069 | public class LinkedList implements List //Συνδεδεμένη Λίστα
{
private Node firstNode;
private Node lastNode;
//Constructor
public LinkedList()
{
firstNode=lastNode=null;
}
//Getters-Setters
public Node getFirstNode()
{
return firstNode;
}
public Node getLastNode()
{
return lastNode;
}
public void setFirstNode(Node firstNode)
{
this.firstNode=firstNode;
}
public void setLastNode(Node lastNode)
{
this.lastNode=lastNode;
}
//Methods
@Override
public boolean isEmpty()
{
return (firstNode==null);
}
@Override
public int size()
{
int size=0;
Node position=firstNode;
while(position!=null)
{
position=position.getNext();
size++;
}
return size;
}
@Override
public void insertFirst(Object newItem)
{
if(isEmpty())
firstNode=lastNode=new Node(newItem,null);
else
firstNode=new Node(newItem,firstNode);
}
@Override
public void insertLast(Object newItem)
{
if(isEmpty())
firstNode=lastNode=new Node(newItem,null);
else
{
Node temp=new Node(newItem,null);
lastNode.setNext(temp);
lastNode=temp;
}
}
@Override
public Object removeFirst() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object removeItem=firstNode.getItem();
if(firstNode==lastNode)
firstNode=lastNode=null;
else
firstNode=firstNode.getNext();
return removeItem;
}
@Override
public Object removeLast() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object removeItem=lastNode.getItem();
if(firstNode==lastNode)
firstNode=lastNode=null;
else
{
Node position;
for(position=firstNode; position.getNext()!=lastNode; position=position.getNext())
lastNode=position;
position.setNext(null);
}
return removeItem;
}
@Override
public void printList() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
for(Node position=firstNode; position!=null; position=position.getNext())
System.out.println(position.getItem());
}
@Override
public Object maxOfList() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object max=firstNode.getItem();
Node position=firstNode.getNext();
while(position!=null)
{
Comparable CoMax=(Comparable)max;
Comparable CoItem=(Comparable)position.getItem();
if(CoMax.compareTo(CoItem)<0)
max=position.getItem();
position=position.getNext();
}
return max;
}
@Override
public boolean exists(Object newItem) throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Node position=firstNode;
while(position!=null)
{
if(position.getItem().equals(newItem))
return true;
position=position.getNext();
}
return false;
}
//Sort() LinkedList
public LinkedList sort()
{
Node trace,current,min;
trace=getFirstNode();
while(trace!=null)
{
current=trace;
min=trace;
while(current!=null)
{
if(((String)(current.getItem())).compareTo((String)(min.getItem()))<0) //για φθίνουσα '>'
min=current;
current=current.getNext();
}
String temp=(String)trace.getItem();
trace.setItem(min.getItem());
min.setItem(temp);
trace=trace.getNext();
} //EndWhile trace
return this;
}
//BubbleSort() LinkedList
public LinkedList BubbleSort()
{
Node current=getFirstNode();
while(current!=null)
{
Node second=current.getNext();
while(second!=null)
{
if(((String)(current.getItem())).compareTo((String)(second.getItem()))>0) //για φθίνουσα '<'
{
String temp=(String) current.getItem();
current.setItem(second.getItem());
second.setItem(temp);
}
second=second.getNext();
}
current=current.getNext();
} //EndWhile current.
return this;
}
@Override
public Object MinMaxOfList() throws ListEmptyException
{
Object [] MinMax=new Student[2];
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object min=firstNode.getItem();
Node position=firstNode.getNext();
while(position!=null)
{
if(((Student)min).getVathmos()>((Student)(position.getItem())).getVathmos())
min=position.getItem();
position=position.getNext();
}
MinMax[0]=min;
Object max=firstNode.getItem();
position=firstNode.getNext();
while(position!=null)
{
if(((Student)max).getVathmos()<((Student)(position.getItem())).getVathmos())
max=position.getItem();
position=position.getNext();
}
MinMax[1]=max;
return MinMax;
}
} | alexoiik/Data-Structures-Java | DataStructures_Ex3(SimpleLinkedLists)/src/LinkedList.java |
45,074 | public class LinkedList implements List //Συνδεδεμένη Λίστα
{
private Node firstNode;
private Node lastNode;
//Constructor
public LinkedList()
{
firstNode=lastNode=null;
}
//Getters-Setters
public Node getFirstNode()
{
return firstNode;
}
public Node getLastNode()
{
return lastNode;
}
public void setFirstNode(Node firstNode)
{
this.firstNode=firstNode;
}
public void setLastNode(Node lastNode)
{
this.lastNode=lastNode;
}
//Methods
@Override
public boolean isEmpty()
{
return (firstNode==null);
}
@Override
public int size()
{
int size=0;
Node position=firstNode;
while(position!=null)
{
position=position.getNext();
size++;
}
return size;
}
@Override
public void insertFirst(Object newItem)
{
if(isEmpty())
firstNode=lastNode=new Node(newItem,null);
else
firstNode=new Node(newItem,firstNode);
}
@Override
public void insertLast(Object newItem)
{
if(isEmpty())
firstNode=lastNode=new Node(newItem,null);
else
{
Node temp=new Node(newItem,null);
lastNode.setNext(temp);
lastNode=temp;
}
}
@Override
public Object removeFirst() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object removeItem=firstNode.getItem();
if(firstNode==lastNode)
firstNode=lastNode=null;
else
firstNode=firstNode.getNext();
return removeItem;
}
@Override
public Object removeLast() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object removeItem=lastNode.getItem();
if(firstNode==lastNode)
firstNode=lastNode=null;
else
{
Node position;
for(position=firstNode; position.getNext()!=lastNode; position=position.getNext())
lastNode=position;
position.setNext(null);
}
return removeItem;
}
@Override
public void printList() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
for(Node position=firstNode; position!=null; position=position.getNext())
System.out.println(position.getItem());
}
@Override
public Object maxOfList() throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object max=firstNode.getItem();
Node position=firstNode.getNext();
while(position!=null)
{
Comparable CoMax=(Comparable)max;
Comparable CoItem=(Comparable)position.getItem();
if(CoMax.compareTo(CoItem)<0)
max=position.getItem();
position=position.getNext();
}
return max;
}
@Override
public boolean exists(Object newItem) throws ListEmptyException
{
if(isEmpty())
throw new ListEmptyException("List is Empty");
Node position=firstNode;
while(position!=null)
{
if(position.getItem().equals(newItem))
return true;
position=position.getNext();
}
return false;
}
//Sort() LinkedList.
public LinkedList sort()
{
Node trace,current,min;
trace=getFirstNode();
while(trace!=null)
{
current=trace;
min=trace;
while(current!=null)
{
if(((String)(current.getItem())).compareTo((String)(min.getItem()))<0) //για φθίνουσα '>'
min=current;
current=current.getNext();
}
String temp=(String)trace.getItem();
trace.setItem(min.getItem());
min.setItem(temp);
trace=trace.getNext();
} //EndWhile trace
return this;
}
//BubbleSort() LinkedList.
public LinkedList BubbleSort()
{
Node current=getFirstNode();
while(current!=null)
{
Node second=current.getNext();
while(second!=null)
{
if(((String)(current.getItem())).compareTo((String)(second.getItem()))>0) //για φθίνουσα '<'
{
String temp=(String) current.getItem();
current.setItem(second.getItem());
second.setItem(temp);
}
second=second.getNext();
}
current=current.getNext();
} //EndWhile current.
return this;
}
@Override
public Object MinMaxOfList() throws ListEmptyException
{
Object [] MinMax=new Student[2];
if(isEmpty())
throw new ListEmptyException("List is Empty");
Object min=firstNode.getItem();
Node position=firstNode.getNext();
while(position!=null)
{
if(((Student)min).getVathmos()>((Student)(position.getItem())).getVathmos())
min=position.getItem();
position=position.getNext();
}
MinMax[0]=min;
Object max=firstNode.getItem();
position=firstNode.getNext();
while(position!=null)
{
if(((Student)max).getVathmos()<((Student)(position.getItem())).getVathmos())
max=position.getItem();
position=position.getNext();
}
MinMax[1]=max;
return MinMax;
}
} | alexoiik/Data-Structures-Java | DataStructures_Ex4(Stacks&QueuesWithLinkedLists)/src/LinkedList.java |
45,102 | package platform.javabnb;
// απαρίθμηση Θέα
public enum Landscape {
STREET("Street"),
MOUNTAIN("Mountain"),
SEA("Sea");
// η θέα μπορεί να είναι "Street", "Mountain" ή "Sea"
private final String landscape;
private Landscape(String landscape) {
this.landscape = landscape;
}
public String getLandscape() {
return landscape;
}
@Override
public String toString() {
return "Landscape: " + landscape;
}
}
| andreasrous/JavaBnB | src/main/java/platform/javabnb/Landscape.java |
45,129 | package com.unipi.toor_guide;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.cardview.widget.CardView;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class SearchActivity extends AppCompatActivity {
BottomNavigationView bottomBar;
EditText search_text;
Button search_button;
Context searchactivity = this;
private StorageReference storageRef;
private FirebaseRemoteConfig remoteConfig;
private FirebaseDatabase firedb;
private DatabaseReference ref;
List<String> beach_names = new ArrayList<String>();
List<String> gr_beach_names = new ArrayList<String>();
List<String> villages_names = new ArrayList<String>();
List<String> gr_villages_names = new ArrayList<String>();
List<String> beaches_desc = new ArrayList<>();
List<String> villages_desc = new ArrayList<>();
MyTts myTts;
private static final int REC_RESULT = 653;
TextView beach_textview;
TextView village_textview;
HorizontalScrollView beaches_hsv;
HorizontalScrollView villages_hsv;
LinearLayout beaches_cardholder;
LinearLayout villages_cardholder;
CardView cardview;
LinearLayout.LayoutParams llayoutparams;
ImageView cardimage;
TextView cardtext;
TextView no_beaches;
TextView no_villages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bottomBar=findViewById(R.id.bottombar);
bottomBar.getMenu().getItem(1).setChecked(true);
bottomBar.setOnNavigationItemSelectedListener(item -> {
if(item.getItemId()==R.id.home){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
}
if(item.getItemId()==R.id.Favourites){
startActivity(new Intent(getApplicationContext(),FavouritesActivity.class));
overridePendingTransition(0,0);
return true;
}
return item.getItemId() == R.id.search;
});
beach_textview=findViewById(R.id.beach_textview);
village_textview=findViewById(R.id.villages_textview);
beaches_hsv=findViewById(R.id.beaches_hsv);
villages_hsv=findViewById(R.id.villages_hsv);
beaches_cardholder=findViewById(R.id.beaches_cardholder);
villages_cardholder=findViewById(R.id.villages_cardholder);
llayoutparams = new LinearLayout.LayoutParams(
300,
LinearLayout.LayoutParams.WRAP_CONTENT
);
llayoutparams.setMargins(20,0,20,0);
search_text=findViewById(R.id.search_edittext);
search_button=findViewById(R.id.search_button);
search_button.setOnLongClickListener(view -> {
recognize();
search_fun();
return true;
});
storageRef = FirebaseStorage.getInstance().getReference();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); //night mode ui is not supported
remoteConfig = FirebaseRemoteConfig.getInstance();
remoteConfig.setDefaultsAsync(R.xml.config_settings);
remoteConfig.fetch(3).addOnCompleteListener(task -> remoteConfig.fetchAndActivate());
firedb = FirebaseDatabase.getInstance();
ref = firedb.getReference();
myTts = new MyTts(searchactivity);
no_beaches=findViewById(R.id.no_beach_textview);
no_villages=findViewById(R.id.no_villages_textview);
}
@Override
protected void onResume() {
super.onResume();
bottomBar.getMenu().getItem(1).setChecked(true);
beach_names.clear();
beaches_desc.clear();
villages_names.clear();
villages_desc.clear();
beaches_cardholder.removeAllViews();
villages_cardholder.removeAllViews();
beach_textview.setVisibility(View.INVISIBLE);
village_textview.setVisibility(View.INVISIBLE);
beaches_hsv.setVisibility(View.INVISIBLE);
villages_hsv.setVisibility(View.INVISIBLE);
no_beaches.setVisibility(View.INVISIBLE);
no_villages.setVisibility(View.INVISIBLE);
}
public void search(View view){
if(beach_textview.getVisibility()==View.INVISIBLE){
beach_textview.setVisibility(View.VISIBLE);
village_textview.setVisibility(View.VISIBLE);
beaches_hsv.setVisibility(View.VISIBLE);
villages_hsv.setVisibility(View.VISIBLE);
}
search_fun();
}
private void search_fun(){
beach_names.clear();
gr_beach_names.clear();
beaches_desc.clear();
villages_names.clear();
gr_villages_names.clear();
villages_desc.clear();
beaches_cardholder.removeAllViews();
villages_cardholder.removeAllViews();
if(!search_text.getText().toString().equals("")){
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot snap: snapshot.getChildren()){
for(DataSnapshot sight : snap.child("Beaches").getChildren()){
String beachen = String.valueOf(sight.getKey());
String beachel = String.valueOf(sight.child("NameTrans").getValue());
if((beachen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||beachel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!beach_names.contains(beachen)) {
beach_names.add(beachen);
gr_beach_names.add(beachel);
beaches_desc.add(String.valueOf(sight.child("Info").getValue()));
}
}
for (DataSnapshot sight : snap.child("Villages").getChildren()) {
String villagen = String.valueOf(sight.getKey());
String villagel=String.valueOf(sight.child("NameTrans").getValue());
if((villagen.toLowerCase().contains(search_text.getText().toString().toLowerCase())||villagel.toLowerCase().contains(search_text.getText().toString().toLowerCase()))&&!villages_names.contains(villagen)) {
villages_names.add(villagen);
gr_villages_names.add(villagel);
villages_desc.add(String.valueOf(sight.child("Info").getValue()));
}
}
}
if(beach_names.isEmpty()){
no_beaches.setVisibility(View.VISIBLE);
no_beaches.setText(getText(R.string.no_beach)+search_text.getText().toString());
}else {
no_beaches.setVisibility(View.INVISIBLE);
}
if(villages_names.isEmpty()){
no_villages.setVisibility(View.VISIBLE);
no_villages.setText(getText(R.string.no_villages)+search_text.getText().toString());
}else{
no_villages.setVisibility(View.INVISIBLE);
}
for(int i=0; i<beach_names.size(); i++){
String imgname = beach_names.get(i).toLowerCase();
if (imgname.contains(" ")) imgname = imgname.replace(" ","_");
String imgpath = imgname;
imgname = (new StringBuilder().append(imgname).append(".jpg")).toString();
try{
File localfile = File.createTempFile("tmp","jpg") ;
StorageReference imgref = storageRef.child("img/"+ imgname);
int finalI = i;
String finalImgname = imgname;
imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity,
BitmapFactory.decodeFile(localfile.getAbsolutePath()),
beach_names.get(finalI),
beaches_desc.get(finalI),
finalImgname,
false,
beaches_cardholder,
gr_beach_names.get(finalI)));
}catch (IOException e){
e.printStackTrace();
}
}
for(int i=0; i<villages_names.size(); i++){
String imgname = villages_names.get(i).toLowerCase();
if (imgname.contains(" ")) imgname = imgname.replace(" ","_");
String imgpath = imgname;
imgname = (new StringBuilder().append(imgname).append(".jpg")).toString();
try{
File localfile = File.createTempFile("tmp","jpg") ;
StorageReference imgref = storageRef.child("img/"+ imgname);
int finalI = i;
String finalImgname = imgname;
imgref.getFile(localfile).addOnSuccessListener(taskSnapshot ->cards(searchactivity,
BitmapFactory.decodeFile(localfile.getAbsolutePath()),
villages_names.get(finalI),
villages_desc.get(finalI),
finalImgname,
true,
villages_cardholder,
gr_villages_names.get(finalI)));
}catch (IOException e){
e.printStackTrace();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.i("fire_error",error.getMessage());
}
});
}
else {
beach_names.clear();
beaches_desc.clear();
villages_names.clear();
villages_desc.clear();
beaches_cardholder.removeAllViews();
villages_cardholder.removeAllViews();
beach_textview.setVisibility(View.INVISIBLE);
beaches_hsv.setVisibility(View.INVISIBLE);
village_textview.setVisibility(View.INVISIBLE);
villages_hsv.setVisibility(View.INVISIBLE);
}
}
public void cards(Context context, Bitmap background, String name, String description, String imgpath,boolean village,LinearLayout cardholder,String gr_name) {
cardview = new CardView(context);
cardview.setRadius(0);
cardview.setPadding(0, 0, 0, 0);
cardview.setPreventCornerOverlap(false);
cardview.setBackgroundResource(R.drawable.rectangled);
cardimage = new ImageView(context);
cardimage.setImageBitmap(background);
cardimage.setScaleType(ImageView.ScaleType.FIT_XY);
cardimage.setMaxHeight(Integer.MAX_VALUE);
cardimage.setMinimumHeight(Integer.MAX_VALUE);
cardimage.setMaxWidth(Integer.MAX_VALUE);
cardimage.setMinimumHeight(Integer.MAX_VALUE);
cardview.addView(cardimage);
cardtext = new TextView(context);
if (name.contains(" ")) name = name.replace(" ", "\n");
String[] systemLangs = Resources.getSystem().getConfiguration().getLocales().toLanguageTags().split(",");
if (systemLangs[0].contains(Locale.forLanguageTag("EL").toLanguageTag())) cardtext.setText(gr_name);
else cardtext.setText(name);
cardtext.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
cardtext.setTextColor(Color.WHITE);
cardtext.setPadding(10, 430, 10, 0);
cardtext.setGravity(Gravity.END);
cardview.addView(cardtext);
String finalName = name;
cardview.setOnClickListener(v -> {
startActivity(new Intent(this, InfoActivity.class).
putExtra("id", finalName).
putExtra("description", description).
putExtra("path", imgpath).
putExtra("village",village).
putExtra("gr_name",gr_name));
});
cardholder.addView(cardview, llayoutparams);
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(0,0);
}
//Χειρισμός φωνητικών εντολων{
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REC_RESULT && resultCode==RESULT_OK){
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches.contains("favourites") || matches.contains("favorites") || matches.contains("αγαπημένα")){
startActivity(new Intent(this, FavouritesActivity.class));
}
else if (matches.contains("home") ||matches.contains("sights") || matches.contains("αξιοθέατα") || matches.contains("αρχική")){
startActivity(new Intent(this, MainActivity.class));
}
else{
search_text.setText(matches.get(0));
}
}
}
public void recognize(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"What are you searching?");
startActivityForResult(intent,REC_RESULT);
}
//}
} | angelica-thd/Android | app/src/main/java/com/unipi/toor_guide/SearchActivity.java |
45,155 | package api;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.HashSet;
import static org.junit.Assert.*;
public class RentalTest {
Renter renter;
Rental rental;
Review review;
@Before
public void setUp() throws Exception {
renter = new Renter("name", "surname", "username", "password");
rental = new Rental("rentalName", "type", "address", "city", "zipcode", "description", new HashSet<>(), renter);
review = new Review(5, "very good", SDate.dateToString(),
new Tenant("name", "surname", "username", "password"));
}
@Test
public void getReviews() {
assertEquals(new HashMap<Tenant, Review>(), rental.getReviews());
}
@Test
public void getSearchId() {
assertEquals("rentalname type address city zipcode", rental.getSearchID());
}
@Test
public void getName() {
assertEquals("rentalName", rental.getName());
}
@Test
public void getType() {
assertEquals("type", rental.getType());
}
@Test
public void getAddress() {
assertEquals("address", rental.getAddress());
}
@Test
public void getCity() {
assertEquals("city", rental.getCity());
}
@Test
public void getZipcode() {
assertEquals("zipcode", rental.getZipcode());
}
@Test
public void getDescription() {
assertEquals("description", rental.getDescription());
}
@Test
public void getAmenities() {
assertEquals(new HashSet<>(), rental.getAmenities());
}
@Test
public void getOwner() {
assertEquals(renter, rental.getOwner());
}
@Test
public void setName() {
rental.setName("newName");
assertEquals("newName", rental.getName());
}
@Test
public void setType() {
rental.setType("newType");
assertEquals("newType", rental.getType());
}
@Test
public void setAddress() {
rental.setAddress("newAddress");
assertEquals("newAddress", rental.getAddress());
}
@Test
public void setCity() {
rental.setCity("newCity");
assertEquals("newCity", rental.getCity());
}
@Test
public void setZipcode() {
rental.setZipcode("newZipcode");
assertEquals("newZipcode", rental.getZipcode());
}
@Test
public void setDescription() {
rental.setDescription("newDescription");
assertEquals("newDescription", rental.getDescription());
}
@Test
public void setAmenities() {
HashSet<String> newAmenities = new HashSet<>();
newAmenities.add("newAmenity");
rental.setAmenities(newAmenities);
assertEquals(newAmenities, rental.getAmenities());
}
@Test
public void updateSearchID() {
rental.setName("newName");
rental.setType("newType");
assertEquals("newname newtype address city zipcode", rental.getSearchID());
rental.setAddress("newAddress");
rental.setCity("newCity");
rental.setZipcode("newZipcode");
assertEquals("newname newtype newaddress newcity newzipcode", rental.getSearchID());
}
@Test
public void addReview() {
rental.addReview(review);
assertEquals(review, rental.reviews.get(review.getTenant()));
}
@Test
public void updateRating() {
rental.addReview(review);
rental.addReview(new Review(3, "good", SDate.dateToString(),
new Tenant("name", "surname", "username", "password")));
rental.updateRating();
assertEquals(4, rental.rating,0.001);
}
@Test
public void removeReview() {
rental.addReview(review);
rental.removeReview(review);
assertTrue(rental.reviews.isEmpty());
}
@Test
public void getRating() {
rental.addReview(review);
rental.updateRating();
assertEquals(5, rental.getRating(),0.001);
}
@Test
public void gettotalRatings() {
assertEquals(0, rental.getTotalReviews());
rental.addReview(review);
rental.updateRating();
assertEquals(1, rental.getTotalReviews());
}
@Test
public void getTotalReviews() {
assertEquals(0, rental.getTotalReviews());
rental.addReview(review);
assertEquals(1,rental.getTotalReviews());
}
@Test
public void getSearchID() {
assertEquals("rentalname type address city zipcode", rental.getSearchID());
}
@Test
public void getLocation() {
assertEquals("address, city, zipcode", rental.getLocation());
}
@Test
public void getAmenitiesString() {
assertTrue(rental.getAmenitiesString().equals(""));
HashSet<String> amenities = new HashSet<>() {
{
add("Θέα");
}
};
rental.setAmenities(amenities);
assertEquals("θέα ", rental.getAmenitiesString());
}
} | kyrtsouv/Rental-Review | test/api/RentalTest.java |
45,254 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.dubbo.qos.command.impl;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.command.BaseCommand;
import org.apache.dubbo.qos.command.CommandContext;
import org.apache.dubbo.qos.command.annotation.Cmd;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceRepository;
import java.util.Collection;
import java.util.List;
@Cmd(name = "online", summary = "online dubbo", example = {
"online dubbo",
"online xx.xx.xxx.service"
})
public class Online implements BaseCommand {
private static final Logger logger = LoggerFactory.getLogger(Online.class);
private static RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
private static ServiceRepository serviceRepository = ApplicationModel.getServiceRepository();
@Override
public String execute(CommandContext commandContext, String[] args) {
logger.info("receive online command");
String servicePattern = ".*";
if (ArrayUtils.isNotEmpty(args)) {
servicePattern = "" + args[0];
}
boolean hasService = online(servicePattern);
if (hasService) {
return "OK";
} else {
return "service not found";
}
}
public static boolean online(String servicePattern) {
boolean hasService = false;
Collection<ProviderModel> providerModelList = serviceRepository.getExportedServices();
for (ProviderModel providerModel : providerModelList) {
if (providerModel.getServiceMetadata().getDisplayServiceKey().matches(servicePattern)) {
hasService = true;
List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (!statedURL.isRegistered()) {
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.register(statedURL.getProviderUrl());
statedURL.setRegistered(true);
}
}
}
}
return hasService;
}
}
| apache/dubbo | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java |
45,255 | /*
* Copyright (c) 2010-2021 Haifeng Li. All rights reserved.
*
* Smile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Smile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Smile. If not, see <https://www.gnu.org/licenses/>.
*/
package smile.regression;
import java.io.Serial;
import java.util.Arrays;
import java.util.Properties;
import smile.base.mlp.*;
import smile.math.Scaler;
import smile.math.MathEx;
import smile.util.Strings;
/**
* Fully connected multilayer perceptron neural network for regression.
* An MLP consists of at least three layers of nodes: an input layer,
* a hidden layer and an output layer. The nodes are interconnected
* through weighted acyclic arcs from each preceding layer to the
* following, without lateral or feedback connections. Each node
* calculates a transformed weighted linear combination of its inputs
* (output activations from the preceding layer), with one of the weights
* acting as a trainable bias connected to a constant input. The
* transformation, called activation function, is a bounded non-decreasing
* (non-linear) function.
*
* @author Haifeng Li
*/
public class MLP extends MultilayerPerceptron implements Regression<double[]> {
@Serial
private static final long serialVersionUID = 2L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MLP.class);
/** The scaling function of output values. */
private final Scaler scaler;
/**
* Constructor.
*
* @param builders the builders of input and hidden layers from bottom to top.
*/
public MLP(LayerBuilder... builders) {
this(null, builders);
}
/**
* Constructor.
*
* @param scaler the scaling function of output values.
* @param builders the builders of input and hidden layers from bottom to top.
*/
public MLP(Scaler scaler, LayerBuilder... builders) {
super(net(builders));
this.scaler = scaler;
}
/** Builds the layers. */
private static Layer[] net(LayerBuilder... builders) {
int p = 0;
int l = builders.length;
Layer[] net = new Layer[l];
for (int i = 0; i < l; i++) {
net[i] = builders[i].build(p);
p = builders[i].neurons();
}
if (!(net[l-1] instanceof OutputLayer)) {
net = Arrays.copyOf(net, l + 1);
net[l] = new OutputLayer(1, p, OutputFunction.LINEAR, Cost.MEAN_SQUARED_ERROR);
}
return net;
}
@Override
public double predict(double[] x) {
propagate(x, false);
double y = output.output()[0];
return scaler == null ? y : scaler.inv(y);
}
@Override
public boolean online() {
return true;
}
/** Updates the model with a single sample. RMSProp is not applied. */
@Override
public void update(double[] x, double y) {
propagate(x, true);
setTarget(y);
backpropagate(true);
t++;
}
/** Updates the model with a mini-batch. RMSProp is applied if {@code rho > 0}. */
@Override
public void update(double[][] x, double[] y) {
for (int i = 0; i < x.length; i++) {
propagate(x[i], true);
setTarget(y[i]);
backpropagate(false);
}
update(x.length);
t++;
}
/**
* Sets the network target value.
*
* @param y the raw responsible variable.
*/
private void setTarget(double y) {
target.get()[0] = scaler == null ? y : scaler.f(y);
}
/**
* Fits a MLP model.
* @param x the training dataset.
* @param y the response variable.
* @param params the hyperparameters.
* @return the model.
*/
public static MLP fit(double[][] x, double[] y, Properties params) {
int p = x[0].length;
Scaler scaler = Scaler.of(params.getProperty("smile.mlp.scaler"), y);
LayerBuilder[] layers = Layer.of(0, p, params.getProperty("smile.mlp.layers", "ReLU(100)"));
MLP model = new MLP(scaler, layers);
model.setParameters(params);
int epochs = Integer.parseInt(params.getProperty("smile.mlp.epochs", "100"));
int batch = Integer.parseInt(params.getProperty("smile.mlp.mini_batch", "32"));
double[][] batchx = new double[batch][];
double[] batchy = new double[batch];
for (int epoch = 1; epoch <= epochs; epoch++) {
logger.info("{} epoch", Strings.ordinal(epoch));
int[] permutation = MathEx.permutate(x.length);
for (int i = 0; i < x.length; i += batch) {
int size = Math.min(batch, x.length - i);
for (int j = 0; j < size; j++) {
int index = permutation[i + j];
batchx[j] = x[index];
batchy[j] = y[index];
}
if (size < batch) {
model.update(Arrays.copyOf(batchx, size), Arrays.copyOf(batchy, size));
} else {
model.update(batchx, batchy);
}
}
}
return model;
}
}
| haifengl/smile | core/src/main/java/smile/regression/MLP.java |
45,256 | /*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.manager.response;
import io.mycat.MycatServer;
import io.mycat.manager.ManagerConnection;
import io.mycat.net.mysql.OkPacket;
/**
* @author mycat
*/
public class Online {
private static final OkPacket ok = new OkPacket();
static {
ok.packetId = 1;
ok.affectedRows = 1;
ok.serverStatus = 2;
}
public static void execute(String stmt, ManagerConnection mc) {
MycatServer.getInstance().online();
ok.write(mc);
}
} | jim0409/Mycat-Server | src/main/java/io/mycat/manager/response/Online.java |
45,257 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.rocketmq.store.stats;
import java.util.HashMap;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.statistics.StatisticsItem;
import org.apache.rocketmq.common.statistics.StatisticsItemFormatter;
import org.apache.rocketmq.common.statistics.StatisticsItemPrinter;
import org.apache.rocketmq.common.statistics.StatisticsItemScheduledIncrementPrinter;
import org.apache.rocketmq.common.statistics.StatisticsItemScheduledPrinter;
import org.apache.rocketmq.common.statistics.StatisticsItemStateGetter;
import org.apache.rocketmq.common.statistics.StatisticsKindMeta;
import org.apache.rocketmq.common.statistics.StatisticsManager;
import org.apache.rocketmq.common.stats.MomentStatsItemSet;
import org.apache.rocketmq.common.stats.Stats;
import org.apache.rocketmq.common.stats.StatsItem;
import org.apache.rocketmq.common.stats.StatsItemSet;
import org.apache.rocketmq.common.topic.TopicValidator;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
public class BrokerStatsManager {
@Deprecated public static final String QUEUE_PUT_NUMS = Stats.QUEUE_PUT_NUMS;
@Deprecated public static final String QUEUE_PUT_SIZE = Stats.QUEUE_PUT_SIZE;
@Deprecated public static final String QUEUE_GET_NUMS = Stats.QUEUE_GET_NUMS;
@Deprecated public static final String QUEUE_GET_SIZE = Stats.QUEUE_GET_SIZE;
@Deprecated public static final String TOPIC_PUT_NUMS = Stats.TOPIC_PUT_NUMS;
@Deprecated public static final String TOPIC_PUT_SIZE = Stats.TOPIC_PUT_SIZE;
@Deprecated public static final String GROUP_GET_NUMS = Stats.GROUP_GET_NUMS;
@Deprecated public static final String GROUP_GET_SIZE = Stats.GROUP_GET_SIZE;
@Deprecated public static final String SNDBCK_PUT_NUMS = Stats.SNDBCK_PUT_NUMS;
@Deprecated public static final String BROKER_PUT_NUMS = Stats.BROKER_PUT_NUMS;
@Deprecated public static final String BROKER_GET_NUMS = Stats.BROKER_GET_NUMS;
@Deprecated public static final String GROUP_GET_FROM_DISK_NUMS = Stats.GROUP_GET_FROM_DISK_NUMS;
@Deprecated public static final String GROUP_GET_FROM_DISK_SIZE = Stats.GROUP_GET_FROM_DISK_SIZE;
@Deprecated public static final String BROKER_GET_FROM_DISK_NUMS = Stats.BROKER_GET_FROM_DISK_NUMS;
@Deprecated public static final String BROKER_GET_FROM_DISK_SIZE = Stats.BROKER_GET_FROM_DISK_SIZE;
// For commercial
@Deprecated public static final String COMMERCIAL_SEND_TIMES = Stats.COMMERCIAL_SEND_TIMES;
@Deprecated public static final String COMMERCIAL_SNDBCK_TIMES = Stats.COMMERCIAL_SNDBCK_TIMES;
@Deprecated public static final String COMMERCIAL_RCV_TIMES = Stats.COMMERCIAL_RCV_TIMES;
@Deprecated public static final String COMMERCIAL_RCV_EPOLLS = Stats.COMMERCIAL_RCV_EPOLLS;
@Deprecated public static final String COMMERCIAL_SEND_SIZE = Stats.COMMERCIAL_SEND_SIZE;
@Deprecated public static final String COMMERCIAL_RCV_SIZE = Stats.COMMERCIAL_RCV_SIZE;
@Deprecated public static final String COMMERCIAL_PERM_FAILURES = Stats.COMMERCIAL_PERM_FAILURES;
// Send message latency
public static final String TOPIC_PUT_LATENCY = "TOPIC_PUT_LATENCY";
public static final String GROUP_ACK_NUMS = "GROUP_ACK_NUMS";
public static final String GROUP_CK_NUMS = "GROUP_CK_NUMS";
public static final String DLQ_PUT_NUMS = "DLQ_PUT_NUMS";
public static final String BROKER_ACK_NUMS = "BROKER_ACK_NUMS";
public static final String BROKER_CK_NUMS = "BROKER_CK_NUMS";
public static final String BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC = "BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC";
public static final String BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC = "BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC";
public static final String SNDBCK2DLQ_TIMES = "SNDBCK2DLQ_TIMES";
public static final String COMMERCIAL_OWNER = "Owner";
public static final String ACCOUNT_OWNER_PARENT = "OWNER_PARENT";
public static final String ACCOUNT_OWNER_SELF = "OWNER_SELF";
public static final long ACCOUNT_STAT_INVERTAL = 60 * 1000;
public static final String ACCOUNT_AUTH_TYPE = "AUTH_TYPE";
public static final String ACCOUNT_SEND = "SEND";
public static final String ACCOUNT_RCV = "RCV";
public static final String ACCOUNT_SEND_BACK = "SEND_BACK";
public static final String ACCOUNT_SEND_BACK_TO_DLQ = "SEND_BACK_TO_DLQ";
public static final String ACCOUNT_AUTH_FAILED = "AUTH_FAILED";
public static final String ACCOUNT_SEND_REJ = "SEND_REJ";
public static final String ACCOUNT_REV_REJ = "RCV_REJ";
public static final String MSG_NUM = "MSG_NUM";
public static final String MSG_SIZE = "MSG_SIZE";
public static final String SUCCESS_MSG_NUM = "SUCCESS_MSG_NUM";
public static final String FAILURE_MSG_NUM = "FAILURE_MSG_NUM";
public static final String COMMERCIAL_MSG_NUM = "COMMERCIAL_MSG_NUM";
public static final String SUCCESS_REQ_NUM = "SUCCESS_REQ_NUM";
public static final String FAILURE_REQ_NUM = "FAILURE_REQ_NUM";
public static final String SUCCESS_MSG_SIZE = "SUCCESS_MSG_SIZE";
public static final String FAILURE_MSG_SIZE = "FAILURE_MSG_SIZE";
public static final String RT = "RT";
public static final String INNER_RT = "INNER_RT";
@Deprecated public static final String GROUP_GET_FALL_SIZE = Stats.GROUP_GET_FALL_SIZE;
@Deprecated public static final String GROUP_GET_FALL_TIME = Stats.GROUP_GET_FALL_TIME;
// Pull Message Latency
@Deprecated public static final String GROUP_GET_LATENCY = Stats.GROUP_GET_LATENCY;
// Consumer Register Time
public static final String CONSUMER_REGISTER_TIME = "CONSUMER_REGISTER_TIME";
// Producer Register Time
public static final String PRODUCER_REGISTER_TIME = "PRODUCER_REGISTER_TIME";
public static final String CHANNEL_ACTIVITY = "CHANNEL_ACTIVITY";
public static final String CHANNEL_ACTIVITY_CONNECT = "CONNECT";
public static final String CHANNEL_ACTIVITY_IDLE = "IDLE";
public static final String CHANNEL_ACTIVITY_EXCEPTION = "EXCEPTION";
public static final String CHANNEL_ACTIVITY_CLOSE = "CLOSE";
/**
* read disk follow stats
*/
private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_STATS_LOGGER_NAME);
private static final Logger COMMERCIAL_LOG = LoggerFactory.getLogger(
LoggerName.COMMERCIAL_LOGGER_NAME);
private static final Logger ACCOUNT_LOG = LoggerFactory.getLogger(LoggerName.ACCOUNT_LOGGER_NAME);
private static final Logger DLQ_STAT_LOG = LoggerFactory.getLogger(
LoggerName.DLQ_STATS_LOGGER_NAME);
private ScheduledExecutorService scheduledExecutorService;
private ScheduledExecutorService commercialExecutor;
private ScheduledExecutorService accountExecutor;
private final HashMap<String, StatsItemSet> statsTable = new HashMap<>();
private final String clusterName;
private final boolean enableQueueStat;
private MomentStatsItemSet momentStatsItemSetFallSize;
private MomentStatsItemSet momentStatsItemSetFallTime;
private final StatisticsManager accountStatManager = new StatisticsManager();
private StateGetter produerStateGetter;
private StateGetter consumerStateGetter;
private BrokerConfig brokerConfig;
public BrokerStatsManager(BrokerConfig brokerConfig) {
this.brokerConfig = brokerConfig;
this.enableQueueStat = brokerConfig.isEnableDetailStat();
initScheduleService();
this.clusterName = brokerConfig.getBrokerClusterName();
init();
}
public BrokerStatsManager(String clusterName, boolean enableQueueStat) {
this.clusterName = clusterName;
this.enableQueueStat = enableQueueStat;
initScheduleService();
init();
}
public void init() {
momentStatsItemSetFallSize = new MomentStatsItemSet(GROUP_GET_FALL_SIZE,
scheduledExecutorService, log);
momentStatsItemSetFallTime = new MomentStatsItemSet(GROUP_GET_FALL_TIME,
scheduledExecutorService, log);
if (enableQueueStat) {
this.statsTable.put(Stats.QUEUE_PUT_NUMS, new StatsItemSet(Stats.QUEUE_PUT_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.QUEUE_PUT_SIZE, new StatsItemSet(Stats.QUEUE_PUT_SIZE, this.scheduledExecutorService, log));
this.statsTable.put(Stats.QUEUE_GET_NUMS, new StatsItemSet(Stats.QUEUE_GET_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.QUEUE_GET_SIZE, new StatsItemSet(Stats.QUEUE_GET_SIZE, this.scheduledExecutorService, log));
}
this.statsTable.put(Stats.TOPIC_PUT_NUMS, new StatsItemSet(Stats.TOPIC_PUT_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.TOPIC_PUT_SIZE, new StatsItemSet(Stats.TOPIC_PUT_SIZE, this.scheduledExecutorService, log));
this.statsTable.put(Stats.GROUP_GET_NUMS, new StatsItemSet(Stats.GROUP_GET_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.GROUP_GET_SIZE, new StatsItemSet(Stats.GROUP_GET_SIZE, this.scheduledExecutorService, log));
this.statsTable.put(GROUP_ACK_NUMS, new StatsItemSet(GROUP_ACK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(GROUP_CK_NUMS, new StatsItemSet(GROUP_CK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.GROUP_GET_LATENCY, new StatsItemSet(Stats.GROUP_GET_LATENCY, this.scheduledExecutorService, log));
this.statsTable.put(TOPIC_PUT_LATENCY, new StatsItemSet(TOPIC_PUT_LATENCY, this.scheduledExecutorService, log));
this.statsTable.put(Stats.SNDBCK_PUT_NUMS, new StatsItemSet(Stats.SNDBCK_PUT_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(DLQ_PUT_NUMS, new StatsItemSet(DLQ_PUT_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.BROKER_PUT_NUMS, new StatsItemSet(Stats.BROKER_PUT_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.BROKER_GET_NUMS, new StatsItemSet(Stats.BROKER_GET_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(BROKER_ACK_NUMS, new StatsItemSet(BROKER_ACK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(BROKER_CK_NUMS, new StatsItemSet(BROKER_CK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC,
new StatsItemSet(BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC, this.scheduledExecutorService, log));
this.statsTable.put(BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC,
new StatsItemSet(BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC, this.scheduledExecutorService, log));
this.statsTable.put(Stats.GROUP_GET_FROM_DISK_NUMS,
new StatsItemSet(Stats.GROUP_GET_FROM_DISK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.GROUP_GET_FROM_DISK_SIZE,
new StatsItemSet(Stats.GROUP_GET_FROM_DISK_SIZE, this.scheduledExecutorService, log));
this.statsTable.put(Stats.BROKER_GET_FROM_DISK_NUMS,
new StatsItemSet(Stats.BROKER_GET_FROM_DISK_NUMS, this.scheduledExecutorService, log));
this.statsTable.put(Stats.BROKER_GET_FROM_DISK_SIZE,
new StatsItemSet(Stats.BROKER_GET_FROM_DISK_SIZE, this.scheduledExecutorService, log));
this.statsTable.put(SNDBCK2DLQ_TIMES,
new StatsItemSet(SNDBCK2DLQ_TIMES, this.scheduledExecutorService, DLQ_STAT_LOG));
this.statsTable.put(Stats.COMMERCIAL_SEND_TIMES,
new StatsItemSet(Stats.COMMERCIAL_SEND_TIMES, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_RCV_TIMES,
new StatsItemSet(Stats.COMMERCIAL_RCV_TIMES, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_SEND_SIZE,
new StatsItemSet(Stats.COMMERCIAL_SEND_SIZE, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_RCV_SIZE,
new StatsItemSet(Stats.COMMERCIAL_RCV_SIZE, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_RCV_EPOLLS,
new StatsItemSet(Stats.COMMERCIAL_RCV_EPOLLS, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_SNDBCK_TIMES,
new StatsItemSet(Stats.COMMERCIAL_SNDBCK_TIMES, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(Stats.COMMERCIAL_PERM_FAILURES,
new StatsItemSet(Stats.COMMERCIAL_PERM_FAILURES, this.commercialExecutor, COMMERCIAL_LOG));
this.statsTable.put(CONSUMER_REGISTER_TIME,
new StatsItemSet(CONSUMER_REGISTER_TIME, this.scheduledExecutorService, log));
this.statsTable.put(PRODUCER_REGISTER_TIME,
new StatsItemSet(PRODUCER_REGISTER_TIME, this.scheduledExecutorService, log));
this.statsTable.put(CHANNEL_ACTIVITY, new StatsItemSet(CHANNEL_ACTIVITY, this.scheduledExecutorService, log));
StatisticsItemFormatter formatter = new StatisticsItemFormatter();
accountStatManager.setBriefMeta(new Pair[] {
Pair.of(RT, new long[][] {{50, 50}, {100, 10}, {1000, 10}}),
Pair.of(INNER_RT, new long[][] {{10, 10}, {100, 10}, {1000, 10}})});
String[] itemNames = new String[] {
MSG_NUM, SUCCESS_MSG_NUM, FAILURE_MSG_NUM, COMMERCIAL_MSG_NUM,
SUCCESS_REQ_NUM, FAILURE_REQ_NUM,
MSG_SIZE, SUCCESS_MSG_SIZE, FAILURE_MSG_SIZE,
RT, INNER_RT};
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_SEND, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_RCV, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_SEND_BACK, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_SEND_BACK_TO_DLQ, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_SEND_REJ, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.addStatisticsKindMeta(createStatisticsKindMeta(
ACCOUNT_REV_REJ, itemNames, this.accountExecutor, formatter, ACCOUNT_LOG, ACCOUNT_STAT_INVERTAL));
this.accountStatManager.setStatisticsItemStateGetter(new StatisticsItemStateGetter() {
@Override
public boolean online(StatisticsItem item) {
String[] strArr = null;
try {
strArr = splitAccountStatKey(item.getStatObject());
} catch (Exception e) {
log.warn("parse account stat key failed, key: {}", item.getStatObject());
return false;
}
// TODO ugly
if (strArr == null || strArr.length < 4) {
return false;
}
String instanceId = strArr[1];
String topic = strArr[2];
String group = strArr[3];
String kind = item.getStatKind();
if (ACCOUNT_SEND.equals(kind) || ACCOUNT_SEND_REJ.equals(kind)) {
return produerStateGetter.online(instanceId, group, topic);
} else if (ACCOUNT_RCV.equals(kind) || ACCOUNT_SEND_BACK.equals(kind) || ACCOUNT_SEND_BACK_TO_DLQ.equals(kind) || ACCOUNT_REV_REJ.equals(kind)) {
return consumerStateGetter.online(instanceId, group, topic);
}
return false;
}
});
}
private void initScheduleService() {
this.scheduledExecutorService =
ThreadUtils.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("BrokerStatsThread", true, brokerConfig));
this.commercialExecutor =
ThreadUtils.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("CommercialStatsThread", true, brokerConfig));
this.accountExecutor =
ThreadUtils.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("AccountStatsThread", true, brokerConfig));
}
public MomentStatsItemSet getMomentStatsItemSetFallSize() {
return momentStatsItemSetFallSize;
}
public MomentStatsItemSet getMomentStatsItemSetFallTime() {
return momentStatsItemSetFallTime;
}
public StateGetter getProduerStateGetter() {
return produerStateGetter;
}
public void setProduerStateGetter(StateGetter produerStateGetter) {
this.produerStateGetter = produerStateGetter;
}
public StateGetter getConsumerStateGetter() {
return consumerStateGetter;
}
public void setConsumerStateGetter(StateGetter consumerStateGetter) {
this.consumerStateGetter = consumerStateGetter;
}
public void start() {
}
public void shutdown() {
this.scheduledExecutorService.shutdown();
this.commercialExecutor.shutdown();
}
public StatsItem getStatsItem(final String statsName, final String statsKey) {
try {
return this.statsTable.get(statsName).getStatsItem(statsKey);
} catch (Exception e) {
}
return null;
}
public void onTopicDeleted(final String topic) {
this.statsTable.get(Stats.TOPIC_PUT_NUMS).delValue(topic);
this.statsTable.get(Stats.TOPIC_PUT_SIZE).delValue(topic);
if (enableQueueStat) {
this.statsTable.get(Stats.QUEUE_PUT_NUMS).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.QUEUE_PUT_SIZE).delValueByPrefixKey(topic, "@");
}
this.statsTable.get(Stats.GROUP_GET_NUMS).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.GROUP_GET_SIZE).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.QUEUE_GET_NUMS).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.QUEUE_GET_SIZE).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.SNDBCK_PUT_NUMS).delValueByPrefixKey(topic, "@");
this.statsTable.get(Stats.GROUP_GET_LATENCY).delValueByInfixKey(topic, "@");
this.momentStatsItemSetFallSize.delValueByInfixKey(topic, "@");
this.momentStatsItemSetFallTime.delValueByInfixKey(topic, "@");
}
public void onGroupDeleted(final String group) {
this.statsTable.get(Stats.GROUP_GET_NUMS).delValueBySuffixKey(group, "@");
this.statsTable.get(Stats.GROUP_GET_SIZE).delValueBySuffixKey(group, "@");
if (enableQueueStat) {
this.statsTable.get(Stats.QUEUE_GET_NUMS).delValueBySuffixKey(group, "@");
this.statsTable.get(Stats.QUEUE_GET_SIZE).delValueBySuffixKey(group, "@");
}
this.statsTable.get(Stats.SNDBCK_PUT_NUMS).delValueBySuffixKey(group, "@");
this.statsTable.get(Stats.GROUP_GET_LATENCY).delValueBySuffixKey(group, "@");
this.momentStatsItemSetFallSize.delValueBySuffixKey(group, "@");
this.momentStatsItemSetFallTime.delValueBySuffixKey(group, "@");
}
public void incQueuePutNums(final String topic, final Integer queueId) {
if (enableQueueStat) {
this.statsTable.get(Stats.QUEUE_PUT_NUMS).addValue(buildStatsKey(topic, queueId), 1, 1);
}
}
public void incQueuePutNums(final String topic, final Integer queueId, int num, int times) {
if (enableQueueStat) {
this.statsTable.get(Stats.QUEUE_PUT_NUMS).addValue(buildStatsKey(topic, queueId), num, times);
}
}
public void incQueuePutSize(final String topic, final Integer queueId, final int size) {
if (enableQueueStat) {
this.statsTable.get(Stats.QUEUE_PUT_SIZE).addValue(buildStatsKey(topic, queueId), size, 1);
}
}
public void incQueueGetNums(final String group, final String topic, final Integer queueId, final int incValue) {
if (enableQueueStat) {
final String statsKey = buildStatsKey(topic, queueId, group);
this.statsTable.get(Stats.QUEUE_GET_NUMS).addValue(statsKey, incValue, 1);
}
}
public void incQueueGetSize(final String group, final String topic, final Integer queueId, final int incValue) {
if (enableQueueStat) {
final String statsKey = buildStatsKey(topic, queueId, group);
this.statsTable.get(Stats.QUEUE_GET_SIZE).addValue(statsKey, incValue, 1);
}
}
public void incConsumerRegisterTime(final int incValue) {
this.statsTable.get(CONSUMER_REGISTER_TIME).addValue(this.clusterName, incValue, 1);
}
public void incProducerRegisterTime(final int incValue) {
this.statsTable.get(PRODUCER_REGISTER_TIME).addValue(this.clusterName, incValue, 1);
}
public void incChannelConnectNum() {
this.statsTable.get(CHANNEL_ACTIVITY).addValue(CHANNEL_ACTIVITY_CONNECT, 1, 1);
}
public void incChannelCloseNum() {
this.statsTable.get(CHANNEL_ACTIVITY).addValue(CHANNEL_ACTIVITY_CLOSE, 1, 1);
}
public void incChannelExceptionNum() {
this.statsTable.get(CHANNEL_ACTIVITY).addValue(CHANNEL_ACTIVITY_EXCEPTION, 1, 1);
}
public void incChannelIdleNum() {
this.statsTable.get(CHANNEL_ACTIVITY).addValue(CHANNEL_ACTIVITY_IDLE, 1, 1);
}
public void incTopicPutNums(final String topic) {
this.statsTable.get(Stats.TOPIC_PUT_NUMS).addValue(topic, 1, 1);
}
public void incTopicPutNums(final String topic, int num, int times) {
this.statsTable.get(Stats.TOPIC_PUT_NUMS).addValue(topic, num, times);
}
public void incTopicPutSize(final String topic, final int size) {
this.statsTable.get(Stats.TOPIC_PUT_SIZE).addValue(topic, size, 1);
}
public void incGroupGetNums(final String group, final String topic, final int incValue) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(Stats.GROUP_GET_NUMS).addValue(statsKey, incValue, 1);
}
public void incGroupCkNums(final String group, final String topic, final int incValue) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(GROUP_CK_NUMS).addValue(statsKey, incValue, 1);
}
public void incGroupAckNums(final String group, final String topic, final int incValue) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(GROUP_ACK_NUMS).addValue(statsKey, incValue, 1);
}
public String buildStatsKey(String topic, String group) {
StringBuilder strBuilder;
if (topic != null && group != null) {
strBuilder = new StringBuilder(topic.length() + group.length() + 1);
} else {
strBuilder = new StringBuilder();
}
strBuilder.append(topic).append("@").append(group);
return strBuilder.toString();
}
public String buildStatsKey(String topic, int queueId) {
StringBuilder strBuilder;
if (topic != null) {
strBuilder = new StringBuilder(topic.length() + 5);
} else {
strBuilder = new StringBuilder();
}
strBuilder.append(topic).append("@").append(queueId);
return strBuilder.toString();
}
public String buildStatsKey(String topic, int queueId, String group) {
StringBuilder strBuilder;
if (topic != null && group != null) {
strBuilder = new StringBuilder(topic.length() + group.length() + 6);
} else {
strBuilder = new StringBuilder();
}
strBuilder.append(topic).append("@").append(queueId).append("@").append(group);
return strBuilder.toString();
}
public String buildStatsKey(int queueId, String topic, String group) {
StringBuilder strBuilder;
if (topic != null && group != null) {
strBuilder = new StringBuilder(topic.length() + group.length() + 6);
} else {
strBuilder = new StringBuilder();
}
strBuilder.append(queueId).append("@").append(topic).append("@").append(group);
return strBuilder.toString();
}
public void incGroupGetSize(final String group, final String topic, final int incValue) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(Stats.GROUP_GET_SIZE).addValue(statsKey, incValue, 1);
}
public void incGroupGetLatency(final String group, final String topic, final int queueId, final int incValue) {
String statsKey;
if (enableQueueStat) {
statsKey = buildStatsKey(queueId, topic, group);
} else {
statsKey = buildStatsKey(topic, group);
}
this.statsTable.get(Stats.GROUP_GET_LATENCY).addRTValue(statsKey, incValue, 1);
}
public void incTopicPutLatency(final String topic, final int queueId, final int incValue) {
StringBuilder statsKey;
if (topic != null) {
statsKey = new StringBuilder(topic.length() + 6);
} else {
statsKey = new StringBuilder(6);
}
statsKey.append(queueId).append("@").append(topic);
this.statsTable.get(TOPIC_PUT_LATENCY).addValue(statsKey.toString(), incValue, 1);
}
public void incBrokerPutNums() {
this.statsTable.get(Stats.BROKER_PUT_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(1);
}
public void incBrokerPutNums(final String topic, final int incValue) {
this.statsTable.get(Stats.BROKER_PUT_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
incBrokerPutNumsWithoutSystemTopic(topic, incValue);
}
public void incBrokerGetNums(final String topic, final int incValue) {
this.statsTable.get(Stats.BROKER_GET_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
this.incBrokerGetNumsWithoutSystemTopic(topic, incValue);
}
public void incBrokerAckNums(final int incValue) {
this.statsTable.get(BROKER_ACK_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
}
public void incBrokerCkNums(final int incValue) {
this.statsTable.get(BROKER_CK_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
}
public void incBrokerGetNumsWithoutSystemTopic(final String topic, final int incValue) {
if (TopicValidator.isSystemTopic(topic)) {
return;
}
this.statsTable.get(BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
}
public void incBrokerPutNumsWithoutSystemTopic(final String topic, final int incValue) {
if (TopicValidator.isSystemTopic(topic)) {
return;
}
this.statsTable.get(BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
}
public long getBrokerGetNumsWithoutSystemTopic() {
final StatsItemSet statsItemSet = this.statsTable.get(BROKER_GET_NUMS_WITHOUT_SYSTEM_TOPIC);
if (statsItemSet == null) {
return 0;
}
final StatsItem statsItem = statsItemSet.getStatsItem(this.clusterName);
if (statsItem == null) {
return 0;
}
return statsItem.getValue().longValue();
}
public long getBrokerPutNumsWithoutSystemTopic() {
final StatsItemSet statsItemSet = this.statsTable.get(BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC);
if (statsItemSet == null) {
return 0;
}
final StatsItem statsItem = statsItemSet.getStatsItem(this.clusterName);
if (statsItem == null) {
return 0;
}
return statsItem.getValue().longValue();
}
public void incSendBackNums(final String group, final String topic) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(Stats.SNDBCK_PUT_NUMS).addValue(statsKey, 1, 1);
}
public double tpsGroupGetNums(final String group, final String topic) {
final String statsKey = buildStatsKey(topic, group);
return this.statsTable.get(Stats.GROUP_GET_NUMS).getStatsDataInMinute(statsKey).getTps();
}
public void recordDiskFallBehindTime(final String group, final String topic, final int queueId,
final long fallBehind) {
final String statsKey = buildStatsKey(queueId, topic, group);
this.momentStatsItemSetFallTime.getAndCreateStatsItem(statsKey).getValue().set(fallBehind);
}
public void recordDiskFallBehindSize(final String group, final String topic, final int queueId,
final long fallBehind) {
final String statsKey = buildStatsKey(queueId, topic, group);
this.momentStatsItemSetFallSize.getAndCreateStatsItem(statsKey).getValue().set(fallBehind);
}
public void incDLQStatValue(final String key, final String owner, final String group,
final String topic, final String type, final int incValue) {
final String statsKey = buildCommercialStatsKey(owner, topic, group, type);
this.statsTable.get(key).addValue(statsKey, incValue, 1);
}
public void incCommercialValue(final String key, final String owner, final String group,
final String topic, final String type, final int incValue) {
final String statsKey = buildCommercialStatsKey(owner, topic, group, type);
this.statsTable.get(key).addValue(statsKey, incValue, 1);
}
public void incAccountValue(final String key, final String accountOwnerParent, final String accountOwnerSelf,
final String instanceId, final String group, final String topic,
final String msgType, final int incValue) {
final String statsKey = buildAccountStatsKey(accountOwnerParent, accountOwnerSelf, instanceId, topic, group,
msgType);
this.statsTable.get(key).addValue(statsKey, incValue, 1);
}
public void incAccountValue(final String key, final String accountOwnerParent, final String accountOwnerSelf,
final String instanceId, final String group, final String topic,
final String msgType, final String flowlimitThreshold, final int incValue) {
final String statsKey = buildAccountStatsKey(accountOwnerParent, accountOwnerSelf, instanceId, topic, group,
msgType, flowlimitThreshold);
this.statsTable.get(key).addValue(statsKey, incValue, 1);
}
public void incAccountValue(final String statType, final String owner, final String instanceId, final String topic,
final String group, final String msgType,
final long... incValues) {
final String key = buildAccountStatKey(owner, instanceId, topic, group, msgType);
this.accountStatManager.inc(statType, key, incValues);
}
public void incAccountValue(final String statType, final String owner, final String instanceId, final String topic,
final String group, final String msgType, final String flowlimitThreshold,
final long... incValues) {
final String key = buildAccountStatKey(owner, instanceId, topic, group, msgType, flowlimitThreshold);
this.accountStatManager.inc(statType, key, incValues);
}
public String buildCommercialStatsKey(String owner, String topic, String group, String type) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(owner);
strBuilder.append("@");
strBuilder.append(topic);
strBuilder.append("@");
strBuilder.append(group);
strBuilder.append("@");
strBuilder.append(type);
return strBuilder.toString();
}
public String buildAccountStatsKey(String accountOwnerParent, String accountOwnerSelf, String instanceId,
String topic, String group, String msgType) {
StringBuffer strBuilder = new StringBuffer();
strBuilder.append(accountOwnerParent);
strBuilder.append("@");
strBuilder.append(accountOwnerSelf);
strBuilder.append("@");
strBuilder.append(instanceId);
strBuilder.append("@");
strBuilder.append(topic);
strBuilder.append("@");
strBuilder.append(group);
strBuilder.append("@");
strBuilder.append(msgType);
return strBuilder.toString();
}
public String buildAccountStatsKey(String accountOwnerParent, String accountOwnerSelf, String instanceId,
String topic, String group, String msgType, String flowlimitThreshold) {
StringBuffer strBuilder = new StringBuffer();
strBuilder.append(accountOwnerParent);
strBuilder.append("@");
strBuilder.append(accountOwnerSelf);
strBuilder.append("@");
strBuilder.append(instanceId);
strBuilder.append("@");
strBuilder.append(topic);
strBuilder.append("@");
strBuilder.append(group);
strBuilder.append("@");
strBuilder.append(msgType);
strBuilder.append("@");
strBuilder.append(flowlimitThreshold);
return strBuilder.toString();
}
public String buildAccountStatKey(final String owner, final String instanceId,
final String topic, final String group,
final String msgType) {
final String sep = "|";
StringBuffer strBuilder = new StringBuffer();
strBuilder.append(owner).append(sep);
strBuilder.append(instanceId).append(sep);
strBuilder.append(topic).append(sep);
strBuilder.append(group).append(sep);
strBuilder.append(msgType);
return strBuilder.toString();
}
public String buildAccountStatKey(final String owner, final String instanceId,
final String topic, final String group,
final String msgType, String flowlimitThreshold) {
final String sep = "|";
StringBuffer strBuilder = new StringBuffer();
strBuilder.append(owner).append(sep);
strBuilder.append(instanceId).append(sep);
strBuilder.append(topic).append(sep);
strBuilder.append(group).append(sep);
strBuilder.append(msgType).append(sep);
strBuilder.append(flowlimitThreshold);
return strBuilder.toString();
}
public String[] splitAccountStatKey(final String accountStatKey) {
final String sep = "\\|";
return accountStatKey.split(sep);
}
private StatisticsKindMeta createStatisticsKindMeta(String name,
String[] itemNames,
ScheduledExecutorService executorService,
StatisticsItemFormatter formatter,
Logger log,
long interval) {
final BrokerConfig brokerConfig = this.brokerConfig;
StatisticsItemPrinter printer = new StatisticsItemPrinter(formatter, log);
StatisticsKindMeta kindMeta = new StatisticsKindMeta();
kindMeta.setName(name);
kindMeta.setItemNames(itemNames);
kindMeta.setScheduledPrinter(
new StatisticsItemScheduledIncrementPrinter(
"Stat In One Minute: ",
printer,
executorService,
new StatisticsItemScheduledPrinter.InitialDelay() {
@Override
public long get() {
return Math.abs(UtilAll.computeNextMinutesTimeMillis() - System.currentTimeMillis());
}
},
interval,
new String[] {MSG_NUM},
new StatisticsItemScheduledIncrementPrinter.Valve() {
@Override
public boolean enabled() {
return brokerConfig != null ? brokerConfig.isAccountStatsEnable() : true;
}
@Override
public boolean printZeroLine() {
return brokerConfig != null ? brokerConfig.isAccountStatsPrintZeroValues() : true;
}
}
)
);
return kindMeta;
}
public interface StateGetter {
boolean online(String instanceId, String group, String topic);
}
public enum StatsType {
SEND_SUCCESS,
SEND_FAILURE,
RCV_SUCCESS,
RCV_EPOLLS,
SEND_BACK,
SEND_BACK_TO_DLQ,
SEND_ORDER,
SEND_TIMER,
SEND_TRANSACTION,
PERM_FAILURE
}
}
| apache/rocketmq | store/src/main/java/org/apache/rocketmq/store/stats/BrokerStatsManager.java |
45,258 | 404: Not Found | apache/dubbo | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java |
45,259 | package com.baeldung.netty.customhandlersandlisteners.model;
public class OnlineMessage extends Message {
public OnlineMessage(String info) {
super("system", "client online: " + info);
}
}
| eugenp/tutorials | libraries-server-2/src/main/java/com/baeldung/netty/customhandlersandlisteners/model/OnlineMessage.java |
45,260 | /*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
package com.zerotier.sdk;
import com.zerotier.sdk.util.StringUtils;
/**
* Current node status
* <p>
* Defined in ZeroTierOne.h as ZT_NodeStatus
*/
public class NodeStatus {
private final long address;
private final String publicIdentity;
private final String secretIdentity;
private final boolean online;
public NodeStatus(long address, String publicIdentity, String secretIdentity, boolean online) {
this.address = address;
this.publicIdentity = publicIdentity;
this.secretIdentity = secretIdentity;
this.online = online;
}
@Override
public String toString() {
return "NodeStatus(" + StringUtils.addressToString(address) + ", " + publicIdentity + ", " + secretIdentity + ", " + online + ")";
}
/**
* 40-bit ZeroTier address of this node
*/
public long getAddress() {
return address;
}
/**
* Public identity in string-serialized form (safe to send to others)
*
* <p>This identity will remain valid as long as the node exists.</p>
*/
public String getPublicIdentity() {
return publicIdentity;
}
/**
* Full identity including secret key in string-serialized form
*
* <p>This identity will remain valid as long as the node exists.</p>
*/
public String getSecretIdentity() {
return secretIdentity;
}
/**
* True if some kind of connectivity appears available
*/
public boolean isOnline() {
return online;
}
}
| zerotier/ZeroTierOne | java/src/com/zerotier/sdk/NodeStatus.java |
45,261 | /*
* Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma
*
* 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 com.termux.shared.shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Locale;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import com.termux.shared.logger.Logger;
/**
* Thread utility class continuously reading from an InputStream
*
* https://github.com/Chainfire/libsuperuser/blob/1.1.0.201907261845/libsuperuser/src/eu/chainfire/libsuperuser/Shell.java#L141
* https://github.com/Chainfire/libsuperuser/blob/1.1.0.201907261845/libsuperuser/src/eu/chainfire/libsuperuser/StreamGobbler.java
*/
@SuppressWarnings({"WeakerAccess"})
public class StreamGobbler extends Thread {
private static int threadCounter = 0;
private static int incThreadCounter() {
synchronized (StreamGobbler.class) {
int ret = threadCounter;
threadCounter++;
return ret;
}
}
/**
* Line callback interface
*/
public interface OnLineListener {
/**
* <p>Line callback</p>
*
* <p>This callback should process the line as quickly as possible.
* Delays in this callback may pause the native process or even
* result in a deadlock</p>
*
* @param line String that was gobbled
*/
void onLine(String line);
}
/**
* Stream closed callback interface
*/
public interface OnStreamClosedListener {
/**
* <p>Stream closed callback</p>
*/
void onStreamClosed();
}
@NonNull
private final String shell;
@NonNull
private final InputStream inputStream;
@NonNull
private final BufferedReader reader;
@Nullable
private final List<String> listWriter;
@Nullable
private final StringBuilder stringWriter;
@Nullable
private final OnLineListener lineListener;
@Nullable
private final OnStreamClosedListener streamClosedListener;
@Nullable
private final Integer mLogLevel;
private volatile boolean active = true;
private volatile boolean calledOnClose = false;
private static final String LOG_TAG = "StreamGobbler";
/**
* <p>StreamGobbler constructor</p>
*
* <p>We use this class because shell STDOUT and STDERR should be read as quickly as
* possible to prevent a deadlock from occurring, or Process.waitFor() never
* returning (as the buffer is full, pausing the native process)</p>
*
* @param shell Name of the shell
* @param inputStream InputStream to read from
* @param outputList {@literal List<String>} to write to, or null
* @param logLevel The custom log level to use for logging the command output. If set to
* {@code null}, then {@link Logger#LOG_LEVEL_VERBOSE} will be used.
*/
@AnyThread
public StreamGobbler(@NonNull String shell, @NonNull InputStream inputStream,
@Nullable List<String> outputList,
@Nullable Integer logLevel) {
super("Gobbler#" + incThreadCounter());
this.shell = shell;
this.inputStream = inputStream;
reader = new BufferedReader(new InputStreamReader(inputStream));
streamClosedListener = null;
listWriter = outputList;
stringWriter = null;
lineListener = null;
mLogLevel = logLevel;
}
/**
* <p>StreamGobbler constructor</p>
*
* <p>We use this class because shell STDOUT and STDERR should be read as quickly as
* possible to prevent a deadlock from occurring, or Process.waitFor() never
* returning (as the buffer is full, pausing the native process)</p>
* Do not use this for concurrent reading for STDOUT and STDERR for the same StringBuilder since
* its not synchronized.
*
* @param shell Name of the shell
* @param inputStream InputStream to read from
* @param outputString {@literal List<String>} to write to, or null
* @param logLevel The custom log level to use for logging the command output. If set to
* {@code null}, then {@link Logger#LOG_LEVEL_VERBOSE} will be used.
*/
@AnyThread
public StreamGobbler(@NonNull String shell, @NonNull InputStream inputStream,
@Nullable StringBuilder outputString,
@Nullable Integer logLevel) {
super("Gobbler#" + incThreadCounter());
this.shell = shell;
this.inputStream = inputStream;
reader = new BufferedReader(new InputStreamReader(inputStream));
streamClosedListener = null;
listWriter = null;
stringWriter = outputString;
lineListener = null;
mLogLevel = logLevel;
}
/**
* <p>StreamGobbler constructor</p>
*
* <p>We use this class because shell STDOUT and STDERR should be read as quickly as
* possible to prevent a deadlock from occurring, or Process.waitFor() never
* returning (as the buffer is full, pausing the native process)</p>
*
* @param shell Name of the shell
* @param inputStream InputStream to read from
* @param onLineListener OnLineListener callback
* @param onStreamClosedListener OnStreamClosedListener callback
* @param logLevel The custom log level to use for logging the command output. If set to
* {@code null}, then {@link Logger#LOG_LEVEL_VERBOSE} will be used.
*/
@AnyThread
public StreamGobbler(@NonNull String shell, @NonNull InputStream inputStream,
@Nullable OnLineListener onLineListener,
@Nullable OnStreamClosedListener onStreamClosedListener,
@Nullable Integer logLevel) {
super("Gobbler#" + incThreadCounter());
this.shell = shell;
this.inputStream = inputStream;
reader = new BufferedReader(new InputStreamReader(inputStream));
streamClosedListener = onStreamClosedListener;
listWriter = null;
stringWriter = null;
lineListener = onLineListener;
mLogLevel = logLevel;
}
@Override
public void run() {
String defaultLogTag = Logger.getDefaultLogTag();
boolean loggingEnabled = Logger.shouldEnableLoggingForCustomLogLevel(mLogLevel);
if (loggingEnabled)
Logger.logVerbose(LOG_TAG, "Using custom log level: " + mLogLevel + ", current log level: " + Logger.getLogLevel());
// keep reading the InputStream until it ends (or an error occurs)
// optionally pausing when a command is executed that consumes the InputStream itself
try {
String line;
while ((line = reader.readLine()) != null) {
if (loggingEnabled)
Logger.logVerboseForce(defaultLogTag + "Command", String.format(Locale.ENGLISH, "[%s] %s", shell, line)); // This will get truncated by LOGGER_ENTRY_MAX_LEN, likely 4KB
if (stringWriter != null) stringWriter.append(line).append("\n");
if (listWriter != null) listWriter.add(line);
if (lineListener != null) lineListener.onLine(line);
while (!active) {
synchronized (this) {
try {
this.wait(128);
} catch (InterruptedException e) {
// no action
}
}
}
}
} catch (IOException e) {
// reader probably closed, expected exit condition
if (streamClosedListener != null) {
calledOnClose = true;
streamClosedListener.onStreamClosed();
}
}
// make sure our stream is closed and resources will be freed
try {
reader.close();
} catch (IOException e) {
// read already closed
}
if (!calledOnClose) {
if (streamClosedListener != null) {
calledOnClose = true;
streamClosedListener.onStreamClosed();
}
}
}
/**
* <p>Resume consuming the input from the stream</p>
*/
@AnyThread
public void resumeGobbling() {
if (!active) {
synchronized (this) {
active = true;
this.notifyAll();
}
}
}
/**
* <p>Suspend gobbling, so other code may read from the InputStream instead</p>
*
* <p>This should <i>only</i> be called from the OnLineListener callback!</p>
*/
@AnyThread
public void suspendGobbling() {
synchronized (this) {
active = false;
this.notifyAll();
}
}
/**
* <p>Wait for gobbling to be suspended</p>
*
* <p>Obviously this cannot be called from the same thread as {@link #suspendGobbling()}</p>
*/
@WorkerThread
public void waitForSuspend() {
synchronized (this) {
while (active) {
try {
this.wait(32);
} catch (InterruptedException e) {
// no action
}
}
}
}
/**
* <p>Is gobbling suspended ?</p>
*
* @return is gobbling suspended?
*/
@AnyThread
public boolean isSuspended() {
synchronized (this) {
return !active;
}
}
/**
* <p>Get current source InputStream</p>
*
* @return source InputStream
*/
@NonNull
@AnyThread
public InputStream getInputStream() {
return inputStream;
}
/**
* <p>Get current OnLineListener</p>
*
* @return OnLineListener
*/
@Nullable
@AnyThread
public OnLineListener getOnLineListener() {
return lineListener;
}
void conditionalJoin() throws InterruptedException {
if (calledOnClose) return; // deadlock from callback, we're inside exit procedure
if (Thread.currentThread() == this) return; // can't join self
join();
}
}
| izzy2fancy/termux-app | termux-shared/src/main/java/com/termux/shared/shell/StreamGobbler.java |
45,262 | /*
* Copyright 2016 - 2020 Anton Tananaev ([email protected])
*
* 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.traccar.model;
import org.traccar.storage.StorageName;
import java.util.Date;
@StorageName("tc_events")
public class Event extends Message {
public Event(String type, Position position) {
setType(type);
setPositionId(position.getId());
setDeviceId(position.getDeviceId());
eventTime = position.getDeviceTime();
}
public Event(String type, long deviceId) {
setType(type);
setDeviceId(deviceId);
eventTime = new Date();
}
public Event() {
}
public static final String ALL_EVENTS = "allEvents";
public static final String TYPE_COMMAND_RESULT = "commandResult";
public static final String TYPE_DEVICE_ONLINE = "deviceOnline";
public static final String TYPE_DEVICE_UNKNOWN = "deviceUnknown";
public static final String TYPE_DEVICE_OFFLINE = "deviceOffline";
public static final String TYPE_DEVICE_INACTIVE = "deviceInactive";
public static final String TYPE_QUEUED_COMMAND_SENT = "queuedCommandSent";
public static final String TYPE_DEVICE_MOVING = "deviceMoving";
public static final String TYPE_DEVICE_STOPPED = "deviceStopped";
public static final String TYPE_DEVICE_OVERSPEED = "deviceOverspeed";
public static final String TYPE_DEVICE_FUEL_DROP = "deviceFuelDrop";
public static final String TYPE_DEVICE_FUEL_INCREASE = "deviceFuelIncrease";
public static final String TYPE_GEOFENCE_ENTER = "geofenceEnter";
public static final String TYPE_GEOFENCE_EXIT = "geofenceExit";
public static final String TYPE_ALARM = "alarm";
public static final String TYPE_IGNITION_ON = "ignitionOn";
public static final String TYPE_IGNITION_OFF = "ignitionOff";
public static final String TYPE_MAINTENANCE = "maintenance";
public static final String TYPE_TEXT_MESSAGE = "textMessage";
public static final String TYPE_DRIVER_CHANGED = "driverChanged";
public static final String TYPE_MEDIA = "media";
private Date eventTime;
public Date getEventTime() {
return eventTime;
}
public void setEventTime(Date eventTime) {
this.eventTime = eventTime;
}
private long positionId;
public long getPositionId() {
return positionId;
}
public void setPositionId(long positionId) {
this.positionId = positionId;
}
private long geofenceId = 0;
public long getGeofenceId() {
return geofenceId;
}
public void setGeofenceId(long geofenceId) {
this.geofenceId = geofenceId;
}
private long maintenanceId = 0;
public long getMaintenanceId() {
return maintenanceId;
}
public void setMaintenanceId(long maintenanceId) {
this.maintenanceId = maintenanceId;
}
}
| traccar/traccar | src/main/java/org/traccar/model/Event.java |
45,263 | /**
* Copyright (c) 2006-2022, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.IOException;
public interface AbsComm
{
String getCookieValue(String name, Object request_p);
void addCookie(String name, String val, int age, String cookiePath, Object response_p);
void deleteCookie(String name, String cookiePath, Object response_p);
String getParameter(String name, Object request);
String getPostParameter(String name, Object request);
String getQueryString(Object request);
String getHeader(String name, Object request);
String getServerName(Object request);
String getRemoteAddr(Object request);
void setBody(String body, Object response) throws IOException;
void setStatus(int status, Object response);
void setHeader(String name, String value, Object response);
void sendRedirect(String url, Object response) throws IOException;
} | jgraph/drawio | src/main/java/com/mxgraph/online/AbsComm.java |
45,264 | package com.taobao.rigel.rap.common.service.impl;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
public class ContextManager {
public static final String KEY_COUNT_OF_ONLINE_USER_LIST = "KEY_COUNT_OF_ONLINE_USER_LIST";
public static final String KEY_ACCOUNT = "KEY_ACCOUNT";
public static final String KEY_PROJECT_LOCK_LIST = "KEY_PROJECT_LOCK_LIST";
public static final String KEY_USER_ID = "KEY_USER_ID";
// public static final String KEY_CORP_NAME = "KEY_CORP_NAME";
public static final String KEY_NAME = "KEY_NAME";
public static final String KEY_ROLE_LIST = "KEY_ROLE_LIST";
public static final String KEY_EMP_ID = "KEY_EMP_ID";
@SuppressWarnings("rawtypes")
public static Map currentSession() {
return ActionContext.getContext().getSession();
}
@SuppressWarnings("rawtypes")
public static Map getApplication() {
return ActionContext.getContext().getApplication();
}
}
| thx/RAP | src/main/java/com/taobao/rigel/rap/common/service/impl/ContextManager.java |
45,265 | package com.xkcoding.rbac.security.vo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.xkcoding.rbac.security.common.Consts;
import com.xkcoding.rbac.security.model.User;
import lombok.Data;
/**
* <p>
* 在线用户 VO
* </p>
*
* @author yangkai.shen
* @date Created in 2018-12-12 00:58
*/
@Data
public class OnlineUser {
/**
* 主键
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 昵称
*/
private String nickname;
/**
* 手机
*/
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 生日
*/
private Long birthday;
/**
* 性别,男-1,女-2
*/
private Integer sex;
public static OnlineUser create(User user) {
OnlineUser onlineUser = new OnlineUser();
BeanUtil.copyProperties(user, onlineUser);
// 脱敏
onlineUser.setPhone(StrUtil.hide(user.getPhone(), 3, 7));
onlineUser.setEmail(StrUtil.hide(user.getEmail(), 1, StrUtil.indexOfIgnoreCase(user.getEmail(), Consts.SYMBOL_EMAIL)));
return onlineUser;
}
}
| xkcoding/spring-boot-demo | demo-rbac-security/src/main/java/com/xkcoding/rbac/security/vo/OnlineUser.java |
45,266 | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class UserOnline implements Serializable{
private static final long serialVersionUID = 3828664348416633856L;
// session id
private String id;
// 用户id
private String userId;
// 用户名称
private String username;
// 用户主机地址
private String host;
// 用户登录时系统IP
private String systemHost;
// 状态
private String status;
// session创建时间
private Date startTimestamp;
// session最后访问时间
private Date lastAccessTime;
// 超时时间
private Long timeout;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSystemHost() {
return systemHost;
}
public void setSystemHost(String systemHost) {
this.systemHost = systemHost;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(Date startTimestamp) {
this.startTimestamp = startTimestamp;
}
public Date getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(Date lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
}
| wuyouzhuguli/SpringAll | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/UserOnline.java |
45,267 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.ast.statement;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.*;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
import java.util.ArrayList;
import java.util.List;
public class SQLAlterTableStatement extends SQLStatementImpl implements SQLDDLStatement, SQLAlterStatement {
private boolean only;
private SQLExprTableSource tableSource;
private List<SQLAlterTableItem> items = new ArrayList<SQLAlterTableItem>();
// for mysql
private boolean ignore;
private boolean online;
private boolean offline;
private boolean updateGlobalIndexes;
private boolean invalidateGlobalIndexes;
private boolean removePatiting;
private boolean upgradePatiting;
private List<SQLAssignItem> tableOptions = new ArrayList<SQLAssignItem>();
private SQLPartitionBy partition;
// odps
private boolean mergeSmallFiles;
protected boolean range;
protected final List<SQLSelectOrderByItem> clusteredBy = new ArrayList<SQLSelectOrderByItem>();
protected final List<SQLSelectOrderByItem> sortedBy = new ArrayList<SQLSelectOrderByItem>();
protected int buckets;
protected int shards;
private boolean ifExists;
private boolean notClustered;
// clickhouse
private SQLName on;
public SQLAlterTableStatement() {
}
public SQLAlterTableStatement(DbType dbType) {
super(dbType);
}
public boolean isOnly() {
return only;
}
public void setOnly(boolean only) {
this.only = only;
}
public boolean isIgnore() {
return ignore;
}
public void setIgnore(boolean ignore) {
this.ignore = ignore;
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
public boolean isOffline() {
return offline;
}
public void setOffline(boolean offline) {
this.offline = offline;
}
public boolean isIfExists() {
return ifExists;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
public boolean isRemovePatiting() {
return removePatiting;
}
public void setRemovePatiting(boolean removePatiting) {
this.removePatiting = removePatiting;
}
public boolean isUpgradePatiting() {
return upgradePatiting;
}
public void setUpgradePatiting(boolean upgradePatiting) {
this.upgradePatiting = upgradePatiting;
}
public boolean isUpdateGlobalIndexes() {
return updateGlobalIndexes;
}
public void setUpdateGlobalIndexes(boolean updateGlobalIndexes) {
this.updateGlobalIndexes = updateGlobalIndexes;
}
public boolean isInvalidateGlobalIndexes() {
return invalidateGlobalIndexes;
}
public void setInvalidateGlobalIndexes(boolean invalidateGlobalIndexes) {
this.invalidateGlobalIndexes = invalidateGlobalIndexes;
}
public boolean isMergeSmallFiles() {
return mergeSmallFiles;
}
public void setMergeSmallFiles(boolean mergeSmallFiles) {
this.mergeSmallFiles = mergeSmallFiles;
}
public List<SQLAlterTableItem> getItems() {
return items;
}
public void addItem(SQLAlterTableItem item) {
if (item != null) {
item.setParent(this);
}
this.items.add(item);
}
public SQLExprTableSource getTableSource() {
return tableSource;
}
public void setTableSource(SQLExprTableSource tableSource) {
this.tableSource = tableSource;
}
public void setTableSource(SQLExpr table) {
this.setTableSource(new SQLExprTableSource(table));
}
public SQLName getName() {
if (getTableSource() == null) {
return null;
}
return (SQLName) getTableSource().getExpr();
}
public long nameHashCode64() {
if (getTableSource() == null) {
return 0L;
}
return ((SQLName) getTableSource().getExpr()).nameHashCode64();
}
public void setName(SQLName name) {
this.setTableSource(new SQLExprTableSource(name));
}
public List<SQLAssignItem> getTableOptions() {
return tableOptions;
}
public SQLPartitionBy getPartition() {
return partition;
}
public void setPartition(SQLPartitionBy partition) {
this.partition = partition;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, getTableSource());
acceptChild(visitor, getItems());
}
visitor.endVisit(this);
}
@Override
public List<SQLObject> getChildren() {
List<SQLObject> children = new ArrayList<SQLObject>();
if (tableSource != null) {
children.add(tableSource);
}
children.addAll(this.items);
return children;
}
public String getTableName() {
if (tableSource == null) {
return null;
}
SQLExpr expr = ((SQLExprTableSource) tableSource).getExpr();
if (expr instanceof SQLIdentifierExpr) {
return ((SQLIdentifierExpr) expr).getName();
} else if (expr instanceof SQLPropertyExpr) {
return ((SQLPropertyExpr) expr).getName();
}
return null;
}
public String getSchema() {
SQLName name = getName();
if (name == null) {
return null;
}
if (name instanceof SQLPropertyExpr) {
return ((SQLPropertyExpr) name).getOwnernName();
}
return null;
}
public void setItems(List<SQLAlterTableItem> items) {
this.items = items;
}
public boolean isRange() {
return range;
}
public void setRange(boolean range) {
this.range = range;
}
public List<SQLSelectOrderByItem> getClusteredBy() {
return clusteredBy;
}
public void addClusteredByItem(SQLSelectOrderByItem item) {
item.setParent(this);
this.clusteredBy.add(item);
}
public List<SQLSelectOrderByItem> getSortedBy() {
return sortedBy;
}
public void addSortedByItem(SQLSelectOrderByItem item) {
item.setParent(this);
this.sortedBy.add(item);
}
public int getBuckets() {
return buckets;
}
public void setBuckets(int buckets) {
this.buckets = buckets;
}
public int getShards() {
return shards;
}
public void setShards(int shards) {
this.shards = shards;
}
public boolean isNotClustered() {
return notClustered;
}
public void setNotClustered(boolean notClustered) {
this.notClustered = notClustered;
}
@Override
public DDLObjectType getDDLObjectType() {
return DDLObjectType.TABLE;
}
public SQLName getOn() {
return on;
}
public void setOn(SQLName x) {
if (x != null) {
x.setParent(this);
}
this.on = x;
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableStatement.java |
45,269 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.html;
import java.awt.Color;
import java.util.Objects;
public class TextLine implements ValidatableLine {
private String text;
private Color textColor;
private ValidatableLine validationLine;
public TextLine(String text) {
this.text = Objects.requireNonNull(text);
}
@Override
public ValidatableLine copy() {
return new TextLine(text);
}
@Override
public String getText() {
return text;
}
@Override
public boolean isDiffColored() {
return textColor != null;
}
public Color getTextColor() {
return textColor;
}
@Override
public void setTextColor(Color color) {
this.textColor = color;
}
boolean matches(TextLine otherLine) {
return text.equals(otherLine.text);
}
@Override
public String toString() {
return text + colorStrig();
}
private String colorStrig() {
return textColor == null ? "" : " " + textColor.toString();
}
@Override
public boolean isValidated() {
return validationLine != null;
}
@Override
public boolean matches(ValidatableLine otherLine) {
if (!(otherLine instanceof TextLine)) {
return false;
}
TextLine textLine = (TextLine) otherLine;
return text.equals(textLine.getText());
}
@Override
public void updateColor(ValidatableLine otherLine, Color invalidColor) {
if (invalidColor == null) {
throw new NullPointerException("Color cannot be null");
}
if (otherLine == null) {
setTextColor(invalidColor);
return;
}
if (!matches(otherLine)) {
setTextColor(invalidColor);
otherLine.setTextColor(invalidColor);
}
}
@Override
public void setValidationLine(ValidatableLine line) {
if (validationLine == line) {
return; // already set
}
this.validationLine = line;
line.setValidationLine(this);
updateColor(line, INVALID_COLOR);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((text == null) ? 0 : text.hashCode());
result = prime * result + ((textColor == null) ? 0 : textColor.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TextLine other = (TextLine) obj;
if (text == null) {
if (other.text != null) {
return false;
}
}
else if (!text.equals(other.text)) {
return false;
}
if (textColor == null) {
if (other.textColor != null) {
return false;
}
}
else if (!textColor.equals(other.textColor)) {
return false;
}
return true;
}
}
| NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/util/html/TextLine.java |
45,270 | class Node {
int l, r;
int x, cnt;
}
class SegmentTree {
private Node[] tr;
private int[] nums;
public SegmentTree(int[] nums) {
int n = nums.length;
this.nums = nums;
tr = new Node[n << 2];
for (int i = 0; i < tr.length; ++i) {
tr[i] = new Node();
}
build(1, 1, n);
}
private void build(int u, int l, int r) {
tr[u].l = l;
tr[u].r = r;
if (l == r) {
tr[u].x = nums[l - 1];
tr[u].cnt = 1;
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
public int[] query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
return new int[] {tr[u].x, tr[u].cnt};
}
int mid = (tr[u].l + tr[u].r) >> 1;
if (r <= mid) {
return query(u << 1, l, r);
}
if (l > mid) {
return query(u << 1 | 1, l, r);
}
var left = query(u << 1, l, r);
var right = query(u << 1 | 1, l, r);
if (left[0] == right[0]) {
left[1] += right[1];
} else if (left[1] >= right[1]) {
left[1] -= right[1];
} else {
right[1] -= left[1];
left = right;
}
return left;
}
private void pushup(int u) {
if (tr[u << 1].x == tr[u << 1 | 1].x) {
tr[u].x = tr[u << 1].x;
tr[u].cnt = tr[u << 1].cnt + tr[u << 1 | 1].cnt;
} else if (tr[u << 1].cnt >= tr[u << 1 | 1].cnt) {
tr[u].x = tr[u << 1].x;
tr[u].cnt = tr[u << 1].cnt - tr[u << 1 | 1].cnt;
} else {
tr[u].x = tr[u << 1 | 1].x;
tr[u].cnt = tr[u << 1 | 1].cnt - tr[u << 1].cnt;
}
}
}
class MajorityChecker {
private SegmentTree tree;
private Map<Integer, List<Integer>> d = new HashMap<>();
public MajorityChecker(int[] arr) {
tree = new SegmentTree(arr);
for (int i = 0; i < arr.length; ++i) {
d.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
}
public int query(int left, int right, int threshold) {
int x = tree.query(1, left + 1, right + 1)[0];
int l = search(d.get(x), left);
int r = search(d.get(x), right + 1);
return r - l >= threshold ? x : -1;
}
private int search(List<Integer> arr, int x) {
int left = 0, right = arr.size();
while (left < right) {
int mid = (left + right) >> 1;
if (arr.get(mid) >= x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
/**
* Your MajorityChecker object will be instantiated and called as such:
* MajorityChecker obj = new MajorityChecker(arr);
* int param_1 = obj.query(left,right,threshold);
*/ | doocs/leetcode | solution/1100-1199/1157.Online Majority Element In Subarray/Solution.java |
45,271 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search.profile.query;
import org.apache.lucene.search.Query;
import org.elasticsearch.search.profile.AbstractProfiler;
import org.elasticsearch.search.profile.Timer;
import static java.util.Objects.requireNonNull;
/**
* This class acts as a thread-local storage for profiling a query. It also
* builds a representation of the query tree which is built constructed
* "online" as the weights are wrapped by ContextIndexSearcher. This allows us
* to know the relationship between nodes in tree without explicitly
* walking the tree or pre-wrapping everything
*
* A Profiler is associated with every Search, not per Search-Request. E.g. a
* request may execute two searches (query + global agg). A Profiler just
* represents one of those
*/
public final class QueryProfiler extends AbstractProfiler<QueryProfileBreakdown, Query> {
/**
* The root CollectorResult used in the search
*/
private CollectorResult collectorResult;
private long vectorOpsCount;
public QueryProfiler() {
super(new InternalQueryProfileTree());
}
public void setVectorOpsCount(long vectorOpsCount) {
this.vectorOpsCount = vectorOpsCount;
}
public long getVectorOpsCount() {
return this.vectorOpsCount;
}
/** Set the collector result that is associated with this profiler. */
public void setCollectorResult(CollectorResult collectorResult) {
if (this.collectorResult != null) {
throw new IllegalStateException("The collector result can only be set once.");
}
this.collectorResult = requireNonNull(collectorResult);
}
/**
* Begin timing the rewrite phase of a request. All rewrites are accumulated together into a
* single metric
*/
public Timer startRewriteTime() {
return ((InternalQueryProfileTree) profileTree).startRewriteTime();
}
/**
* Stop recording the current rewrite and add it's time to the total tally, returning the
* cumulative time so far.
*
* @return cumulative rewrite time
*/
public long stopAndAddRewriteTime(Timer rewriteTimer) {
return ((InternalQueryProfileTree) profileTree).stopAndAddRewriteTime(requireNonNull(rewriteTimer));
}
/**
* @return total time taken to rewrite all queries in this profile
*/
public long getRewriteTime() {
return ((InternalQueryProfileTree) profileTree).getRewriteTime();
}
/**
* Return the current root Collector for this search
*/
public CollectorResult getCollectorResult() {
return this.collectorResult;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/search/profile/query/QueryProfiler.java |
45,272 | /*
* Copyright (C) 2014 The Dagger Authors.
*
* 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 dagger.internal.codegen;
import androidx.room.compiler.processing.util.Source;
import com.google.common.collect.ImmutableList;
import dagger.testing.compile.CompilerTests;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class BindsInstanceValidationTest {
@Parameters(name = "{0}")
public static ImmutableList<Object[]> parameters() {
return CompilerMode.TEST_PARAMETERS;
}
private final CompilerMode compilerMode;
public BindsInstanceValidationTest(CompilerMode compilerMode) {
this.compilerMode = compilerMode;
}
@Test
public void bindsInstanceInModule() {
Source testModule =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
"import dagger.BindsInstance;",
"import dagger.Module;",
"",
"@Module",
"abstract class TestModule {",
" @BindsInstance abstract void str(String string);",
"}");
CompilerTests.daggerCompiler(testModule)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@BindsInstance methods should not be included in @Modules. Did you mean @Binds");
});
}
@Test
public void bindsInstanceInComponent() {
Source testComponent =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.BindsInstance;",
"import dagger.Component;",
"",
"@Component",
"interface TestComponent {",
" @BindsInstance String s(String s);",
"}");
CompilerTests.daggerCompiler(testComponent)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@BindsInstance methods should not be included in @Components. "
+ "Did you mean to put it in a @Component.Builder?");
});
}
@Test
public void bindsInstanceNotAbstract() {
Source notAbstract =
CompilerTests.javaSource(
"test.BindsInstanceNotAbstract",
"package test;",
"",
"import dagger.BindsInstance;",
"import dagger.Component;",
"",
"class BindsInstanceNotAbstract {",
" @BindsInstance BindsInstanceNotAbstract bind(int unused) { return this; }",
"}");
CompilerTests.daggerCompiler(notAbstract)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining("@BindsInstance methods must be abstract")
.onSource(notAbstract)
.onLine(7);
});
}
@Test
public void bindsInstanceNoParameters() {
Source notAbstract =
CompilerTests.javaSource(
"test.BindsInstanceNoParameters",
"package test;",
"",
"import dagger.BindsInstance;",
"",
"interface BindsInstanceNoParameters {",
" @BindsInstance void noParams();",
"}");
CompilerTests.daggerCompiler(notAbstract)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@BindsInstance methods should have exactly one parameter for the bound type")
.onSource(notAbstract)
.onLine(6);
});
}
@Test
public void bindsInstanceManyParameters() {
Source notAbstract =
CompilerTests.javaSource(
"test.BindsInstanceNoParameter",
"package test;",
"",
"import dagger.BindsInstance;",
"",
"interface BindsInstanceManyParameters {",
" @BindsInstance void manyParams(int i, long l);",
"}");
CompilerTests.daggerCompiler(notAbstract)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@BindsInstance methods should have exactly one parameter for the bound type")
.onSource(notAbstract)
.onLine(6);
});
}
@Test
public void bindsInstanceFrameworkType() {
Source bindsFrameworkType =
CompilerTests.javaSource(
"test.BindsInstanceFrameworkType",
"package test;",
"",
"import dagger.BindsInstance;",
"import dagger.producers.Producer;",
"import javax.inject.Provider;",
"",
"interface BindsInstanceFrameworkType {",
" @BindsInstance void bindsProvider(Provider<Object> objectProvider);",
" @BindsInstance void bindsProducer(Producer<Object> objectProducer);",
"}");
CompilerTests.daggerCompiler(bindsFrameworkType)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(2);
subject.hasErrorContaining("@BindsInstance parameters must not be framework types")
.onSource(bindsFrameworkType)
.onLine(8);
subject.hasErrorContaining("@BindsInstance parameters must not be framework types")
.onSource(bindsFrameworkType)
.onLine(9);
});
}
}
| google/dagger | javatests/dagger/internal/codegen/BindsInstanceValidationTest.java |
45,273 | /**
* Calculate
* R := B
* P mod M
* for large values of B, P, and M using an efficient algorithm. (That’s right, this problem has a time
* dependency !!!.)
* Input
* The input will contain several test cases, each of them as described below. Consecutive test cases are
* separated by a single blank line.
* Three integer values (in the order B, P, M) will be read one number per line. B and P are integers
* in the range 0 to 2147483647 inclusive. M is an integer in the range 1 to 46340 inclusive.
* Output
* For each test, the result of the computation. A single integer on a line by itself.
* Sample Input
* 3
* 18132
* 17
* 17
* 1765
* 3
* 2374859
* 3029382
* 36123
* Sample Output
* 13
* 2
* 13195
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=727&page=show_problem&problem=310
import java.math.BigInteger;
import java.util.Scanner;
public class BigMod {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
BigInteger b = input.nextBigInteger();
BigInteger p = input.nextBigInteger();
BigInteger m = input.nextBigInteger();
System.out.println(b.modPow(p, m));
}
}
}
| kdn251/interviews | uva/BigMod.java |
45,274 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.transition.TransitionManager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.utils.PhotoUtilities;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.Cells.CheckBoxCell;
import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Components.AlertsCreator;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.ImageUpdater;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RLottieDrawable;
import org.telegram.ui.Components.RadialProgressView;
import org.telegram.ui.LNavigation.NavigationExt;
import java.io.File;
import java.util.ArrayList;
public class ContactAddActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ImageUpdater.ImageUpdaterDelegate {
private View doneButton;
private EditTextBoldCursor firstNameField;
private EditTextBoldCursor lastNameField;
private BackupImageView avatarImage;
private TextView nameTextView;
private TextView onlineTextView;
private AvatarDrawable avatarDrawable;
private TextView infoTextView;
private CheckBoxCell checkBoxCell;
private Theme.ResourcesProvider resourcesProvider;
private RadialProgressView avatarProgressView;
private View avatarOverlay;
private AnimatorSet avatarAnimation;
private MessagesController.DialogPhotos dialogPhotos;
private long user_id;
private boolean addContact;
private boolean needAddException;
private String phone;
private String firstNameFromCard;
private String lastNameFromCard;
private ContactAddActivityDelegate delegate;
private final static int done_button = 1;
private ImageUpdater imageUpdater;
private TLRPC.FileLocation avatar;
TextCell oldPhotoCell;
private final static int TYPE_SUGGEST = 1;
private final static int TYPE_SET = 2;
private int photoSelectedType;
private int photoSelectedTypeFinal;
private TLRPC.Photo prevAvatar;
private BackupImageView oldAvatarView;
private LinearLayout linearLayout;
public interface ContactAddActivityDelegate {
void didAddToContacts();
}
public ContactAddActivity(Bundle args) {
super(args);
imageUpdater = new ImageUpdater(true, ImageUpdater.FOR_TYPE_USER, true);
}
public ContactAddActivity(Bundle args, Theme.ResourcesProvider resourcesProvider) {
super(args);
this.resourcesProvider = resourcesProvider;
imageUpdater = new ImageUpdater(true, ImageUpdater.FOR_TYPE_USER, true);
}
@Override
public Theme.ResourcesProvider getResourceProvider() {
return resourcesProvider;
}
@Override
public boolean onFragmentCreate() {
getNotificationCenter().addObserver(this, NotificationCenter.updateInterfaces);
getNotificationCenter().addObserver(this, NotificationCenter.dialogPhotosUpdate);
user_id = getArguments().getLong("user_id", 0);
phone = getArguments().getString("phone");
firstNameFromCard = getArguments().getString("first_name_card");
lastNameFromCard = getArguments().getString("last_name_card");
addContact = getArguments().getBoolean("addContact", false);
needAddException = MessagesController.getNotificationsSettings(currentAccount).getBoolean("dialog_bar_exception" + user_id, false);
TLRPC.User user = null;
if (user_id != 0) {
user = getMessagesController().getUser(user_id);
}
if (imageUpdater != null) {
imageUpdater.parentFragment = this;
imageUpdater.setDelegate(this);
}
dialogPhotos = MessagesController.getInstance(currentAccount).getDialogPhotos(user_id);
return user != null && super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
getNotificationCenter().removeObserver(this, NotificationCenter.updateInterfaces);
getNotificationCenter().removeObserver(this, NotificationCenter.dialogPhotosUpdate);
if (imageUpdater != null) {
imageUpdater.clear();
}
}
@Override
public View createView(Context context) {
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_avatar_actionBarSelectorBlue, resourcesProvider), false);
actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultIcon, resourcesProvider), false);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
if (addContact) {
actionBar.setTitle(LocaleController.getString("NewContact", R.string.NewContact));
} else {
actionBar.setTitle(LocaleController.getString("EditContact", R.string.EditContact));
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == done_button) {
if (firstNameField.getText().length() != 0) {
TLRPC.User user = getMessagesController().getUser(user_id);
user.first_name = firstNameField.getText().toString();
user.last_name = lastNameField.getText().toString();
user.contact = true;
getMessagesController().putUser(user, false);
getContactsController().addContact(user, checkBoxCell != null && checkBoxCell.isChecked());
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
preferences.edit().putInt("dialog_bar_vis3" + user_id, 3).commit();
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME);
getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, user_id);
finishFragment();
if (delegate != null) {
delegate.didAddToContacts();
}
}
}
}
});
ActionBarMenu menu = actionBar.createMenu();
doneButton = menu.addItem(done_button, LocaleController.getString("Done", R.string.Done).toUpperCase());
fragmentView = new ScrollView(context);
fragmentView.setBackgroundColor(getThemedColor(Theme.key_windowBackgroundWhite));
linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
((ScrollView) fragmentView).addView(linearLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT));
linearLayout.setOnTouchListener((v, event) -> true);
FrameLayout frameLayout = new FrameLayout(context);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 24, 24, 0));
avatarImage = new BackupImageView(context);
avatarImage.setRoundRadius(AndroidUtilities.dp(30));
frameLayout.addView(avatarImage, LayoutHelper.createFrame(60, 60, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP));
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0x55000000);
avatarOverlay = new View(context) {
@Override
protected void onDraw(Canvas canvas) {
if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
canvas.drawCircle(getMeasuredWidth() / 2.0f, getMeasuredHeight() / 2.0f, getMeasuredWidth() / 2.0f, paint);
}
}
};
frameLayout.addView(avatarOverlay, LayoutHelper.createFrame(60, 60, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP));
avatarProgressView = new RadialProgressView(context);
avatarProgressView.setSize(AndroidUtilities.dp(30));
avatarProgressView.setProgressColor(0xffffffff);
avatarProgressView.setNoProgress(false);
frameLayout.addView(avatarProgressView, LayoutHelper.createFrame(60, 60, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP));
showAvatarProgress(false, false);
nameTextView = new TextView(context);
nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
nameTextView.setLines(1);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT));
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 80, 3, LocaleController.isRTL ? 80 : 0, 0));
onlineTextView = new TextView(context);
onlineTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3, resourcesProvider));
onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
onlineTextView.setLines(1);
onlineTextView.setMaxLines(1);
onlineTextView.setSingleLine(true);
onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT));
frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 80, 32, LocaleController.isRTL ? 80 : 0, 0));
firstNameField = new EditTextBoldCursor(context) {
@Override
protected Theme.ResourcesProvider getResourcesProvider() {
return resourcesProvider;
}
};
firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
firstNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText, resourcesProvider));
firstNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
firstNameField.setBackgroundDrawable(null);
firstNameField.setLineColors(getThemedColor(Theme.key_windowBackgroundWhiteInputField), getThemedColor(Theme.key_windowBackgroundWhiteInputFieldActivated), getThemedColor(Theme.key_text_RedRegular));
firstNameField.setMaxLines(1);
firstNameField.setLines(1);
firstNameField.setSingleLine(true);
firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName));
firstNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
firstNameField.setCursorSize(AndroidUtilities.dp(20));
firstNameField.setCursorWidth(1.5f);
linearLayout.addView(firstNameField, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 24, 24, 24, 0));
firstNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_NEXT) {
lastNameField.requestFocus();
lastNameField.setSelection(lastNameField.length());
return true;
}
return false;
});
firstNameField.setOnFocusChangeListener(new View.OnFocusChangeListener() {
boolean focused;
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!paused && !hasFocus && focused) {
FileLog.d("changed");
}
focused = hasFocus;
}
});
firstNameField.setText(firstNameFromCard);
lastNameField = new EditTextBoldCursor(context) {
@Override
protected Theme.ResourcesProvider getResourcesProvider() {
return resourcesProvider;
}
};
lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
lastNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText, resourcesProvider));
lastNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
lastNameField.setBackgroundDrawable(null);
lastNameField.setLineColors(getThemedColor(Theme.key_windowBackgroundWhiteInputField), getThemedColor(Theme.key_windowBackgroundWhiteInputFieldActivated), getThemedColor(Theme.key_text_RedRegular));
lastNameField.setMaxLines(1);
lastNameField.setLines(1);
lastNameField.setSingleLine(true);
lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE);
lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName));
lastNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
lastNameField.setCursorSize(AndroidUtilities.dp(20));
lastNameField.setCursorWidth(1.5f);
linearLayout.addView(lastNameField, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 24, 16, 24, 0));
lastNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_DONE) {
doneButton.performClick();
return true;
}
return false;
});
lastNameField.setText(lastNameFromCard);
TLRPC.User user = getMessagesController().getUser(user_id);
if (user != null && firstNameFromCard == null && lastNameFromCard == null) {
if (user.phone == null) {
if (phone != null) {
user.phone = PhoneFormat.stripExceptNumbers(phone);
}
}
firstNameField.setText(user.first_name);
firstNameField.setSelection(firstNameField.length());
lastNameField.setText(user.last_name);
}
infoTextView = new TextView(context);
infoTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
infoTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
if (addContact) {
if (!needAddException || TextUtils.isEmpty(getPhone())) {
linearLayout.addView(infoTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 18, 24, 0));
}
if (needAddException) {
checkBoxCell = new CheckBoxCell(getParentActivity(), 0);
checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
CharSequence firstName = UserObject.getFirstName(user);
firstName = Emoji.replaceEmoji(firstName, infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(12), false);
checkBoxCell.setText(AndroidUtilities.replaceCharSequence("%1$s", AndroidUtilities.replaceTags(LocaleController.getString("SharePhoneNumberWith", R.string.SharePhoneNumberWith)), firstName), "", true, false);
checkBoxCell.setPadding(AndroidUtilities.dp(7), 0, AndroidUtilities.dp(7), 0);
checkBoxCell.setOnClickListener(v -> checkBoxCell.setChecked(!checkBoxCell.isChecked(), true));
linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 10, 0, 0));
}
} else {
TextCell suggestPhoto = new TextCell(context, resourcesProvider);
suggestPhoto.setTextAndIcon(LocaleController.formatString("SuggestUserPhoto", R.string.SuggestUserPhoto, user.first_name), R.drawable.msg_addphoto, true);
suggestPhoto.setBackgroundDrawable(Theme.getSelectorDrawable(false));
suggestPhoto.setColors(Theme.key_windowBackgroundWhiteBlueIcon, Theme.key_windowBackgroundWhiteBlueButton);
RLottieDrawable suggestDrawable = new RLottieDrawable(R.raw.photo_suggest_icon, "" + R.raw.photo_suggest_icon, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null);
suggestPhoto.imageView.setTranslationX(-AndroidUtilities.dp(8));
suggestPhoto.imageView.setAnimation(suggestDrawable);
suggestPhoto.setOnClickListener(v -> {
photoSelectedType = TYPE_SUGGEST;
imageUpdater.setUser(user);
TLRPC.FileLocation avatar = (user == null || user.photo == null) ? null : user.photo.photo_small;
imageUpdater.openMenu(avatar != null, () -> {
}, dialogInterface -> {
if (!imageUpdater.isUploadingImage()) {
suggestDrawable.setCustomEndFrame(85);
suggestPhoto.imageView.playAnimation();
} else {
suggestDrawable.setCurrentFrame(0, false);
}
}, ImageUpdater.TYPE_SUGGEST_PHOTO_FOR_USER);
suggestDrawable.setCurrentFrame(0);
suggestDrawable.setCustomEndFrame(43);
suggestPhoto.imageView.playAnimation();
});
linearLayout.addView(suggestPhoto, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 18, 0, 0));
TextCell setAvatarCell = new TextCell(context, resourcesProvider);
setAvatarCell.setTextAndIcon(LocaleController.formatString("UserSetPhoto", R.string.UserSetPhoto, user.first_name), R.drawable.msg_addphoto, false);
setAvatarCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
setAvatarCell.setColors(Theme.key_windowBackgroundWhiteBlueIcon, Theme.key_windowBackgroundWhiteBlueButton);
RLottieDrawable cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(50), AndroidUtilities.dp(50), false, null);
setAvatarCell.imageView.setTranslationX(-AndroidUtilities.dp(8));
setAvatarCell.imageView.setAnimation(cameraDrawable);
setAvatarCell.setOnClickListener(v -> {
photoSelectedType = TYPE_SET;
imageUpdater.setUser(user);
TLRPC.FileLocation avatar = (user == null || user.photo == null) ? null : user.photo.photo_small;
imageUpdater.openMenu(avatar != null, () -> {
}, dialogInterface -> {
if (!imageUpdater.isUploadingImage()) {
cameraDrawable.setCustomEndFrame(86);
setAvatarCell.imageView.playAnimation();
} else {
cameraDrawable.setCurrentFrame(0, false);
}
}, ImageUpdater.TYPE_SET_PHOTO_FOR_USER);
cameraDrawable.setCurrentFrame(0);
cameraDrawable.setCustomEndFrame(43);
setAvatarCell.imageView.playAnimation();
});
linearLayout.addView(setAvatarCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0, 0));
oldAvatarView = new BackupImageView(context);
oldPhotoCell = new TextCell(context, resourcesProvider) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
oldAvatarView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(30), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(30), MeasureSpec.EXACTLY));
oldAvatarView.setRoundRadius(AndroidUtilities.dp(30));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int l = AndroidUtilities.dp(21);
int t = (getMeasuredHeight() - oldAvatarView.getMeasuredHeight()) / 2;
oldAvatarView.layout(l, t, l + oldAvatarView.getMeasuredWidth(), t + oldAvatarView.getMeasuredHeight());
}
};
if (avatarDrawable == null) {
avatarDrawable = new AvatarDrawable(user);
}
oldAvatarView.setForUserOrChat(user.photo, avatarDrawable);
oldPhotoCell.addView(oldAvatarView, LayoutHelper.createFrame(30, 30, Gravity.CENTER_VERTICAL, 21, 0, 21, 0));
oldPhotoCell.setText(LocaleController.getString("ResetToOriginalPhoto", R.string.ResetToOriginalPhoto), false);
oldPhotoCell.getImageView().setVisibility(View.VISIBLE);
oldPhotoCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
oldPhotoCell.setColors(Theme.key_windowBackgroundWhiteBlueIcon, Theme.key_windowBackgroundWhiteBlueButton);
oldPhotoCell.setOnClickListener(v -> {
AlertsCreator.createSimpleAlert(context,
LocaleController.getString("ResetToOriginalPhotoTitle", R.string.ResetToOriginalPhotoTitle),
LocaleController.formatString("ResetToOriginalPhotoMessage", R.string.ResetToOriginalPhotoMessage, user.first_name),
LocaleController.getString("Reset", R.string.Reset), () -> {
avatar = null;
sendPhotoChangedRequest(null, null,null, null, null, 0, TYPE_SET);
TLRPC.User user1 = getMessagesController().getUser(user_id);
user1.photo.personal = false;
TLRPC.UserFull fullUser = MessagesController.getInstance(currentAccount).getUserFull(user_id);
if (fullUser != null) {
fullUser.personal_photo = null;
fullUser.flags &= ~2097152;
getMessagesStorage().updateUserInfo(fullUser, true);
}
if (prevAvatar != null) {
user1.photo.photo_id = prevAvatar.id;
ArrayList<TLRPC.PhotoSize> sizes = prevAvatar.sizes;
TLRPC.PhotoSize smallSize2 = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize2 = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
if (smallSize2 != null) {
user1.photo.photo_small = smallSize2.location;
}
if (bigSize2 != null) {
user1.photo.photo_big = bigSize2.location;
}
} else {
user1.photo = null;
user1.flags &= ~32;
}
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
getMessagesStorage().putUsersAndChats(users, null, false, true);
updateCustomPhotoInfo();
getNotificationCenter().postNotificationName(NotificationCenter.reloadDialogPhotos);
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_AVATAR);
}, resourcesProvider).show();
});
linearLayout.addView(oldPhotoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0, 0));
// getMessagesController().loadDialogPhotos(user_id, 2, 0, true, getClassGuid(), null);
TLRPC.UserFull userFull = getMessagesController().getUserFull(user_id);
if (userFull != null) {
prevAvatar = userFull.profile_photo;
if (prevAvatar == null) {
prevAvatar = userFull.fallback_photo;
}
}
updateCustomPhotoInfo();
}
return fragmentView;
}
private void showAvatarProgress(boolean show, boolean animated) {
if (avatarProgressView == null) {
return;
}
if (avatarAnimation != null) {
avatarAnimation.cancel();
avatarAnimation = null;
}
if (animated) {
avatarAnimation = new AnimatorSet();
if (show) {
avatarProgressView.setVisibility(View.VISIBLE);
avatarOverlay.setVisibility(View.VISIBLE);
avatarAnimation.playTogether(ObjectAnimator.ofFloat(avatarProgressView, View.ALPHA, 1.0f),
ObjectAnimator.ofFloat(avatarOverlay, View.ALPHA, 1.0f));
} else {
avatarAnimation.playTogether(ObjectAnimator.ofFloat(avatarProgressView, View.ALPHA, 0.0f),
ObjectAnimator.ofFloat(avatarOverlay, View.ALPHA, 0.0f));
}
avatarAnimation.setDuration(180);
avatarAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (avatarAnimation == null || avatarProgressView == null) {
return;
}
if (!show) {
avatarProgressView.setVisibility(View.INVISIBLE);
avatarOverlay.setVisibility(View.INVISIBLE);
}
avatarAnimation = null;
}
@Override
public void onAnimationCancel(Animator animation) {
avatarAnimation = null;
}
});
avatarAnimation.start();
} else {
if (show) {
avatarProgressView.setAlpha(1.0f);
avatarProgressView.setVisibility(View.VISIBLE);
avatarOverlay.setAlpha(1.0f);
avatarOverlay.setVisibility(View.VISIBLE);
} else {
avatarProgressView.setAlpha(0.0f);
avatarProgressView.setVisibility(View.INVISIBLE);
avatarOverlay.setAlpha(0.0f);
avatarOverlay.setVisibility(View.INVISIBLE);
}
}
}
public void setDelegate(ContactAddActivityDelegate contactAddActivityDelegate) {
delegate = contactAddActivityDelegate;
}
private void updateAvatarLayout() {
if (nameTextView == null) {
return;
}
TLRPC.User user = getMessagesController().getUser(user_id);
if (user == null) {
return;
}
if (TextUtils.isEmpty(getPhone())) {
nameTextView.setText(LocaleController.getString("MobileHidden", R.string.MobileHidden));
CharSequence firstName = UserObject.getFirstName(user);
firstName = Emoji.replaceEmoji(firstName, infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(12), false);
infoTextView.setText(AndroidUtilities.replaceCharSequence("%1$s", AndroidUtilities.replaceTags(LocaleController.getString("MobileHiddenExceptionInfo", R.string.MobileHiddenExceptionInfo)), firstName));
} else {
nameTextView.setText(PhoneFormat.getInstance().format("+" + getPhone()));
if (needAddException) {
infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("MobileVisibleInfo", R.string.MobileVisibleInfo, UserObject.getFirstName(user))));
}
}
onlineTextView.setText(LocaleController.formatUserStatus(currentAccount, user));
if (avatar == null) {
avatarImage.setForUserOrChat(user, avatarDrawable = new AvatarDrawable(user));
}
}
private String getPhone() {
TLRPC.User user = getMessagesController().getUser(user_id);
return user != null && !TextUtils.isEmpty(user.phone) ? user.phone : phone;
}
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.updateInterfaces) {
int mask = (Integer) args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
updateAvatarLayout();
}
} else if (id == NotificationCenter.dialogPhotosUpdate) {
MessagesController.DialogPhotos dialogPhotos = (MessagesController.DialogPhotos) args[0];
if (dialogPhotos == this.dialogPhotos) {
ArrayList<TLRPC.Photo> photos = new ArrayList<>(dialogPhotos.photos);
for (int i = 0; i < photos.size(); i++) {
if (photos.get(i) == null) {
photos.remove(i);
i--;
}
}
for (int i = 0; i < photos.size(); ++i) {
prevAvatar = photos.get(i);
updateCustomPhotoInfo();
break;
}
}
}
}
private void updateCustomPhotoInfo() {
if (addContact) {
return;
}
TLRPC.User user = getMessagesController().getUser(user_id);
if (fragmentBeginToShow) {
TransitionManager.beginDelayedTransition(linearLayout);
}
if (user.photo != null && user.photo.personal) {
oldPhotoCell.setVisibility(View.VISIBLE);
if (prevAvatar != null) {
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(prevAvatar.sizes, 1000);
ImageLocation location = ImageLocation.getForPhoto(photoSize, prevAvatar);
oldAvatarView.setImage(location, "50_50", avatarDrawable, null);
}
} else {
oldPhotoCell.setVisibility(View.GONE);
}
if (avatarDrawable == null) {
avatarDrawable = new AvatarDrawable(user);
}
if (avatar == null) {
avatarImage.setForUserOrChat(user, avatarDrawable);
} else {
avatarImage.setImage(ImageLocation.getForLocal(avatar), "50_50", avatarDrawable, getMessagesController().getUser(user_id));
}
}
boolean paused;
@Override
public void onPause() {
super.onPause();
paused = true;
imageUpdater.onPause();
}
@Override
public void onResume() {
super.onResume();
updateAvatarLayout();
imageUpdater.onResume();
}
MessageObject suggestPhotoMessageFinal;
@Override
public boolean canFinishFragment() {
return photoSelectedTypeFinal != TYPE_SUGGEST;
}
@Override
public void didUploadPhoto(TLRPC.InputFile photo, TLRPC.InputFile video, double videoStartTimestamp, String videoPath, TLRPC.PhotoSize bigSize, TLRPC.PhotoSize smallSize, boolean isVideo, TLRPC.VideoSize emojiMarkup) {
AndroidUtilities.runOnUIThread(() -> {
if (imageUpdater.isCanceled()) {
return;
}
if (photoSelectedTypeFinal == TYPE_SET) {
avatar = smallSize.location;
} else {
if (photoSelectedTypeFinal == TYPE_SUGGEST) {
NavigationExt.backToFragment(ContactAddActivity.this, fragment -> {
if (fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
if (chatActivity.getDialogId() == user_id && chatActivity.getChatMode() == 0) {
chatActivity.scrollToLastMessage(true, false);
return true;
}
}
return false;
});
}
}
if (photo != null || video != null) {
TLRPC.User user = getMessagesController().getUser(user_id);
if (suggestPhotoMessageFinal == null && user != null) {
PhotoUtilities.applyPhotoToUser(smallSize, bigSize, video != null, user, true);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
getMessagesStorage().putUsersAndChats(users, null, false, true);
getNotificationCenter().postNotificationName(NotificationCenter.reloadDialogPhotos);
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_AVATAR);
}
sendPhotoChangedRequest(avatar, bigSize.location, photo, video, emojiMarkup, videoStartTimestamp, photoSelectedTypeFinal);
showAvatarProgress(false, true);
} else {
avatarImage.setImage(ImageLocation.getForLocal(avatar), "50_50", avatarDrawable, getMessagesController().getUser(user_id));
if (photoSelectedTypeFinal == TYPE_SET) {
showAvatarProgress(true, false);
} else {
createServiceMessageLocal(smallSize, bigSize, isVideo);
}
}
updateCustomPhotoInfo();
});
}
@Override
public void didUploadFailed() {
AndroidUtilities.runOnUIThread(() -> {
ImageUpdater.ImageUpdaterDelegate.super.didUploadFailed();
if (suggestPhotoMessageFinal != null) {
ArrayList<Integer> ids = new ArrayList<>();
ids.add(suggestPhotoMessageFinal.getId());
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.messagesDeleted, ids, 0L, false);
}
});
}
private void createServiceMessageLocal(TLRPC.PhotoSize smallSize, TLRPC.PhotoSize bigSize, boolean video) {
TLRPC.TL_messageService message = new TLRPC.TL_messageService();
message.random_id = SendMessagesHelper.getInstance(currentAccount).getNextRandomId();
message.dialog_id = user_id;
message.unread = true;
message.out = true;
message.local_id = message.id = getUserConfig().getNewMessageId();
message.from_id = new TLRPC.TL_peerUser();
message.from_id.user_id = getUserConfig().getClientUserId();
message.flags |= 256;
message.peer_id = new TLRPC.TL_peerUser();
message.peer_id.user_id = user_id;
message.date = getConnectionsManager().getCurrentTime();
TLRPC.TL_messageActionSuggestProfilePhoto suggestProfilePhoto = new TLRPC.TL_messageActionSuggestProfilePhoto();
message.action = suggestProfilePhoto;
suggestProfilePhoto.photo = new TLRPC.TL_photo();
suggestProfilePhoto.photo.sizes.add(smallSize);
suggestProfilePhoto.photo.sizes.add(bigSize);
suggestProfilePhoto.video = video;
suggestProfilePhoto.photo.file_reference = new byte[0];
ArrayList<MessageObject> objArr = new ArrayList<>();
objArr.add(suggestPhotoMessageFinal = new MessageObject(currentAccount, message, false, false));
ArrayList<TLRPC.Message> arr = new ArrayList<>();
arr.add(message);
// MessagesStorage.getInstance(currentAccount).putMessages(arr, false, true, false, 0, false, 0);
MessagesController.getInstance(currentAccount).updateInterfaceWithMessages(user_id, objArr, 0);
getMessagesController().photoSuggestion.put(message.local_id, imageUpdater);
}
private void sendPhotoChangedRequest(TLRPC.FileLocation avatar, TLRPC.FileLocation bigAvatar, TLRPC.InputFile photo, TLRPC.InputFile video, TLRPC.VideoSize emojiMarkup, double videoStartTimestamp, int photoSelectedTypeFinal) {
TLRPC.TL_photos_uploadContactProfilePhoto req = new TLRPC.TL_photos_uploadContactProfilePhoto();
req.user_id = getMessagesController().getInputUser(user_id);
if (photo != null) {
req.file = photo;
req.flags |= 1;
}
if (video != null) {
req.video = video;
req.flags |= 2;
req.video_start_ts = videoStartTimestamp;
req.flags |= 4;
}
if (emojiMarkup != null) {
req.flags |= 32;
req.video_emoji_markup = emojiMarkup;
}
if (photoSelectedTypeFinal == TYPE_SUGGEST) {
req.suggest = true;
req.flags |= 8;
} else {
req.save = true;
req.flags |= 16;
}
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (suggestPhotoMessageFinal != null) {
return;
}
if (avatar == null && video == null) {
return;
}
if (response != null) {
TLRPC.TL_photos_photo photo2 = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo2.photo.sizes;
TLRPC.User user = getMessagesController().getUser(user_id);
TLRPC.UserFull fullUser = MessagesController.getInstance(currentAccount).getUserFull(user_id);
if (fullUser != null) {
fullUser.personal_photo = photo2.photo;
fullUser.flags |= 2097152;
getMessagesStorage().updateUserInfo(fullUser, true);
}
if (user != null) {
TLRPC.PhotoSize smallSize2 = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize2 = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
if (smallSize2 != null && avatar != null) {
File destFile = FileLoader.getInstance(currentAccount).getPathToAttach(smallSize2, true);
File src = FileLoader.getInstance(currentAccount).getPathToAttach(avatar, true);
src.renameTo(destFile);
String oldKey = avatar.volume_id + "_" + avatar.local_id + "@50_50";
String newKey = smallSize2.location.volume_id + "_" + smallSize2.location.local_id + "@50_50";
ImageLoader.getInstance().replaceImageInCache(oldKey, newKey, ImageLocation.getForUser(user, ImageLocation.TYPE_SMALL), false);
}
if (bigSize2 != null && bigAvatar != null) {
File destFile = FileLoader.getInstance(currentAccount).getPathToAttach(bigSize2, true);
File src = FileLoader.getInstance(currentAccount).getPathToAttach(bigAvatar, true);
src.renameTo(destFile);
}
PhotoUtilities.applyPhotoToUser(photo2.photo, user, true);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
getMessagesStorage().putUsersAndChats(users, null, false, true);
getMessagesController().getDialogPhotos(user_id).addPhotoAtStart(photo2.photo);
getNotificationCenter().postNotificationName(NotificationCenter.reloadDialogPhotos);
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_AVATAR);
if (getParentActivity() != null) {
if (photoSelectedTypeFinal == TYPE_SET) {
BulletinFactory.of(this).createUsersBulletin(users, AndroidUtilities.replaceTags(LocaleController.formatString("UserCustomPhotoSeted", R.string.UserCustomPhotoSeted, user.first_name))).show();
} else {
BulletinFactory.of(this).createUsersBulletin(users, AndroidUtilities.replaceTags(LocaleController.formatString("UserCustomPhotoSeted", R.string.UserCustomPhotoSeted, user.first_name))).show();
}
}
}
this.avatar = null;
updateCustomPhotoInfo();
}
}));
}
@Override
public String getInitialSearchString() {
return ImageUpdater.ImageUpdaterDelegate.super.getInitialSearchString();
}
@Override
public void onUploadProgressChanged(float progress) {
if (avatarProgressView == null) {
return;
}
avatarProgressView.setProgress(progress);
}
@Override
public void didStartUpload(boolean isVideo) {
if (avatarProgressView == null) {
return;
}
photoSelectedTypeFinal = photoSelectedType;
avatarProgressView.setProgress(0.0f);
}
@Override
public ArrayList<ThemeDescription> getThemeDescriptions() {
ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>();
ThemeDescription.ThemeDescriptionDelegate cellDelegate = () -> {
if (avatarImage != null) {
TLRPC.User user = getMessagesController().getUser(user_id);
if (user == null) {
return;
}
avatarDrawable.setInfo(currentAccount, user);
avatarImage.invalidate();
}
};
themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundWhite));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector));
themeDescriptions.add(new ThemeDescription(nameTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(onlineTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText3));
themeDescriptions.add(new ThemeDescription(firstNameField, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(firstNameField, ThemeDescription.FLAG_HINTTEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteHintText));
themeDescriptions.add(new ThemeDescription(firstNameField, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_windowBackgroundWhiteInputField));
themeDescriptions.add(new ThemeDescription(firstNameField, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_windowBackgroundWhiteInputFieldActivated));
themeDescriptions.add(new ThemeDescription(lastNameField, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(lastNameField, ThemeDescription.FLAG_HINTTEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteHintText));
themeDescriptions.add(new ThemeDescription(lastNameField, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_windowBackgroundWhiteInputField));
themeDescriptions.add(new ThemeDescription(lastNameField, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_windowBackgroundWhiteInputFieldActivated));
themeDescriptions.add(new ThemeDescription(infoTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText4));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, Theme.avatarDrawables, cellDelegate, Theme.key_avatar_text));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundRed));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundOrange));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundViolet));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundGreen));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundCyan));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundBlue));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundPink));
return themeDescriptions;
}
public static class PhotoSuggestion {
TLRPC.FileLocation smallLocation;
TLRPC.FileLocation bigLocation;
public PhotoSuggestion(TLRPC.FileLocation smallLocation, TLRPC.FileLocation bigLocation) {
this.smallLocation = smallLocation;
this.bigLocation = bigLocation;
}
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java |
45,275 | /**
* Copyright (c) 2006-2019, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.IOException;
@SuppressWarnings("serial")
abstract public class GitHubAuth extends AbsAuth
{
public static String CLIENT_SECRET_FILE_PATH = "github_client_secret";
public static String CLIENT_ID_FILE_PATH = "github_client_id";
public static String AUTH_SERVICE_URL_FILE_PATH = "github_auth_url";
private static Config CONFIG = null;
protected Config getConfig()
{
if (CONFIG == null)
{
String clientSerets = SecretFacade.getSecret(CLIENT_SECRET_FILE_PATH, getServletContext()),
clientIds = SecretFacade.getSecret(CLIENT_ID_FILE_PATH, getServletContext());
CONFIG = new Config(clientIds, clientSerets);
try
{
CONFIG.AUTH_SERVICE_URL = SecretFacade.getSecret(AUTH_SERVICE_URL_FILE_PATH, getServletContext());
}
catch (Exception e)
{
CONFIG.AUTH_SERVICE_URL = "https://github.com/login/oauth/access_token";
}
CONFIG.REDIRECT_PATH = "/github2";
}
return CONFIG;
}
public GitHubAuth()
{
super();
cookiePath = "/github2";
withRedirectUrl = false;
withAcceptJsonHeader = true;
}
protected String processAuthResponse(String authRes, boolean jsonResponse)
{
StringBuffer res = new StringBuffer();
if (!jsonResponse)
{
res.append("<!DOCTYPE html><html><head><script type=\"text/javascript\">");
res.append("(function() { var authInfo = "); //The following is a json containing access_token
}
res.append(authRes);
if (!jsonResponse)
{
res.append(";");
res.append("if (window.opener != null && window.opener.onGitHubCallback != null)");
res.append("{");
res.append(" window.opener.onGitHubCallback(authInfo, window);");
res.append("} else {");
res.append(" onGitHubCallback(authInfo);");
res.append("}");
res.append("})();</script>");
res.append("</head><body></body></html>");
}
return res.toString();
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/GitHubAuth.java |
45,276 | /**
* Copyright (c) 2006-2019, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.IOException;
@SuppressWarnings("serial")
abstract public class DropboxAuth extends AbsAuth
{
public static String CLIENT_SECRET_FILE_PATH = "dropbox_client_secret";
public static String CLIENT_ID_FILE_PATH = "dropbox_client_id";
private static Config CONFIG = null;
protected Config getConfig()
{
if (CONFIG == null)
{
String clientSerets = SecretFacade.getSecret(CLIENT_SECRET_FILE_PATH, getServletContext()),
clientIds = SecretFacade.getSecret(CLIENT_ID_FILE_PATH, getServletContext());
CONFIG = new Config(clientIds, clientSerets);
CONFIG.AUTH_SERVICE_URL = "https://api.dropboxapi.com/oauth2/token";
CONFIG.REDIRECT_PATH = "/dropbox";
}
return CONFIG;
}
public DropboxAuth()
{
super();
cookiePath = "/dropbox";
withRedirectUrlInRefresh = false;
}
protected String processAuthResponse(String authRes, boolean jsonResponse)
{
StringBuffer res = new StringBuffer();
if (!jsonResponse)
{
res.append("<!DOCTYPE html><html><head><script type=\"text/javascript\">");
res.append("(function() { var authInfo = "); //The following is a json containing access_token
}
res.append(authRes);
if (!jsonResponse)
{
res.append(";");
res.append("if (window.opener != null && window.opener.onDropboxCallback != null)");
res.append("{");
res.append(" window.opener.onDropboxCallback(authInfo, window);");
res.append("} else {");
res.append(" onDropboxCallback(authInfo);");
res.append("}");
res.append("})();</script>");
res.append("</head><body></body></html>");
}
return res.toString();
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/DropboxAuth.java |
45,277 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Components;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.collection.LongSparseArray;
import androidx.core.view.ViewCompat;
import androidx.dynamicanimation.animation.FloatValueHolder;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.telegram.SQLite.SQLiteCursor;
import org.telegram.messenger.AccountInstance;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.BotWebViewVibrationEffect;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.GenericProvider;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_stories;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenuSubItem;
import org.telegram.ui.ActionBar.ActionBarPopupWindow;
import org.telegram.ui.ActionBar.AdjustPanLayoutHelper;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.BottomSheet;
import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Adapters.DialogsSearchAdapter;
import org.telegram.ui.Adapters.SearchAdapterHelper;
import org.telegram.ui.Cells.GraySectionCell;
import org.telegram.ui.Cells.HintDialogCell;
import org.telegram.ui.Cells.ProfileSearchCell;
import org.telegram.ui.Cells.ShareDialogCell;
import org.telegram.ui.Cells.ShareTopicCell;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.MessageStatisticActivity;
import org.telegram.ui.PremiumPreviewFragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class ShareAlert extends BottomSheet implements NotificationCenter.NotificationCenterDelegate {
private FrameLayout frameLayout;
private FrameLayout frameLayout2;
private EditTextEmoji commentTextView;
private FrameLayout writeButtonContainer;
private View selectedCountView;
private TextView pickerBottomLayout;
private FrameLayout bulletinContainer;
public FrameLayout bulletinContainer2;
private LinearLayout sharesCountLayout;
private AnimatorSet animatorSet;
private RecyclerListView topicsGridView;
private RecyclerListView gridView;
private RecyclerListView searchGridView;
private GridLayoutManager layoutManager;
private GridLayoutManager topicsLayoutManager;
private FillLastGridLayoutManager searchLayoutManager;
private ShareDialogsAdapter listAdapter;
private ShareTopicsAdapter shareTopicsAdapter;
private ShareSearchAdapter searchAdapter;
protected ArrayList<MessageObject> sendingMessageObjects;
private String[] sendingText = new String[2];
private int hasPoll;
private StickerEmptyView searchEmptyView;
private Drawable shadowDrawable;
private View[] shadow = new View[2];
private AnimatorSet[] shadowAnimation = new AnimatorSet[2];
protected LongSparseArray<TLRPC.Dialog> selectedDialogs = new LongSparseArray<>();
protected Map<TLRPC.Dialog, TLRPC.TL_forumTopic> selectedDialogTopics = new HashMap<>();
private SwitchView switchView;
private int containerViewTop = -1;
private boolean fullyShown = false;
private boolean includeStory;
public boolean includeStoryFromMessage;
private ChatActivity parentFragment;
private Activity parentActivity;
private boolean darkTheme;
public boolean forceDarkThemeForHint;
private RectF rect = new RectF();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
private TLRPC.TL_exportedMessageLink exportedMessageLink;
private boolean loadingLink;
private boolean copyLinkOnEnd;
private boolean isChannel;
private String[] linkToCopy = new String[2];
private int scrollOffsetY;
private int previousScrollOffsetY;
private int topBeforeSwitch;
private boolean panTranslationMoveLayout;
private ShareAlertDelegate delegate;
private float currentPanTranslationY;
private float captionEditTextTopOffset;
private float chatActivityEnterViewAnimateFromTop;
private ValueAnimator topBackgroundAnimator;
RecyclerItemsEnterAnimator recyclerItemsEnterAnimator;
SearchField searchView;
ActionBar topicsBackActionBar;
private boolean updateSearchAdapter;
private SpringAnimation topicsAnimation;
private TLRPC.Dialog selectedTopicDialog;
private SizeNotifierFrameLayout sizeNotifierFrameLayout;
private ArrayList<DialogsSearchAdapter.RecentSearchObject> recentSearchObjects = new ArrayList<>();
private LongSparseArray<DialogsSearchAdapter.RecentSearchObject> recentSearchObjectsById = new LongSparseArray<>();
private final Theme.ResourcesProvider resourcesProvider;
TL_stories.StoryItem storyItem;
public void setStoryToShare(TL_stories.StoryItem storyItem) {
this.storyItem = storyItem;
}
public interface ShareAlertDelegate {
default void didShare() {
}
default boolean didCopy() {
return false;
}
}
@SuppressWarnings("FieldCanBeLocal")
private class SwitchView extends FrameLayout {
private View searchBackground;
private SimpleTextView rightTab;
private SimpleTextView leftTab;
private View slidingView;
private int currentTab;
private float tabSwitchProgress;
private AnimatorSet animator;
private LinearGradient linearGradient;
private Paint paint;
private RectF rect;
private int lastColor;
public SwitchView(Context context) {
super(context);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
rect = new RectF();
searchBackground = new View(context);
searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(dp(18), getThemedColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground)));
addView(searchBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 0, 14, 0));
slidingView = new View(context) {
@Override
public void setTranslationX(float translationX) {
super.setTranslationX(translationX);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int color01 = 0xff75CB6B;
int color02 = 0xff4FAFBE;
int color11 = 0xff5F94F5;
int color12 = 0xffB95A91;
int color0 = AndroidUtilities.getOffsetColor(color01, color11, getTranslationX() / getMeasuredWidth(), 1.0f);
int color1 = AndroidUtilities.getOffsetColor(color02, color12, getTranslationX() / getMeasuredWidth(), 1.0f);
if (color0 != lastColor) {
linearGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, new int[]{color0, color1}, null, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRoundRect(rect, dp(18), dp(18), paint);
}
};
addView(slidingView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 0, 14, 0));
leftTab = new SimpleTextView(context);
leftTab.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
leftTab.setTextSize(13);
leftTab.setLeftDrawable(R.drawable.msg_tabs_mic1);
leftTab.setText(LocaleController.getString("VoipGroupInviteCanSpeak", R.string.VoipGroupInviteCanSpeak));
leftTab.setGravity(Gravity.CENTER);
addView(leftTab, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 14, 0, 0, 0));
leftTab.setOnClickListener(v -> switchToTab(0));
rightTab = new SimpleTextView(context);
rightTab.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
rightTab.setTextSize(13);
rightTab.setLeftDrawable(R.drawable.msg_tabs_mic2);
rightTab.setText(LocaleController.getString("VoipGroupInviteListenOnly", R.string.VoipGroupInviteListenOnly));
rightTab.setGravity(Gravity.CENTER);
addView(rightTab, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 14, 0));
rightTab.setOnClickListener(v -> switchToTab(1));
}
protected void onTabSwitch(int num) {
}
private void switchToTab(int tab) {
if (currentTab == tab) {
return;
}
currentTab = tab;
if (animator != null) {
animator.cancel();
}
animator = new AnimatorSet();
animator.playTogether(ObjectAnimator.ofFloat(slidingView, View.TRANSLATION_X, currentTab == 0 ? 0 : slidingView.getMeasuredWidth()));
animator.setDuration(180);
animator.setInterpolator(CubicBezierInterpolator.EASE_OUT);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animator = null;
}
});
animator.start();
onTabSwitch(currentTab);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec) - dp(28);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) leftTab.getLayoutParams();
layoutParams.width = width / 2;
layoutParams = (FrameLayout.LayoutParams) rightTab.getLayoutParams();
layoutParams.width = width / 2;
layoutParams.leftMargin = width / 2 + dp(14);
layoutParams = (FrameLayout.LayoutParams) slidingView.getLayoutParams();
layoutParams.width = width / 2;
if (animator != null) {
animator.cancel();
}
slidingView.setTranslationX(currentTab == 0 ? 0 : layoutParams.width);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@SuppressWarnings("FieldCanBeLocal")
private class SearchField extends FrameLayout {
private View searchBackground;
private ImageView searchIconImageView;
private ImageView clearSearchImageView;
private CloseProgressDrawable2 progressDrawable;
private EditTextBoldCursor searchEditText;
private View backgroundView;
public SearchField(Context context) {
super(context);
searchBackground = new View(context);
searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(dp(18), getThemedColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground)));
addView(searchBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 11, 14, 0));
searchIconImageView = new ImageView(context);
searchIconImageView.setScaleType(ImageView.ScaleType.CENTER);
searchIconImageView.setImageResource(R.drawable.smiles_inputsearch);
searchIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_mutedIcon : Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY));
addView(searchIconImageView, LayoutHelper.createFrame(36, 36, Gravity.LEFT | Gravity.TOP, 16, 11, 0, 0));
clearSearchImageView = new ImageView(context);
clearSearchImageView.setScaleType(ImageView.ScaleType.CENTER);
clearSearchImageView.setImageDrawable(progressDrawable = new CloseProgressDrawable2() {
@Override
protected int getCurrentColor() {
return getThemedColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchIcon);
}
});
progressDrawable.setSide(dp(7));
clearSearchImageView.setScaleX(0.1f);
clearSearchImageView.setScaleY(0.1f);
clearSearchImageView.setAlpha(0.0f);
addView(clearSearchImageView, LayoutHelper.createFrame(36, 36, Gravity.RIGHT | Gravity.TOP, 14, 11, 14, 0));
clearSearchImageView.setOnClickListener(v -> {
updateSearchAdapter = true;
searchEditText.setText("");
AndroidUtilities.showKeyboard(searchEditText);
});
searchEditText = new EditTextBoldCursor(context);
searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
searchEditText.setHintTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchHint));
searchEditText.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_dialogSearchText));
searchEditText.setBackgroundDrawable(null);
searchEditText.setPadding(0, 0, 0, 0);
searchEditText.setMaxLines(1);
searchEditText.setLines(1);
searchEditText.setSingleLine(true);
searchEditText.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
searchEditText.setHint(LocaleController.getString("ShareSendTo", R.string.ShareSendTo));
searchEditText.setCursorColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_featuredStickers_addedIcon));
searchEditText.setCursorSize(dp(20));
searchEditText.setCursorWidth(1.5f);
addView(searchEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 40, Gravity.LEFT | Gravity.TOP, 16 + 38, 9, 16 + 30, 0));
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
boolean show = searchEditText.length() > 0;
boolean showed = clearSearchImageView.getAlpha() != 0;
if (show != showed) {
clearSearchImageView.animate()
.alpha(show ? 1.0f : 0.0f)
.setDuration(150)
.scaleX(show ? 1.0f : 0.1f)
.scaleY(show ? 1.0f : 0.1f)
.start();
}
if (!TextUtils.isEmpty(searchEditText.getText())) {
checkCurrentList(false);
}
if (!updateSearchAdapter) {
return;
}
String text = searchEditText.getText().toString();
if (text.length() != 0) {
if (searchEmptyView != null) {
searchEmptyView.title.setText(LocaleController.getString("NoResult", R.string.NoResult));
}
} else {
if (gridView.getAdapter() != listAdapter) {
int top = getCurrentTop();
searchEmptyView.title.setText(LocaleController.getString("NoResult", R.string.NoResult));
searchEmptyView.showProgress(false, true);
checkCurrentList(false);
listAdapter.notifyDataSetChanged();
if (top > 0) {
layoutManager.scrollToPositionWithOffset(0, -top);
}
}
}
if (searchAdapter != null) {
searchAdapter.searchDialogs(text);
}
}
});
searchEditText.setOnEditorActionListener((v, actionId, event) -> {
if (event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
AndroidUtilities.hideKeyboard(searchEditText);
}
return false;
});
}
public void hideKeyboard() {
AndroidUtilities.hideKeyboard(searchEditText);
}
}
public static ShareAlert createShareAlert(final Context context, MessageObject messageObject, final String text, boolean channel, final String copyLink, boolean fullScreen) {
ArrayList<MessageObject> arrayList;
if (messageObject != null) {
arrayList = new ArrayList<>();
arrayList.add(messageObject);
} else {
arrayList = null;
}
return new ShareAlert(context, null, arrayList, text, null, channel, copyLink, null, fullScreen, false);
}
public ShareAlert(final Context context, ArrayList<MessageObject> messages, final String text, boolean channel, final String copyLink, boolean fullScreen) {
this(context, messages, text, channel, copyLink, fullScreen, null);
}
public ShareAlert(final Context context, ArrayList<MessageObject> messages, final String text, boolean channel, final String copyLink, boolean fullScreen, Theme.ResourcesProvider resourcesProvider) {
this(context, null, messages, text, null, channel, copyLink, null, fullScreen, false, false, resourcesProvider);
}
public ShareAlert(final Context context, ChatActivity fragment, ArrayList<MessageObject> messages, final String text, final String text2, boolean channel, final String copyLink, final String copyLink2, boolean fullScreen, boolean forCall) {
this(context, fragment, messages, text, text2, channel, copyLink, copyLink2, fullScreen, forCall, false, null);
}
public ShareAlert(final Context context, ChatActivity fragment, ArrayList<MessageObject> messages, final String text, final String text2, boolean channel, final String copyLink, final String copyLink2, boolean fullScreen, boolean forCall, boolean includeStory, Theme.ResourcesProvider resourcesProvider) {
super(context, true, resourcesProvider);
this.resourcesProvider = resourcesProvider;
this.includeStory = includeStory;
if (context instanceof Activity) {
parentActivity = (Activity) context;
}
darkTheme = forCall;
parentFragment = fragment;
shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
int backgroundColor = getThemedColor(behindKeyboardColorKey = (darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground));
shadowDrawable.setColorFilter(new PorterDuffColorFilter(backgroundColor, PorterDuff.Mode.MULTIPLY));
fixNavigationBar(backgroundColor);
isFullscreen = fullScreen;
linkToCopy[0] = copyLink;
linkToCopy[1] = copyLink2;
sendingMessageObjects = messages;
searchAdapter = new ShareSearchAdapter(context);
isChannel = channel;
sendingText[0] = text;
sendingText[1] = text2;
useSmoothKeyboard = true;
super.setDelegate(new BottomSheetDelegate() {
@Override
public void onOpenAnimationEnd() {
fullyShown = true;
}
});
if (sendingMessageObjects != null) {
for (int a = 0, N = sendingMessageObjects.size(); a < N; a++) {
MessageObject messageObject = sendingMessageObjects.get(a);
if (messageObject.isPoll()) {
hasPoll = messageObject.isPublicPoll() ? 2 : 1;
if (hasPoll == 2) {
break;
}
}
}
}
if (channel) {
loadingLink = true;
TLRPC.TL_channels_exportMessageLink req = new TLRPC.TL_channels_exportMessageLink();
req.id = messages.get(0).getId();
req.channel = MessagesController.getInstance(currentAccount).getInputChannel(messages.get(0).messageOwner.peer_id.channel_id);
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (response != null) {
exportedMessageLink = (TLRPC.TL_exportedMessageLink) response;
if (copyLinkOnEnd) {
copyLink(context);
}
}
loadingLink = false;
}));
}
sizeNotifierFrameLayout = new SizeNotifierFrameLayout(context) {
private boolean ignoreLayout = false;
private RectF rect1 = new RectF();
private boolean fullHeight;
private int topOffset;
private int previousTopOffset;
private int fromScrollY;
private int toScrollY;
private int fromOffsetTop;
private int toOffsetTop;
{
adjustPanLayoutHelper = new AdjustPanLayoutHelper(this) {
@Override
protected void onTransitionStart(boolean keyboardVisible, int contentHeight) {
super.onTransitionStart(keyboardVisible, contentHeight);
if (previousScrollOffsetY != scrollOffsetY) {
fromScrollY = previousScrollOffsetY;
toScrollY = scrollOffsetY;
panTranslationMoveLayout = true;
scrollOffsetY = fromScrollY;
} else {
fromScrollY = -1;
}
if (topOffset != previousTopOffset) {
fromOffsetTop = 0;
toOffsetTop = 0;
panTranslationMoveLayout = true;
if (!keyboardVisible) {
toOffsetTop -= topOffset - previousTopOffset;
} else {
toOffsetTop += topOffset - previousTopOffset;
}
scrollOffsetY = keyboardVisible ? fromScrollY : toScrollY;
} else {
fromOffsetTop = -1;
}
gridView.setTopGlowOffset((int) (currentPanTranslationY + scrollOffsetY));
frameLayout.setTranslationY(currentPanTranslationY + scrollOffsetY);
searchEmptyView.setTranslationY(currentPanTranslationY + scrollOffsetY);
invalidate();
}
@Override
protected void onTransitionEnd() {
super.onTransitionEnd();
panTranslationMoveLayout = false;
previousScrollOffsetY = scrollOffsetY;
gridView.setTopGlowOffset(scrollOffsetY);
frameLayout.setTranslationY(scrollOffsetY);
searchEmptyView.setTranslationY(scrollOffsetY);
gridView.setTranslationY(0);
searchGridView.setTranslationY(0);
}
@Override
protected void onPanTranslationUpdate(float y, float progress, boolean keyboardVisible) {
super.onPanTranslationUpdate(y, progress, keyboardVisible);
for (int i = 0; i < containerView.getChildCount(); i++) {
if (containerView.getChildAt(i) != pickerBottomLayout && containerView.getChildAt(i) != bulletinContainer && containerView.getChildAt(i) != shadow[1] && containerView.getChildAt(i) != sharesCountLayout
&& containerView.getChildAt(i) != frameLayout2 && containerView.getChildAt(i) != writeButtonContainer && containerView.getChildAt(i) != selectedCountView) {
containerView.getChildAt(i).setTranslationY(y);
}
}
currentPanTranslationY = y;
if (fromScrollY != -1) {
float p = keyboardVisible ? progress : (1f - progress);
scrollOffsetY = (int) (fromScrollY * (1f - p) + toScrollY * p);
float translationY = currentPanTranslationY + (fromScrollY - toScrollY) * (1f - p);
gridView.setTranslationY(translationY);
if (keyboardVisible) {
searchGridView.setTranslationY(translationY);
} else {
searchGridView.setTranslationY(translationY + gridView.getPaddingTop());
}
} else if (fromOffsetTop != -1) {
scrollOffsetY = (int) (fromOffsetTop * (1f - progress) + toOffsetTop * progress);
float p = keyboardVisible ? (1f - progress) : progress;
if (keyboardVisible) {
gridView.setTranslationY(currentPanTranslationY - (fromOffsetTop - toOffsetTop) * progress);
} else {
gridView.setTranslationY(currentPanTranslationY + (toOffsetTop - fromOffsetTop) * p);
}
}
gridView.setTopGlowOffset((int) (scrollOffsetY + currentPanTranslationY));
frameLayout.setTranslationY(scrollOffsetY + currentPanTranslationY);
searchEmptyView.setTranslationY(scrollOffsetY + currentPanTranslationY);
frameLayout2.invalidate();
setCurrentPanTranslationY(currentPanTranslationY);
invalidate();
}
@Override
protected boolean heightAnimationEnabled() {
if (isDismissed() || !fullyShown) {
return false;
}
return !commentTextView.isPopupVisible();
}
};
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
adjustPanLayoutHelper.setResizableView(this);
adjustPanLayoutHelper.onAttach();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
adjustPanLayoutHelper.onDetach();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int totalHeight;
if (getLayoutParams().height > 0) {
totalHeight = getLayoutParams().height;
} else {
totalHeight = MeasureSpec.getSize(heightMeasureSpec);
}
layoutManager.setNeedFixGap(getLayoutParams().height <= 0);
searchLayoutManager.setNeedFixGap(getLayoutParams().height <= 0);
if (Build.VERSION.SDK_INT >= 21 && !isFullscreen) {
ignoreLayout = true;
setPadding(backgroundPaddingLeft, AndroidUtilities.statusBarHeight, backgroundPaddingLeft, 0);
ignoreLayout = false;
}
int availableHeight = totalHeight - getPaddingTop();
int size = Math.max(searchAdapter.getItemCount(), listAdapter.getItemCount() - 1);
int contentSize = dp(103) + dp(48) + Math.max(2, (int) Math.ceil(size / 4.0f)) * dp(103) + backgroundPaddingTop;
if (topicsGridView.getVisibility() != View.GONE) {
int topicsSize = dp(103) + dp(48) + Math.max(2, (int) Math.ceil((shareTopicsAdapter.getItemCount() - 1) / 4.0f)) * dp(103) + backgroundPaddingTop;
if (topicsSize > contentSize) {
contentSize = AndroidUtilities.lerp(contentSize, topicsSize, topicsGridView.getAlpha());
}
}
int padding = (contentSize < availableHeight ? 0 : availableHeight - (availableHeight / 5 * 3)) + dp(8);
if (gridView.getPaddingTop() != padding) {
ignoreLayout = true;
gridView.setPadding(0, padding, 0, dp(48));
topicsGridView.setPadding(0, padding, 0, dp(48));
ignoreLayout = false;
}
if (keyboardVisible && getLayoutParams().height <= 0 && searchGridView.getPaddingTop() != padding) {
ignoreLayout = true;
searchGridView.setPadding(0, 0, 0, dp(48));
ignoreLayout = false;
}
fullHeight = contentSize >= totalHeight;
topOffset = fullHeight ? 0 : totalHeight - contentSize;
ignoreLayout = true;
checkCurrentList(false);
ignoreLayout = false;
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), totalHeight);
onMeasureInternal(widthMeasureSpec, MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY));
}
private void onMeasureInternal(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
widthSize -= backgroundPaddingLeft * 2;
int keyboardSize = 0;
if (!commentTextView.isWaitingForKeyboardOpen() && keyboardSize <= dp(20) && !commentTextView.isPopupShowing() && !commentTextView.isAnimatePopupClosing()) {
ignoreLayout = true;
commentTextView.hideEmojiView();
ignoreLayout = false;
}
ignoreLayout = true;
if (keyboardSize <= dp(20)) {
if (!AndroidUtilities.isInMultiwindow) {
int paddingBottom;
if (keyboardVisible) {
paddingBottom = 0;
} else {
paddingBottom = commentTextView.getEmojiPadding();
}
heightSize -= paddingBottom;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
}
int visibility = commentTextView.isPopupShowing() ? GONE : VISIBLE;
if (pickerBottomLayout != null) {
pickerBottomLayout.setVisibility(visibility);
if (sharesCountLayout != null) {
sharesCountLayout.setVisibility(visibility);
}
}
} else {
commentTextView.hideEmojiView();
if (pickerBottomLayout != null) {
pickerBottomLayout.setVisibility(GONE);
if (sharesCountLayout != null) {
sharesCountLayout.setVisibility(GONE);
}
}
}
ignoreLayout = false;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child == null || child.getVisibility() == GONE) {
continue;
}
if (commentTextView != null && commentTextView.isPopupView(child)) {
if (AndroidUtilities.isInMultiwindow || AndroidUtilities.isTablet()) {
if (AndroidUtilities.isTablet()) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(dp(AndroidUtilities.isTablet() ? 200 : 320), heightSize - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
}
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
}
} else {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int keyboardSize = measureKeyboardHeight();
int paddingBottom;
if (keyboardVisible) {
paddingBottom = 0;
} else {
paddingBottom = keyboardSize <= dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? commentTextView.getEmojiPadding() : 0;
}
setBottomClip(paddingBottom);
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.LEFT;
}
final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = (r - l) - width - lp.rightMargin - getPaddingRight() - backgroundPaddingLeft;
break;
case Gravity.LEFT:
default:
childLeft = lp.leftMargin + getPaddingLeft();
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = lp.topMargin + getPaddingTop() + topOffset;
break;
case Gravity.CENTER_VERTICAL:
childTop = ((b - paddingBottom) - (t + topOffset) - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
break;
default:
childTop = lp.topMargin;
}
if (commentTextView != null && commentTextView.isPopupView(child)) {
if (AndroidUtilities.isTablet()) {
childTop = getMeasuredHeight() - child.getMeasuredHeight();
} else {
childTop = getMeasuredHeight() + keyboardSize - child.getMeasuredHeight();
}
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
notifyHeightChanged();
updateLayout();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!fullHeight) {
if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getY() < topOffset - dp(30)) {
dismiss();
return true;
}
} else {
if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0 && ev.getY() < scrollOffsetY - dp(30)) {
dismiss();
return true;
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
return !isDismissed() && super.onTouchEvent(e);
}
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
private boolean lightStatusBar = AndroidUtilities.computePerceivedBrightness(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)) > .721f;
private final AnimatedFloat pinnedToTop = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(0, currentPanTranslationY);
int y = scrollOffsetY - backgroundPaddingTop + dp(6) + topOffset;
int top = containerViewTop = scrollOffsetY - backgroundPaddingTop - dp(13) + topOffset;
int height = getMeasuredHeight() + dp(30 + 30) + backgroundPaddingTop;
int statusBarHeight = 0;
float radProgress = 1.0f;
float pinAlpha = 0;
if (!isFullscreen && Build.VERSION.SDK_INT >= 21) {
y += AndroidUtilities.statusBarHeight;
final boolean pinnedToTop = fullHeight && top + backgroundPaddingTop < AndroidUtilities.statusBarHeight;
top = AndroidUtilities.lerp(top + AndroidUtilities.statusBarHeight, -backgroundPaddingTop, pinAlpha = this.pinnedToTop.set(pinnedToTop));
}
shadowDrawable.setBounds(0, top, getMeasuredWidth(), height);
shadowDrawable.draw(canvas);
if (bulletinContainer2 != null) {
if (top <= AndroidUtilities.statusBarHeight && bulletinContainer2.getChildCount() > 0) {
bulletinContainer2.setTranslationY(0);
Bulletin bulletin = Bulletin.getVisibleBulletin();
if (bulletin != null) {
if (bulletin.getLayout() != null) {
bulletin.getLayout().setTop(true);
}
bulletin.hide();
}
} else {
bulletinContainer2.setTranslationY(Math.max(0, top + backgroundPaddingTop - bulletinContainer2.getTop() - bulletinContainer2.getMeasuredHeight()));
}
}
if (pinAlpha < 1) {
int w = dp(36);
rect1.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + dp(4));
Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(darkTheme ? Theme.key_voipgroup_scrollUp : Theme.key_sheet_scrollUp));
Theme.dialogs_onlineCirclePaint.setAlpha((int) (Theme.dialogs_onlineCirclePaint.getAlpha() * (1f - pinAlpha)));
canvas.drawRoundRect(rect1, dp(2), dp(2), Theme.dialogs_onlineCirclePaint);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = getSystemUiVisibility();
boolean shouldBeLightStatusBar = lightStatusBar && statusBarHeight > AndroidUtilities.statusBarHeight * .5f;
boolean isLightStatusBar = (flags & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) > 0;
if (shouldBeLightStatusBar != isLightStatusBar) {
if (shouldBeLightStatusBar) {
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
setSystemUiVisibility(flags);
}
}
canvas.restore();
previousTopOffset = topOffset;
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.clipRect(0, getPaddingTop() + currentPanTranslationY, getMeasuredWidth(), getMeasuredHeight() + currentPanTranslationY + dp(50));
super.dispatchDraw(canvas);
canvas.restore();
}
};
containerView = sizeNotifierFrameLayout;
containerView.setWillNotDraw(false);
containerView.setClipChildren(false);
containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);
frameLayout = new FrameLayout(context);
frameLayout.setBackgroundColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground));
if (darkTheme && linkToCopy[1] != null) {
switchView = new SwitchView(context) {
@Override
protected void onTabSwitch(int num) {
if (pickerBottomLayout == null) {
return;
}
if (num == 0) {
pickerBottomLayout.setText(LocaleController.getString("VoipGroupCopySpeakerLink", R.string.VoipGroupCopySpeakerLink).toUpperCase());
} else {
pickerBottomLayout.setText(LocaleController.getString("VoipGroupCopyListenLink", R.string.VoipGroupCopyListenLink).toUpperCase());
}
}
};
frameLayout.addView(switchView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.LEFT, 0, 11, 0, 0));
}
searchView = new SearchField(context);
frameLayout.addView(searchView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 58, Gravity.BOTTOM | Gravity.LEFT));
topicsBackActionBar = new ActionBar(context);
topicsBackActionBar.setOccupyStatusBar(false);
topicsBackActionBar.setBackButtonImage(R.drawable.ic_ab_back);
topicsBackActionBar.setTitleColor(getThemedColor(Theme.key_dialogTextBlack));
topicsBackActionBar.setSubtitleColor(getThemedColor(Theme.key_dialogTextGray2));
topicsBackActionBar.setItemsColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2), false);
topicsBackActionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarWhiteSelector), false);
topicsBackActionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
onBackPressed();
}
});
topicsBackActionBar.setVisibility(View.GONE);
frameLayout.addView(topicsBackActionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 58, Gravity.BOTTOM | Gravity.LEFT));
topicsGridView = new RecyclerListView(context, resourcesProvider);
topicsGridView.setLayoutManager(topicsLayoutManager = new GridLayoutManager(context, 4));
topicsLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position == 0) {
return topicsLayoutManager.getSpanCount();
}
return 1;
}
});
topicsGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy != 0) {
updateLayout();
previousScrollOffsetY = scrollOffsetY;
}
}
});
topicsGridView.setAdapter(shareTopicsAdapter = new ShareTopicsAdapter(context));
topicsGridView.setGlowColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow));
topicsGridView.setVerticalScrollBarEnabled(false);
topicsGridView.setHorizontalScrollBarEnabled(false);
topicsGridView.setOverScrollMode(View.OVER_SCROLL_NEVER);
topicsGridView.setSelectorDrawableColor(0);
topicsGridView.setItemSelectorColorProvider(i -> 0);
topicsGridView.setPadding(0, 0, 0, dp(48));
topicsGridView.setClipToPadding(false);
topicsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(@NonNull android.graphics.Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
RecyclerListView.Holder holder = (RecyclerListView.Holder) parent.getChildViewHolder(view);
if (holder != null) {
int pos = holder.getAdapterPosition();
outRect.left = pos % 4 == 0 ? 0 : dp(4);
outRect.right = pos % 4 == 3 ? 0 : dp(4);
} else {
outRect.left = dp(4);
outRect.right = dp(4);
}
}
});
topicsGridView.setOnItemClickListener((view, position) -> {
TLRPC.TL_forumTopic topic = shareTopicsAdapter.getItem(position);
if (topic == null || selectedTopicDialog == null) {
return;
}
long dialogId = selectedTopicDialog.id;
TLRPC.Dialog dialog = selectedTopicDialog;
selectedDialogs.put(dialogId, dialog);
selectedDialogTopics.put(dialog, topic);
updateSelectedCount(2);
if (searchIsVisible || searchWasVisibleBeforeTopics) {
TLRPC.Dialog existingDialog = listAdapter.dialogsMap.get(dialog.id);
if (existingDialog == null) {
listAdapter.dialogsMap.put(dialog.id, dialog);
listAdapter.dialogs.add(listAdapter.dialogs.isEmpty() ? 0 : 1, dialog);
}
listAdapter.notifyDataSetChanged();
updateSearchAdapter = false;
searchView.searchEditText.setText("");
checkCurrentList(false);
}
for (int i = 0; i < getMainGridView().getChildCount(); i++) {
View child = getMainGridView().getChildAt(i);
if (child instanceof ShareDialogCell && ((ShareDialogCell) child).getCurrentDialog() == selectedTopicDialog.id) {
ShareDialogCell cell = (ShareDialogCell) child;
if (cell != null) {
cell.setTopic(topic, true);
cell.setChecked(true, true);
}
}
}
collapseTopics();
});
topicsGridView.setVisibility(View.GONE);
containerView.addView(topicsGridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
gridView = new RecyclerListView(context, resourcesProvider) {
@Override
protected boolean allowSelectChildAtPosition(float x, float y) {
return y >= dp(darkTheme && linkToCopy[1] != null ? 111 : 58) + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
}
@Override
public void draw(Canvas canvas) {
if (topicsGridView.getVisibility() != View.GONE) {
canvas.save();
canvas.clipRect(0, scrollOffsetY + dp(darkTheme && linkToCopy[1] != null ? 111 : 58), getWidth(), getHeight());
}
super.draw(canvas);
if (topicsGridView.getVisibility() != View.GONE) {
canvas.restore();
}
}
};
gridView.setSelectorDrawableColor(0);
gridView.setItemSelectorColorProvider(i -> 0);
gridView.setPadding(0, 0, 0, dp(48));
gridView.setClipToPadding(false);
gridView.setLayoutManager(layoutManager = new GridLayoutManager(getContext(), 4));
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position == 0) {
return layoutManager.getSpanCount();
}
return 1;
}
});
gridView.setHorizontalScrollBarEnabled(false);
gridView.setVerticalScrollBarEnabled(false);
gridView.setOverScrollMode(View.OVER_SCROLL_NEVER);
gridView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
RecyclerListView.Holder holder = (RecyclerListView.Holder) parent.getChildViewHolder(view);
if (holder != null) {
int pos = holder.getAdapterPosition();
outRect.left = pos % 4 == 0 ? 0 : dp(4);
outRect.right = pos % 4 == 3 ? 0 : dp(4);
} else {
outRect.left = dp(4);
outRect.right = dp(4);
}
}
});
containerView.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
gridView.setAdapter(listAdapter = new ShareDialogsAdapter(context));
gridView.setGlowColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow));
gridView.setOnItemClickListener((view, position) -> {
if (position < 0) {
return;
}
TLRPC.Dialog dialog = listAdapter.getItem(position);
if (dialog == null) {
return;
}
selectDialog(view, dialog);
});
gridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy != 0) {
updateLayout();
previousScrollOffsetY = scrollOffsetY;
}
if (Bulletin.getVisibleBulletin() != null && Bulletin.getVisibleBulletin().getLayout() != null && Bulletin.getVisibleBulletin().getLayout().getParent() instanceof View && ((View) Bulletin.getVisibleBulletin().getLayout().getParent()).getParent() == bulletinContainer2) {
Bulletin.hideVisible();
}
}
});
searchGridView = new RecyclerListView(context, resourcesProvider) {
@Override
protected boolean allowSelectChildAtPosition(float x, float y) {
return y >= dp(darkTheme && linkToCopy[1] != null ? 111 : 58) + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
}
@Override
public void draw(Canvas canvas) {
if (topicsGridView.getVisibility() != View.GONE) {
canvas.save();
canvas.clipRect(0, scrollOffsetY + dp(darkTheme && linkToCopy[1] != null ? 111 : 58), getWidth(), getHeight());
}
super.draw(canvas);
if (topicsGridView.getVisibility() != View.GONE) {
canvas.restore();
}
}
};
searchGridView.setItemSelectorColorProvider(i -> 0);
searchGridView.setSelectorDrawableColor(0);
searchGridView.setPadding(0, 0, 0, dp(48));
searchGridView.setClipToPadding(false);
searchGridView.setLayoutManager(searchLayoutManager = new FillLastGridLayoutManager(getContext(), 4, 0, searchGridView));
searchLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return searchAdapter.getSpanSize(4, position);
}
});
searchGridView.setOnItemClickListener((view, position) -> {
if (position < 0) {
return;
}
TLRPC.Dialog dialog = searchAdapter.getItem(position);
if (dialog == null) {
return;
}
selectDialog(view, dialog);
});
searchGridView.setHasFixedSize(true);
searchGridView.setItemAnimator(null);
searchGridView.setHorizontalScrollBarEnabled(false);
searchGridView.setVerticalScrollBarEnabled(false);
searchGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy != 0) {
updateLayout();
previousScrollOffsetY = scrollOffsetY;
}
}
});
searchGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final RecyclerListView.Holder holder = (RecyclerListView.Holder) parent.getChildViewHolder(view);
if (holder != null) {
if (holder.getItemViewType() != 5) {
outRect.left = outRect.right = 0;
} else {
final int pos = holder.getAdapterPosition();
outRect.left = pos % 4 == 0 ? 0 : dp(4);
outRect.right = pos % 4 == 3 ? 0 : dp(4);
}
} else {
outRect.left = dp(4);
outRect.right = dp(4);
}
}
});
searchGridView.setAdapter(searchAdapter);
searchGridView.setGlowColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow));
recyclerItemsEnterAnimator = new RecyclerItemsEnterAnimator(searchGridView, true);
FlickerLoadingView flickerLoadingView = new FlickerLoadingView(context, resourcesProvider);
flickerLoadingView.setViewType(FlickerLoadingView.SHARE_ALERT_TYPE);
if (darkTheme) {
flickerLoadingView.setColors(Theme.key_voipgroup_inviteMembersBackground, Theme.key_voipgroup_searchBackground, -1);
}
searchEmptyView = new StickerEmptyView(context, flickerLoadingView, StickerEmptyView.STICKER_TYPE_SEARCH, resourcesProvider);
searchEmptyView.addView(flickerLoadingView, 0);
searchEmptyView.setAnimateLayoutChange(true);
searchEmptyView.showProgress(false, false);
if (darkTheme) {
searchEmptyView.title.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
}
searchEmptyView.title.setText(LocaleController.getString("NoResult", R.string.NoResult));
searchGridView.setEmptyView(searchEmptyView);
searchGridView.setHideIfEmpty(false);
searchGridView.setAnimateEmptyView(true, RecyclerListView.EMPTY_VIEW_ANIMATION_TYPE_ALPHA);
containerView.addView(searchEmptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 52, 0, 0));
containerView.addView(searchGridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT);
frameLayoutParams.topMargin = dp(darkTheme && linkToCopy[1] != null ? 111 : 58);
shadow[0] = new View(context);
shadow[0].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine));
shadow[0].setAlpha(0.0f);
shadow[0].setTag(1);
containerView.addView(shadow[0], frameLayoutParams);
containerView.addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, darkTheme && linkToCopy[1] != null ? 111 : 58, Gravity.LEFT | Gravity.TOP));
frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.BOTTOM | Gravity.LEFT);
frameLayoutParams.bottomMargin = dp(48);
shadow[1] = new View(context);
shadow[1].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine));
containerView.addView(shadow[1], frameLayoutParams);
if (isChannel || linkToCopy[0] != null) {
pickerBottomLayout = new TextView(context);
pickerBottomLayout.setBackgroundDrawable(Theme.createSelectorWithBackgroundDrawable(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground), getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector)));
pickerBottomLayout.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2));
pickerBottomLayout.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
pickerBottomLayout.setPadding(dp(18), 0, dp(18), 0);
pickerBottomLayout.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
pickerBottomLayout.setGravity(Gravity.CENTER);
if (darkTheme && linkToCopy[1] != null) {
pickerBottomLayout.setText(LocaleController.getString("VoipGroupCopySpeakerLink", R.string.VoipGroupCopySpeakerLink).toUpperCase());
} else {
pickerBottomLayout.setText(LocaleController.getString("CopyLink", R.string.CopyLink).toUpperCase());
}
pickerBottomLayout.setOnClickListener(v -> {
if (selectedDialogs.size() == 0 && (isChannel || linkToCopy[0] != null)) {
dismiss();
if (linkToCopy[0] == null && loadingLink) {
copyLinkOnEnd = true;
Toast.makeText(ShareAlert.this.getContext(), LocaleController.getString("Loading", R.string.Loading), Toast.LENGTH_SHORT).show();
} else {
copyLink(ShareAlert.this.getContext());
}
}
});
containerView.addView(pickerBottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
if (parentFragment != null && ChatObject.hasAdminRights(parentFragment.getCurrentChat()) && sendingMessageObjects.size() > 0 && sendingMessageObjects.get(0).messageOwner.forwards > 0) {
MessageObject messageObject = sendingMessageObjects.get(0);
if (!messageObject.isForwarded()) {
sharesCountLayout = new LinearLayout(context);
sharesCountLayout.setOrientation(LinearLayout.HORIZONTAL);
sharesCountLayout.setGravity(Gravity.CENTER_VERTICAL);
sharesCountLayout.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector), 2));
containerView.addView(sharesCountLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.RIGHT | Gravity.BOTTOM, 6, 0, -6, 0));
sharesCountLayout.setOnClickListener(view -> parentFragment.presentFragment(new MessageStatisticActivity(messageObject)));
ImageView imageView = new ImageView(context);
imageView.setImageResource(R.drawable.share_arrow);
imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2), PorterDuff.Mode.MULTIPLY));
sharesCountLayout.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL, 20, 0, 0, 0));
TextView textView = new TextView(context);
textView.setText(String.format("%d", messageObject.messageOwner.forwards));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2));
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
sharesCountLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL, 8, 0, 20, 0));
}
}
} else {
shadow[1].setAlpha(0.0f);
}
bulletinContainer = new FrameLayout(context);
containerView.addView(bulletinContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, pickerBottomLayout != null ? 48 : 0));
bulletinContainer2 = new FrameLayout(context);
containerView.addView(bulletinContainer2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.FILL_HORIZONTAL | Gravity.TOP, 0, 0, 0, 0));
frameLayout2 = new FrameLayout(context) {
private final Paint p = new Paint();
private int color;
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility != View.VISIBLE) {
shadow[1].setTranslationY(0);
}
}
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (chatActivityEnterViewAnimateFromTop != 0 && chatActivityEnterViewAnimateFromTop != frameLayout2.getTop() + chatActivityEnterViewAnimateFromTop) {
if (topBackgroundAnimator != null) {
topBackgroundAnimator.cancel();
}
captionEditTextTopOffset = chatActivityEnterViewAnimateFromTop - (frameLayout2.getTop() + captionEditTextTopOffset);
topBackgroundAnimator = ValueAnimator.ofFloat(captionEditTextTopOffset, 0);
topBackgroundAnimator.addUpdateListener(valueAnimator -> {
captionEditTextTopOffset = (float) valueAnimator.getAnimatedValue();
frameLayout2.invalidate();
invalidate();
});
topBackgroundAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
topBackgroundAnimator.setDuration(200);
topBackgroundAnimator.start();
chatActivityEnterViewAnimateFromTop = 0;
}
float alphaOffset = (frameLayout2.getMeasuredHeight() - dp(48)) * (1f - getAlpha());
shadow[1].setTranslationY(-(frameLayout2.getMeasuredHeight() - dp(48)) + captionEditTextTopOffset + currentPanTranslationY + alphaOffset);
// int newColor = getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground);
// if (color != newColor) {
// color = newColor;
// p.setColor(color);
// }
// canvas.drawRect(0, captionEditTextTopOffset + alphaOffset, getMeasuredWidth(), getMeasuredHeight(), p);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.clipRect(0, captionEditTextTopOffset, getMeasuredWidth(), getMeasuredHeight());
super.dispatchDraw(canvas);
canvas.restore();
}
};
frameLayout2.setWillNotDraw(false);
frameLayout2.setAlpha(0.0f);
frameLayout2.setVisibility(View.INVISIBLE);
containerView.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
frameLayout2.setOnTouchListener((v, event) -> true);
commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG, true, resourcesProvider) {
private boolean shouldAnimateEditTextWithBounds;
private int messageEditTextPredrawHeigth;
private int messageEditTextPredrawScrollY;
private ValueAnimator messageEditTextAnimator;
@Override
protected void dispatchDraw(Canvas canvas) {
if (shouldAnimateEditTextWithBounds) {
EditTextCaption editText = commentTextView.getEditText();
float dy = (messageEditTextPredrawHeigth - editText.getMeasuredHeight()) + (messageEditTextPredrawScrollY - editText.getScrollY());
editText.setOffsetY(editText.getOffsetY() - dy);
ValueAnimator a = ValueAnimator.ofFloat(editText.getOffsetY(), 0);
a.addUpdateListener(animation -> editText.setOffsetY((float) animation.getAnimatedValue()));
if (messageEditTextAnimator != null) {
messageEditTextAnimator.cancel();
}
messageEditTextAnimator = a;
a.setDuration(200);
a.setInterpolator(CubicBezierInterpolator.DEFAULT);
a.start();
shouldAnimateEditTextWithBounds = false;
}
super.dispatchDraw(canvas);
}
@Override
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
if (!TextUtils.isEmpty(getEditText().getText())) {
shouldAnimateEditTextWithBounds = true;
messageEditTextPredrawHeigth = getEditText().getMeasuredHeight();
messageEditTextPredrawScrollY = getEditText().getScrollY();
invalidate();
} else {
getEditText().animate().cancel();
getEditText().setOffsetY(0);
shouldAnimateEditTextWithBounds = false;
}
chatActivityEnterViewAnimateFromTop = frameLayout2.getTop() + captionEditTextTopOffset;
frameLayout2.invalidate();
}
@Override
protected void showPopup(int show) {
super.showPopup(show);
if (darkTheme) {
navBarColorKey = -1;
AndroidUtilities.setNavigationBarColor(ShareAlert.this.getWindow(), ShareAlert.this.getThemedColor(Theme.key_windowBackgroundGray), true, color -> {
ShareAlert.this.setOverlayNavBarColor(navBarColor = color);
});
}
}
@Override
public void hidePopup(boolean byBackButton) {
super.hidePopup(byBackButton);
if (darkTheme) {
navBarColorKey = -1;
AndroidUtilities.setNavigationBarColor(ShareAlert.this.getWindow(), ShareAlert.this.getThemedColor(Theme.key_voipgroup_inviteMembersBackground), true, color -> {
ShareAlert.this.setOverlayNavBarColor(navBarColor = color);
});
}
}
};
if (darkTheme) {
commentTextView.getEditText().setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
commentTextView.getEditText().setCursorColor(getThemedColor(Theme.key_voipgroup_nameText));
}
commentTextView.setBackgroundColor(backgroundColor);
commentTextView.setHint(LocaleController.getString("ShareComment", R.string.ShareComment));
commentTextView.onResume();
commentTextView.setPadding(0, 0, dp(84), 0);
frameLayout2.addView(commentTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT));
frameLayout2.setClipChildren(false);
frameLayout2.setClipToPadding(false);
commentTextView.setClipChildren(false);
writeButtonContainer = new FrameLayout(context) {
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setText(LocaleController.formatPluralString("AccDescrShareInChats", selectedDialogs.size()));
info.setClassName(Button.class.getName());
info.setLongClickable(true);
info.setClickable(true);
}
};
writeButtonContainer.setFocusable(true);
writeButtonContainer.setFocusableInTouchMode(true);
writeButtonContainer.setVisibility(View.INVISIBLE);
writeButtonContainer.setScaleX(0.2f);
writeButtonContainer.setScaleY(0.2f);
writeButtonContainer.setAlpha(0.0f);
containerView.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 6, 10));
ImageView writeButton = new ImageView(context);
Drawable drawable = Theme.createSimpleSelectorCircleDrawable(dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(dp(56), dp(56));
drawable = combinedDrawable;
}
writeButton.setBackgroundDrawable(drawable);
writeButton.setImageResource(R.drawable.attach_send);
writeButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
writeButton.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
writeButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, dp(56), dp(56));
}
});
}
writeButtonContainer.addView(writeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, Gravity.LEFT | Gravity.TOP, Build.VERSION.SDK_INT >= 21 ? 2 : 0, 0, 0, 0));
writeButton.setOnClickListener(v -> sendInternal(true));
writeButton.setOnLongClickListener(v -> {
return onSendLongClick(writeButton);
});
textPaint.setTextSize(dp(12));
textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
selectedCountView = new View(context) {
@Override
protected void onDraw(Canvas canvas) {
String text = String.format("%d", Math.max(1, selectedDialogs.size()));
int textSize = (int) Math.ceil(textPaint.measureText(text));
int size = Math.max(dp(16) + textSize, dp(24));
int cx = getMeasuredWidth() / 2;
int cy = getMeasuredHeight() / 2;
textPaint.setColor(getThemedColor(Theme.key_dialogRoundCheckBoxCheck));
paint.setColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground));
rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight());
canvas.drawRoundRect(rect, dp(12), dp(12), paint);
paint.setColor(getThemedColor(Theme.key_dialogFloatingButton));
rect.set(cx - size / 2 + dp(2), dp(2), cx + size / 2 - dp(2), getMeasuredHeight() - dp(2));
canvas.drawRoundRect(rect, dp(10), dp(10), paint);
canvas.drawText(text, cx - textSize / 2, dp(16.2f), textPaint);
}
};
selectedCountView.setAlpha(0.0f);
selectedCountView.setScaleX(0.2f);
selectedCountView.setScaleY(0.2f);
containerView.addView(selectedCountView, LayoutHelper.createFrame(42, 24, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -8, 9));
updateSelectedCount(0);
DialogsActivity.loadDialogs(AccountInstance.getInstance(currentAccount));
if (listAdapter.dialogs.isEmpty()) {
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.dialogsNeedReload);
}
DialogsSearchAdapter.loadRecentSearch(currentAccount, 0, new DialogsSearchAdapter.OnRecentSearchLoaded() {
@Override
public void setRecentSearch(ArrayList<DialogsSearchAdapter.RecentSearchObject> arrayList, LongSparseArray<DialogsSearchAdapter.RecentSearchObject> hashMap) {
if (arrayList != null) {
for (int i = 0; i < arrayList.size(); ++i) {
DialogsSearchAdapter.RecentSearchObject recentSearchObject = arrayList.get(i);
if (recentSearchObject.object instanceof TLRPC.Chat && !ChatObject.canWriteToChat((TLRPC.Chat) recentSearchObject.object)) {
arrayList.remove(i);
i--;
}
}
}
recentSearchObjects = arrayList;
recentSearchObjectsById = hashMap;
for (int a = 0; a < recentSearchObjects.size(); a++) {
DialogsSearchAdapter.RecentSearchObject recentSearchObject = recentSearchObjects.get(a);
if (recentSearchObject.object instanceof TLRPC.User) {
MessagesController.getInstance(currentAccount).putUser((TLRPC.User) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.Chat) {
MessagesController.getInstance(currentAccount).putChat((TLRPC.Chat) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.EncryptedChat) {
MessagesController.getInstance(currentAccount).putEncryptedChat((TLRPC.EncryptedChat) recentSearchObject.object, true);
}
}
searchAdapter.notifyDataSetChanged();
}
});
MediaDataController.getInstance(currentAccount).loadHints(true);
AndroidUtilities.updateViewVisibilityAnimated(gridView, true, 1f, false);
AndroidUtilities.updateViewVisibilityAnimated(searchGridView, false, 1f, false);
}
protected void onShareStory(View cell) {
}
private void showPremiumBlockedToast(View view, long dialogId) {
AndroidUtilities.shakeViewSpring(view, shiftDp = -shiftDp);
BotWebViewVibrationEffect.APP_ERROR.vibrate();
String username = "";
if (dialogId >= 0) {
username = UserObject.getUserName(MessagesController.getInstance(currentAccount).getUser(dialogId));
}
Bulletin bulletin;
if (MessagesController.getInstance(currentAccount).premiumFeaturesBlocked()) {
bulletin = BulletinFactory.of(bulletinContainer, resourcesProvider).createSimpleBulletin(R.raw.star_premium_2, AndroidUtilities.replaceTags(LocaleController.formatString(R.string.UserBlockedNonPremium, username)));
} else {
bulletin = BulletinFactory.of(bulletinContainer, resourcesProvider).createSimpleBulletin(R.raw.star_premium_2, AndroidUtilities.replaceTags(LocaleController.formatString(R.string.UserBlockedNonPremium, username)), LocaleController.getString(R.string.UserBlockedNonPremiumButton), () -> {
Runnable openPremium = () -> {
BaseFragment lastFragment = LaunchActivity.getLastFragment();
if (lastFragment != null) {
BaseFragment.BottomSheetParams params = new BaseFragment.BottomSheetParams();
params.transitionFromLeft = true;
params.allowNestedScroll = false;
lastFragment.showAsSheet(new PremiumPreviewFragment("noncontacts"), params);
}
};
if (isKeyboardVisible()) {
if (searchView != null) {
AndroidUtilities.hideKeyboard(searchView.searchEditText);
}
AndroidUtilities.runOnUIThread(openPremium, 300);
} else {
openPremium.run();
}
});
}
bulletin.show();
}
private int shiftDp = 4;
private void selectDialog(View cell, TLRPC.Dialog dialog) {
if (dialog instanceof ShareDialogsAdapter.MyStoryDialog) {
onShareStory(cell);
return;
}
if (dialog != null && (cell instanceof ShareDialogCell && ((ShareDialogCell) cell).isBlocked() || cell instanceof ProfileSearchCell && ((ProfileSearchCell) cell).isBlocked())) {
showPremiumBlockedToast(cell, dialog.id);
return;
}
if (topicsGridView.getVisibility() != View.GONE || parentActivity == null) {
return;
}
if (DialogObject.isChatDialog(dialog.id)) {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialog.id);
if (ChatObject.isChannel(chat) && !chat.megagroup && (!ChatObject.isCanWriteToChannel(-dialog.id, currentAccount) || hasPoll == 2)) {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle));
if (hasPoll == 2) {
if (isChannel) {
builder.setMessage(LocaleController.getString("PublicPollCantForward", R.string.PublicPollCantForward));
} else if (ChatObject.isActionBannedByDefault(chat, ChatObject.ACTION_SEND_POLLS)) {
builder.setMessage(LocaleController.getString("ErrorSendRestrictedPollsAll", R.string.ErrorSendRestrictedPollsAll));
} else {
builder.setMessage(LocaleController.getString("ErrorSendRestrictedPolls", R.string.ErrorSendRestrictedPolls));
}
} else {
builder.setMessage(LocaleController.getString("ChannelCantSendMessage", R.string.ChannelCantSendMessage));
}
builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null);
builder.show();
return;
}
} else if (DialogObject.isEncryptedDialog(dialog.id) && (hasPoll != 0)) {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle));
if (hasPoll != 0) {
builder.setMessage(LocaleController.getString("PollCantForwardSecretChat", R.string.PollCantForwardSecretChat));
} else {
builder.setMessage(LocaleController.getString("InvoiceCantForwardSecretChat", R.string.InvoiceCantForwardSecretChat));
}
builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null);
builder.show();
return;
}
if (selectedDialogs.indexOfKey(dialog.id) >= 0) {
selectedDialogs.remove(dialog.id);
selectedDialogTopics.remove(dialog);
if (cell instanceof ProfileSearchCell) {
((ProfileSearchCell) cell).setChecked(false, true);
} else if (cell instanceof ShareDialogCell) {
((ShareDialogCell) cell).setChecked(false, true);
}
updateSelectedCount(1);
} else {
if (DialogObject.isChatDialog(dialog.id) && MessagesController.getInstance(currentAccount).getChat(-dialog.id) != null && MessagesController.getInstance(currentAccount).getChat(-dialog.id).forum) {
selectedTopicDialog = dialog;
topicsLayoutManager.scrollToPositionWithOffset(0, scrollOffsetY - topicsGridView.getPaddingTop());
AtomicReference<Runnable> timeoutRef = new AtomicReference<>();
NotificationCenter.NotificationCenterDelegate delegate = new NotificationCenter.NotificationCenterDelegate() {
@SuppressLint("NotifyDataSetChanged")
@Override
public void didReceivedNotification(int id, int account, Object... args) {
long chatId = (long) args[0];
if (chatId == -dialog.id) {
boolean animate = shareTopicsAdapter.topics == null && MessagesController.getInstance(currentAccount).getTopicsController().getTopics(-dialog.id) != null || timeoutRef.get() == null;
shareTopicsAdapter.topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(-dialog.id);
if (animate) {
shareTopicsAdapter.notifyDataSetChanged();
}
if (shareTopicsAdapter.topics != null) {
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.topicsDidLoaded);
}
if (animate) {
topicsGridView.setVisibility(View.VISIBLE);
topicsGridView.setAlpha(0);
topicsBackActionBar.setVisibility(View.VISIBLE);
topicsBackActionBar.setAlpha(0);
topicsBackActionBar.setTitle(MessagesController.getInstance(currentAccount).getChat(-dialog.id).title);
topicsBackActionBar.setSubtitle(LocaleController.getString(R.string.SelectTopic));
searchWasVisibleBeforeTopics = searchIsVisible;
if (topicsAnimation != null) {
topicsAnimation.cancel();
}
int[] loc = new int[2];
topicsAnimation = new SpringAnimation(new FloatValueHolder(0))
.setSpring(new SpringForce(1000)
.setStiffness(parentFragment != null && parentFragment.shareAlertDebugTopicsSlowMotion ? 10f : 800f)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY));
topicsAnimation.addUpdateListener((animation, value, velocity) -> {
value /= 1000;
invalidateTopicsAnimation(cell, loc, value);
});
topicsAnimation.addEndListener((animation, canceled, value, velocity) -> {
gridView.setVisibility(View.GONE);
searchGridView.setVisibility(View.GONE);
searchView.setVisibility(View.GONE);
topicsAnimation = null;
});
topicsAnimation.start();
if (timeoutRef.get() != null) {
AndroidUtilities.cancelRunOnUIThread(timeoutRef.get());
timeoutRef.set(null);
}
}
}
}
};
timeoutRef.set(() -> {
timeoutRef.set(null);
delegate.didReceivedNotification(NotificationCenter.topicsDidLoaded, currentAccount, -dialog.id);
});
NotificationCenter.getInstance(currentAccount).addObserver(delegate, NotificationCenter.topicsDidLoaded);
if (MessagesController.getInstance(currentAccount).getTopicsController().getTopics(-dialog.id) != null) {
delegate.didReceivedNotification(NotificationCenter.topicsDidLoaded, currentAccount, -dialog.id);
} else {
MessagesController.getInstance(currentAccount).getTopicsController().loadTopics(-dialog.id);
AndroidUtilities.runOnUIThread(timeoutRef.get(), 300);
}
return;
}
selectedDialogs.put(dialog.id, dialog);
if (cell instanceof ProfileSearchCell) {
((ProfileSearchCell) cell).setChecked(true, true);
} else if (cell instanceof ShareDialogCell) {
((ShareDialogCell) cell).setChecked(true, true);
}
updateSelectedCount(2);
long selfUserId = UserConfig.getInstance(currentAccount).clientUserId;
if (searchIsVisible) {
TLRPC.Dialog existingDialog = listAdapter.dialogsMap.get(dialog.id);
if (existingDialog == null) {
listAdapter.dialogsMap.put(dialog.id, dialog);
listAdapter.dialogs.add(listAdapter.dialogs.isEmpty() ? 0 : 1, dialog);
} else if (existingDialog.id != selfUserId) {
listAdapter.dialogs.remove(existingDialog);
listAdapter.dialogs.add(listAdapter.dialogs.isEmpty() ? 0 : 1, existingDialog);
}
listAdapter.notifyDataSetChanged();
updateSearchAdapter = false;
searchView.searchEditText.setText("");
checkCurrentList(false);
searchView.hideKeyboard();
}
}
if (searchAdapter != null && searchAdapter.categoryAdapter != null) {
searchAdapter.categoryAdapter.notifyItemRangeChanged(0, searchAdapter.categoryAdapter.getItemCount());
}
}
@SuppressLint("NotifyDataSetChanged")
private void collapseTopics() {
if (selectedTopicDialog == null) {
return;
}
TLRPC.Dialog dialog = selectedTopicDialog;
selectedTopicDialog = null;
View cell = null;
for (int i = 0; i < getMainGridView().getChildCount(); i++) {
View child = getMainGridView().getChildAt(i);
if (child instanceof ShareDialogCell && ((ShareDialogCell) child).getCurrentDialog() == dialog.id) {
cell = child;
}
}
if (cell == null) {
return;
}
if (topicsAnimation != null) {
topicsAnimation.cancel();
}
getMainGridView().setVisibility(View.VISIBLE);
searchView.setVisibility(View.VISIBLE);
if (searchIsVisible || searchWasVisibleBeforeTopics) {
sizeNotifierFrameLayout.adjustPanLayoutHelper.ignoreOnce();
searchView.searchEditText.requestFocus();
AndroidUtilities.showKeyboard(searchView.searchEditText);
}
int[] loc = new int[2];
View finalCell = cell;
topicsAnimation = new SpringAnimation(new FloatValueHolder(1000))
.setSpring(new SpringForce(0)
.setStiffness(parentFragment != null && parentFragment.shareAlertDebugTopicsSlowMotion ? 10f : 800f)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY));
topicsAnimation.addUpdateListener((animation, value, velocity) -> {
value /= 1000;
invalidateTopicsAnimation(finalCell, loc, value);
});
topicsAnimation.addEndListener((animation, canceled, value, velocity) -> {
topicsGridView.setVisibility(View.GONE);
topicsBackActionBar.setVisibility(View.GONE);
shareTopicsAdapter.topics = null;
shareTopicsAdapter.notifyDataSetChanged();
topicsAnimation = null;
searchWasVisibleBeforeTopics = false;
});
topicsAnimation.start();
}
private void invalidateTopicsAnimation(View cell, int[] loc, float value) {
topicsGridView.setPivotX(cell.getX() + cell.getWidth() / 2f);
topicsGridView.setPivotY(cell.getY() + cell.getHeight() / 2f);
topicsGridView.setScaleX(0.75f + value * 0.25f);
topicsGridView.setScaleY(0.75f + value * 0.25f);
topicsGridView.setAlpha(value);
RecyclerListView mainGridView = getMainGridView();
mainGridView.setPivotX(cell.getX() + cell.getWidth() / 2f);
mainGridView.setPivotY(cell.getY() + cell.getHeight() / 2f);
mainGridView.setScaleX(1f + value * 0.25f);
mainGridView.setScaleY(1f + value * 0.25f);
mainGridView.setAlpha(1f - value);
searchView.setPivotX(searchView.getWidth() / 2f);
searchView.setPivotY(0);
searchView.setScaleX(0.9f + (1f - value) * 0.1f);
searchView.setScaleY(0.9f + (1f - value) * 0.1f);
searchView.setAlpha(1f - value);
topicsBackActionBar.getBackButton().setTranslationX(-dp(16) * (1f - value));
topicsBackActionBar.getTitleTextView().setTranslationY(dp(16) * (1f - value));
topicsBackActionBar.getSubtitleTextView().setTranslationY(dp(16) * (1f - value));
topicsBackActionBar.setAlpha(value);
topicsGridView.getLocationInWindow(loc);
float moveValue = CubicBezierInterpolator.EASE_OUT.getInterpolation(value);
for (int i = 0; i < mainGridView.getChildCount(); i++) {
View v = mainGridView.getChildAt(i);
if (v instanceof ShareDialogCell) {
v.setTranslationX((v.getX() - cell.getX()) * 0.5f * moveValue);
v.setTranslationY((v.getY() - cell.getY()) * 0.5f * moveValue);
if (v != cell) {
v.setAlpha(1f - Math.min(value, 0.5f) / 0.5f);
} else {
v.setAlpha(1f - value);
}
}
}
for (int i = 0; i < topicsGridView.getChildCount(); i++) {
View v = topicsGridView.getChildAt(i);
if (v instanceof ShareTopicCell) {
v.setTranslationX((float) (-(v.getX() - cell.getX()) * Math.pow(1f - moveValue, 2)));
v.setTranslationY((float) (-(v.getY() + topicsGridView.getTranslationY() - cell.getY()) * Math.pow(1f - moveValue, 2)));
}
}
containerView.requestLayout();
mainGridView.invalidate();
}
@Override
public int getContainerViewHeight() {
return containerView.getMeasuredHeight() - containerViewTop;
}
private boolean showSendersName = true;
private ActionBarPopupWindow sendPopupWindow;
private boolean onSendLongClick(View view) {
if (parentActivity == null) {
return false;
}
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
if (sendingMessageObjects != null) {
ActionBarPopupWindow.ActionBarPopupWindowLayout sendPopupLayout1 = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity, resourcesProvider);
if (darkTheme) {
sendPopupLayout1.setBackgroundColor(getThemedColor(Theme.key_voipgroup_inviteMembersBackground));
}
sendPopupLayout1.setAnimationEnabled(false);
sendPopupLayout1.setOnTouchListener(new View.OnTouchListener() {
private android.graphics.Rect popupRect = new android.graphics.Rect();
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
v.getHitRect(popupRect);
if (!popupRect.contains((int) event.getX(), (int) event.getY())) {
sendPopupWindow.dismiss();
}
}
}
return false;
}
});
sendPopupLayout1.setDispatchKeyEventListener(keyEvent -> {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
});
sendPopupLayout1.setShownFromBottom(false);
ActionBarMenuSubItem showSendersNameView = new ActionBarMenuSubItem(getContext(), true, true, false, resourcesProvider);
if (darkTheme) {
showSendersNameView.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
}
sendPopupLayout1.addView(showSendersNameView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
showSendersNameView.setTextAndIcon(false ? LocaleController.getString("ShowSenderNames", R.string.ShowSenderNames) : LocaleController.getString("ShowSendersName", R.string.ShowSendersName), 0);
showSendersNameView.setChecked(showSendersName = true);
ActionBarMenuSubItem hideSendersNameView = new ActionBarMenuSubItem(getContext(), true, false, true, resourcesProvider);
if (darkTheme) {
hideSendersNameView.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
}
sendPopupLayout1.addView(hideSendersNameView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
hideSendersNameView.setTextAndIcon(false ? LocaleController.getString("HideSenderNames", R.string.HideSenderNames) : LocaleController.getString("HideSendersName", R.string.HideSendersName), 0);
hideSendersNameView.setChecked(!showSendersName);
showSendersNameView.setOnClickListener(e -> {
showSendersNameView.setChecked(showSendersName = true);
hideSendersNameView.setChecked(!showSendersName);
});
hideSendersNameView.setOnClickListener(e -> {
showSendersNameView.setChecked(showSendersName = false);
hideSendersNameView.setChecked(!showSendersName);
});
sendPopupLayout1.setupRadialSelectors(getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_dialogButtonSelector));
layout.addView(sendPopupLayout1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, -8));
}
ActionBarPopupWindow.ActionBarPopupWindowLayout sendPopupLayout2 = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity, resourcesProvider);
if (darkTheme) {
sendPopupLayout2.setBackgroundColor(Theme.getColor(Theme.key_voipgroup_inviteMembersBackground));
}
sendPopupLayout2.setAnimationEnabled(false);
sendPopupLayout2.setOnTouchListener(new View.OnTouchListener() {
private android.graphics.Rect popupRect = new android.graphics.Rect();
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
v.getHitRect(popupRect);
if (!popupRect.contains((int) event.getX(), (int) event.getY())) {
sendPopupWindow.dismiss();
}
}
}
return false;
}
});
sendPopupLayout2.setDispatchKeyEventListener(keyEvent -> {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
});
sendPopupLayout2.setShownFromBottom(false);
ActionBarMenuSubItem sendWithoutSound = new ActionBarMenuSubItem(getContext(), true, true, resourcesProvider);
if (darkTheme) {
sendWithoutSound.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
sendWithoutSound.setIconColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText));
}
sendWithoutSound.setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off);
sendWithoutSound.setMinimumWidth(dp(196));
sendPopupLayout2.addView(sendWithoutSound, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
sendWithoutSound.setOnClickListener(v -> {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
sendInternal(false);
});
ActionBarMenuSubItem sendMessage = new ActionBarMenuSubItem(getContext(), true, true, resourcesProvider);
if (darkTheme) {
sendMessage.setTextColor(getThemedColor(Theme.key_voipgroup_nameText));
sendMessage.setIconColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText));
}
sendMessage.setTextAndIcon(LocaleController.getString("SendMessage", R.string.SendMessage), R.drawable.msg_send);
sendMessage.setMinimumWidth(dp(196));
sendPopupLayout2.addView(sendMessage, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
sendMessage.setOnClickListener(v -> {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
sendInternal(true);
});
sendPopupLayout2.setupRadialSelectors(getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_dialogButtonSelector));
layout.addView(sendPopupLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
sendPopupWindow = new ActionBarPopupWindow(layout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
sendPopupWindow.setAnimationEnabled(false);
sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2);
sendPopupWindow.setOutsideTouchable(true);
sendPopupWindow.setClippingEnabled(true);
sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
sendPopupWindow.getContentView().setFocusableInTouchMode(true);
SharedConfig.removeScheduledOrNoSoundHint();
layout.measure(View.MeasureSpec.makeMeasureSpec(dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(dp(1000), View.MeasureSpec.AT_MOST));
sendPopupWindow.setFocusable(true);
int[] location = new int[2];
view.getLocationInWindow(location);
int y;
if (keyboardVisible && parentFragment != null && parentFragment.contentView.getMeasuredHeight() > dp(58)) {
y = location[1] + view.getMeasuredHeight();
} else {
y = location[1] - layout.getMeasuredHeight() - dp(2);
}
sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - layout.getMeasuredWidth() + dp(8), y);
sendPopupWindow.dimBehind();
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return true;
}
protected void sendInternal(boolean withSound) {
for (int a = 0; a < selectedDialogs.size(); a++) {
long key = selectedDialogs.keyAt(a);
if (AlertsCreator.checkSlowMode(getContext(), currentAccount, key, frameLayout2.getTag() != null && commentTextView.length() > 0)) {
return;
}
}
CharSequence[] text = new CharSequence[] { commentTextView.getText() };
ArrayList<TLRPC.MessageEntity> entities = MediaDataController.getInstance(currentAccount).getEntities(text, true);
if (sendingMessageObjects != null) {
List<Long> removeKeys = new ArrayList<>();
for (int a = 0; a < selectedDialogs.size(); a++) {
long key = selectedDialogs.keyAt(a);
TLRPC.TL_forumTopic topic = selectedDialogTopics.get(selectedDialogs.get(key));
MessageObject replyTopMsg = topic != null ? new MessageObject(currentAccount, topic.topicStartMessage, false, false) : null;
if (replyTopMsg != null) {
replyTopMsg.isTopicMainMessage = true;
}
if (frameLayout2.getTag() != null && commentTextView.length() > 0) {
SendMessagesHelper.getInstance(currentAccount).sendMessage(SendMessagesHelper.SendMessageParams.of(text[0] == null ? null : text[0].toString(), key, replyTopMsg, replyTopMsg, null, true, entities, null, null, withSound, 0, null, false));
}
int result = SendMessagesHelper.getInstance(currentAccount).sendMessage(sendingMessageObjects, key, !showSendersName,false, withSound, 0, replyTopMsg);
if (result != 0) {
removeKeys.add(key);
}
if (selectedDialogs.size() == 1) {
AlertsCreator.showSendMediaAlert(result, parentFragment, null);
if (result != 0) {
break;
}
}
}
for (long key : removeKeys) {
TLRPC.Dialog dialog = selectedDialogs.get(key);
selectedDialogs.remove(key);
if (dialog != null) {
selectedDialogTopics.remove(dialog);
}
}
if (!selectedDialogs.isEmpty()) {
onSend(selectedDialogs, sendingMessageObjects.size(), selectedDialogs.size() == 1 ? selectedDialogTopics.get(selectedDialogs.valueAt(0)) : null);
}
} else {
int num;
if (switchView != null) {
num = switchView.currentTab;
} else {
num = 0;
}
if (storyItem != null) {
for (int a = 0; a < selectedDialogs.size(); a++) {
long key = selectedDialogs.keyAt(a);
TLRPC.TL_forumTopic topic = selectedDialogTopics.get(selectedDialogs.get(key));
MessageObject replyTopMsg = topic != null ? new MessageObject(currentAccount, topic.topicStartMessage, false, false) : null;
SendMessagesHelper.SendMessageParams params;
if (storyItem == null) {
if (frameLayout2.getTag() != null && commentTextView.length() > 0) {
params = SendMessagesHelper.SendMessageParams.of(text[0] == null ? null : text[0].toString(), key, null, replyTopMsg, null, true, entities, null, null, withSound, 0, null, false);
} else {
params = SendMessagesHelper.SendMessageParams.of(sendingText[num], key, null, replyTopMsg, null, true, null, null, null, withSound, 0, null, false);
}
} else {
if (frameLayout2.getTag() != null && commentTextView.length() > 0 && text[0] != null) {
SendMessagesHelper.getInstance(currentAccount).sendMessage(SendMessagesHelper.SendMessageParams.of(text[0].toString(), key, null, replyTopMsg, null, true, null, null, null, withSound, 0, null, false));
}
params = SendMessagesHelper.SendMessageParams.of(null, key, null, replyTopMsg, null, true, null, null, null, withSound, 0, null, false);
params.sendingStory = storyItem;
}
SendMessagesHelper.getInstance(currentAccount).sendMessage(params);
}
} else if (sendingText[num] != null) {
for (int a = 0; a < selectedDialogs.size(); a++) {
long key = selectedDialogs.keyAt(a);
TLRPC.TL_forumTopic topic = selectedDialogTopics.get(selectedDialogs.get(key));
MessageObject replyTopMsg = topic != null ? new MessageObject(currentAccount, topic.topicStartMessage, false, false) : null;
if (frameLayout2.getTag() != null && commentTextView.length() > 0) {
SendMessagesHelper.getInstance(currentAccount).sendMessage(SendMessagesHelper.SendMessageParams.of(text[0] == null ? null : text[0].toString(), key, null, replyTopMsg, null, true, entities, null, null, withSound, 0, null, false));
}
SendMessagesHelper.getInstance(currentAccount).sendMessage(SendMessagesHelper.SendMessageParams.of(sendingText[num], key, null, replyTopMsg, null, true, null, null, null, withSound, 0, null, false));
}
}
onSend(selectedDialogs, 1, selectedDialogTopics.get(selectedDialogs.valueAt(0)));
}
if (delegate != null) {
delegate.didShare();
}
dismiss();
}
protected void onSend(LongSparseArray<TLRPC.Dialog> dids, int count, TLRPC.TL_forumTopic topic) {
}
protected boolean doSend(LongSparseArray<TLRPC.Dialog> dids, TLRPC.TL_forumTopic topic) {
return false;
}
private int getCurrentTop() {
if (gridView.getChildCount() != 0) {
View child = gridView.getChildAt(0);
RecyclerListView.Holder holder = (RecyclerListView.Holder) gridView.findContainingViewHolder(child);
if (holder != null) {
return gridView.getPaddingTop() - (holder.getLayoutPosition() == 0 && child.getTop() >= 0 ? child.getTop() : 0);
}
}
return -1000;
}
private RecyclerListView getMainGridView() {
return searchIsVisible || searchWasVisibleBeforeTopics ? searchGridView : gridView;
}
public void setDelegate(ShareAlertDelegate shareAlertDelegate) {
delegate = shareAlertDelegate;
}
@Override
public void dismissInternal() {
super.dismissInternal();
if (commentTextView != null) {
commentTextView.onDestroy();
}
}
@Override
public void onBackPressed() {
if (selectedTopicDialog != null) {
collapseTopics();
return;
}
if (commentTextView != null && commentTextView.isPopupShowing()) {
commentTextView.hidePopup(true);
return;
}
super.onBackPressed();
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.dialogsNeedReload) {
if (listAdapter != null) {
listAdapter.fetchDialogs();
}
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.dialogsNeedReload);
}
}
@Override
protected boolean canDismissWithSwipe() {
return false;
}
int lastOffset = Integer.MAX_VALUE;
@SuppressLint("NewApi")
private void updateLayout() {
if (panTranslationMoveLayout) {
return;
}
View child;
RecyclerListView.Holder holder = null;
RecyclerListView listView = searchIsVisible ? searchGridView : gridView;
if (listView.getChildCount() <= 0) {
return;
}
child = listView.getChildAt(0);
for (int i = 0; i < listView.getChildCount(); i++) {
if (listView.getChildAt(i).getTop() < child.getTop()) {
child = listView.getChildAt(i);
}
}
holder = (RecyclerListView.Holder) listView.findContainingViewHolder(child);
int top = child.getTop() - dp(8);
int newOffset = top > 0 && holder != null && holder.getAdapterPosition() == 0 ? top : 0;
if (top >= 0 && holder != null && holder.getAdapterPosition() == 0) {
lastOffset = child.getTop();
newOffset = top;
runShadowAnimation(0, false);
} else {
lastOffset = Integer.MAX_VALUE;
runShadowAnimation(0, true);
}
if (topicsGridView.getVisibility() == View.VISIBLE) {
listView = topicsGridView;
if (listView.getChildCount() <= 0) {
return;
}
child = listView.getChildAt(0);
for (int i = 0; i < listView.getChildCount(); i++) {
if (listView.getChildAt(i).getTop() < child.getTop()) {
child = listView.getChildAt(i);
}
}
holder = (RecyclerListView.Holder) listView.findContainingViewHolder(child);
int topicsTop = child.getTop() - dp(8);
int topicsNewOffset = topicsTop > 0 && holder != null && holder.getAdapterPosition() == 0 ? topicsTop : 0;
if (topicsTop >= 0 && holder != null && holder.getAdapterPosition() == 0) {
lastOffset = child.getTop();
topicsNewOffset = topicsTop;
runShadowAnimation(0, false);
} else {
lastOffset = Integer.MAX_VALUE;
runShadowAnimation(0, true);
}
newOffset = AndroidUtilities.lerp(newOffset, topicsNewOffset, topicsGridView.getAlpha());
}
if (scrollOffsetY != newOffset) {
previousScrollOffsetY = scrollOffsetY;
gridView.setTopGlowOffset(scrollOffsetY = (int) (newOffset + currentPanTranslationY));
searchGridView.setTopGlowOffset(scrollOffsetY = (int) (newOffset + currentPanTranslationY));
topicsGridView.setTopGlowOffset(scrollOffsetY = (int) (newOffset + currentPanTranslationY));
frameLayout.setTranslationY(scrollOffsetY + currentPanTranslationY);
searchEmptyView.setTranslationY(scrollOffsetY + currentPanTranslationY);
containerView.invalidate();
}
}
private void runShadowAnimation(final int num, final boolean show) {
if (show && shadow[num].getTag() != null || !show && shadow[num].getTag() == null) {
shadow[num].setTag(show ? null : 1);
if (show) {
shadow[num].setVisibility(View.VISIBLE);
}
if (shadowAnimation[num] != null) {
shadowAnimation[num].cancel();
}
shadowAnimation[num] = new AnimatorSet();
shadowAnimation[num].playTogether(ObjectAnimator.ofFloat(shadow[num], View.ALPHA, show ? 1.0f : 0.0f));
shadowAnimation[num].setDuration(150);
shadowAnimation[num].addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (shadowAnimation[num] != null && shadowAnimation[num].equals(animation)) {
if (!show) {
shadow[num].setVisibility(View.INVISIBLE);
}
shadowAnimation[num] = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (shadowAnimation[num] != null && shadowAnimation[num].equals(animation)) {
shadowAnimation[num] = null;
}
}
});
shadowAnimation[num].start();
}
}
private void copyLink(Context context) {
if (exportedMessageLink == null && linkToCopy[0] == null) {
return;
}
try {
String link;
if (switchView != null) {
link = linkToCopy[switchView.currentTab];
} else {
link = linkToCopy[0];
}
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", link != null ? link : exportedMessageLink.link);
clipboard.setPrimaryClip(clip);
if ((delegate == null || !delegate.didCopy()) && parentActivity instanceof LaunchActivity) {
final boolean isPrivate = exportedMessageLink != null && exportedMessageLink.link.contains("/c/");
((LaunchActivity) parentActivity).showBulletin(factory -> factory.createCopyLinkBulletin(isPrivate, resourcesProvider));
}
} catch (Exception e) {
FileLog.e(e);
}
}
private boolean showCommentTextView(final boolean show) {
if (show == (frameLayout2.getTag() != null)) {
return false;
}
if (animatorSet != null) {
animatorSet.cancel();
}
frameLayout2.setTag(show ? 1 : null);
if (commentTextView.getEditText().isFocused()) {
AndroidUtilities.hideKeyboard(commentTextView.getEditText());
}
commentTextView.hidePopup(true);
if (show) {
frameLayout2.setVisibility(View.VISIBLE);
writeButtonContainer.setVisibility(View.VISIBLE);
}
if (pickerBottomLayout != null) {
ViewCompat.setImportantForAccessibility(pickerBottomLayout, show ? ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS : ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
if (sharesCountLayout != null) {
ViewCompat.setImportantForAccessibility(sharesCountLayout, show ? ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS : ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
animatorSet = new AnimatorSet();
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(frameLayout2, View.ALPHA, show ? 1.0f : 0.0f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.SCALE_X, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.SCALE_Y, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.ALPHA, show ? 1.0f : 0.0f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.SCALE_X, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.SCALE_Y, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.ALPHA, show ? 1.0f : 0.0f));
if (pickerBottomLayout == null || pickerBottomLayout.getVisibility() != View.VISIBLE) {
animators.add(ObjectAnimator.ofFloat(shadow[1], View.ALPHA, show ? 1.0f : 0.0f));
}
animatorSet.playTogether(animators);
animatorSet.setInterpolator(new DecelerateInterpolator());
animatorSet.setDuration(180);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (animation.equals(animatorSet)) {
if (!show) {
frameLayout2.setVisibility(View.INVISIBLE);
writeButtonContainer.setVisibility(View.INVISIBLE);
}
animatorSet = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (animation.equals(animatorSet)) {
animatorSet = null;
}
}
});
animatorSet.start();
return true;
}
public void updateSelectedCount(int animated) {
if (selectedDialogs.size() == 0) {
selectedCountView.setPivotX(0);
selectedCountView.setPivotY(0);
showCommentTextView(false);
} else {
selectedCountView.invalidate();
if (!showCommentTextView(true) && animated != 0) {
selectedCountView.setPivotX(dp(21));
selectedCountView.setPivotY(dp(12));
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(selectedCountView, View.SCALE_X, animated == 1 ? 1.1f : 0.9f, 1.0f),
ObjectAnimator.ofFloat(selectedCountView, View.SCALE_Y, animated == 1 ? 1.1f : 0.9f, 1.0f));
animatorSet.setInterpolator(new OvershootInterpolator());
animatorSet.setDuration(180);
animatorSet.start();
} else {
selectedCountView.setPivotX(0);
selectedCountView.setPivotY(0);
}
}
}
@Override
public void dismiss() {
if (commentTextView != null) {
AndroidUtilities.hideKeyboard(commentTextView.getEditText());
}
fullyShown = false;
super.dismiss();
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.dialogsNeedReload);
}
private class ShareDialogsAdapter extends RecyclerListView.SelectionAdapter {
private class MyStoryDialog extends TLRPC.Dialog {
{ id = Long.MAX_VALUE; }
}
private Context context;
private int currentCount;
private ArrayList<TLRPC.Dialog> dialogs = new ArrayList<>();
private LongSparseArray<TLRPC.Dialog> dialogsMap = new LongSparseArray<>();
public ShareDialogsAdapter(Context context) {
this.context = context;
fetchDialogs();
}
public void fetchDialogs() {
dialogs.clear();
dialogsMap.clear();
long selfUserId = UserConfig.getInstance(currentAccount).clientUserId;
if (includeStory) {
MyStoryDialog d = new MyStoryDialog();
dialogs.add(d);
dialogsMap.put(d.id, d);
}
if (!MessagesController.getInstance(currentAccount).dialogsForward.isEmpty()) {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogsForward.get(0);
dialogs.add(dialog);
dialogsMap.put(dialog.id, dialog);
}
ArrayList<TLRPC.Dialog> archivedDialogs = new ArrayList<>();
ArrayList<TLRPC.Dialog> allDialogs = MessagesController.getInstance(currentAccount).getAllDialogs();
for (int a = 0; a < allDialogs.size(); a++) {
TLRPC.Dialog dialog = allDialogs.get(a);
if (!(dialog instanceof TLRPC.TL_dialog)) {
continue;
}
if (dialog.id == selfUserId) {
continue;
}
if (!DialogObject.isEncryptedDialog(dialog.id)) {
if (DialogObject.isUserDialog(dialog.id)) {
if (dialog.folder_id == 1) {
archivedDialogs.add(dialog);
} else {
dialogs.add(dialog);
}
dialogsMap.put(dialog.id, dialog);
} else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialog.id);
if (!(chat == null || ChatObject.isNotInChat(chat) || chat.gigagroup && !ChatObject.hasAdminRights(chat) || ChatObject.isChannel(chat) && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) && !chat.megagroup)) {
if (dialog.folder_id == 1) {
archivedDialogs.add(dialog);
} else {
dialogs.add(dialog);
}
dialogsMap.put(dialog.id, dialog);
}
}
}
}
dialogs.addAll(archivedDialogs);
if (parentFragment != null) {
switch (parentFragment.shareAlertDebugMode) {
case ChatActivity.DEBUG_SHARE_ALERT_MODE_LESS:
List<TLRPC.Dialog> sublist = new ArrayList<>(dialogs.subList(0, Math.min(4, dialogs.size())));
dialogs.clear();
dialogs.addAll(sublist);
break;
case ChatActivity.DEBUG_SHARE_ALERT_MODE_MORE:
while (!dialogs.isEmpty() && dialogs.size() < 80) {
dialogs.add(dialogs.get(dialogs.size() - 1));
}
break;
}
}
notifyDataSetChanged();
}
@Override
public int getItemCount() {
int count = dialogs.size();
if (count != 0) {
count++;
}
return count;
}
public TLRPC.Dialog getItem(int position) {
position--;
if (position < 0 || position >= dialogs.size()) {
return null;
}
return dialogs.get(position);
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
if (holder.getItemViewType() == 1) {
return false;
}
return true;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 0: {
view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE, resourcesProvider) {
@Override
protected String repostToCustomName() {
if (includeStoryFromMessage) {
return LocaleController.getString(R.string.RepostToStory);
}
return super.repostToCustomName();
}
};
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, dp(100)));
break;
}
case 1:
default: {
view = new View(context);
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, dp(darkTheme && linkToCopy[1] != null ? 109 : 56)));
break;
}
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 0) {
ShareDialogCell cell = (ShareDialogCell) holder.itemView;
TLRPC.Dialog dialog = getItem(position);
if (dialog == null) return;
cell.setTopic(selectedDialogTopics.get(dialog), false);
cell.setDialog(dialog.id, selectedDialogs.indexOfKey(dialog.id) >= 0, null);
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 1;
}
return 0;
}
}
private class ShareTopicsAdapter extends RecyclerListView.SelectionAdapter {
private Context context;
private List<TLRPC.TL_forumTopic> topics;
public ShareTopicsAdapter(Context context) {
this.context = context;
}
@Override
public int getItemCount() {
return topics == null ? 0 : topics.size() + 1;
}
public TLRPC.TL_forumTopic getItem(int position) {
position--;
if (topics == null || position < 0 || position >= topics.size()) {
return null;
}
return topics.get(position);
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return holder.getItemViewType() != 1;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 0: {
view = new ShareTopicCell(context, resourcesProvider);
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, dp(100)));
break;
}
case 1:
default: {
view = new View(context);
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, ActionBar.getCurrentActionBarHeight()));
break;
}
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 0) {
ShareTopicCell cell = (ShareTopicCell) holder.itemView;
TLRPC.TL_forumTopic topic = getItem(position);
cell.setTopic(selectedTopicDialog, topic, selectedDialogs.indexOfKey(topic.id) >= 0, null);
}
}
@Override
public int getItemViewType(int position) {
return position == 0 ? 1 : 0;
}
}
public static class DialogSearchResult {
public TLRPC.Dialog dialog = new TLRPC.TL_dialog();
public TLObject object;
public int date;
public CharSequence name;
}
public class ShareSearchAdapter extends RecyclerListView.SelectionAdapter {
private Context context;
private ArrayList<Object> searchResult = new ArrayList<>();
private SearchAdapterHelper searchAdapterHelper;
private Runnable searchRunnable;
private Runnable searchRunnable2;
private String lastSearchText;
private int reqId;
private int lastReqId;
private int lastSearchId;
private int lastGlobalSearchId;
private int lastLocalSearchId;
int hintsCell = -1;
int resentTitleCell = -1;
int firstEmptyViewCell = -1;
int recentDialogsStartRow = -1;
int searchResultsStartRow = -1;
int lastFilledItem = -1;
int itemsCount;
DialogsSearchAdapter.CategoryAdapterRecycler categoryAdapter;
RecyclerView categoryListView;
public ShareSearchAdapter(Context context) {
this.context = context;
searchAdapterHelper = new SearchAdapterHelper(false) {
@Override
protected boolean filter(TLObject obj) {
return !(obj instanceof TLRPC.Chat) || ChatObject.canWriteToChat((TLRPC.Chat) obj);
}
};
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override
public void onDataSetChanged(int searchId) {
lastGlobalSearchId = searchId;
if (lastLocalSearchId != searchId) {
searchResult.clear();
}
int oldItemsCount = lastItemCont;
if (getItemCount() == 0 && !searchAdapterHelper.isSearchInProgress() && !internalDialogsIsSearching) {
searchEmptyView.showProgress(false, true);
} else {
recyclerItemsEnterAnimator.showItemsAnimated(oldItemsCount);
}
notifyDataSetChanged();
checkCurrentList(true);
}
@Override
public boolean canApplySearchResults(int searchId) {
return searchId == lastSearchId;
}
});
}
boolean internalDialogsIsSearching = false;
private void searchDialogsInternal(final String query, final int searchId) {
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
String search1 = query.trim().toLowerCase();
if (search1.length() == 0) {
lastSearchId = -1;
updateSearchResults(new ArrayList<>(), lastSearchId);
return;
}
String search2 = LocaleController.getInstance().getTranslitString(search1);
if (search1.equals(search2) || search2.length() == 0) {
search2 = null;
}
String[] search = new String[1 + (search2 != null ? 1 : 0)];
search[0] = search1;
if (search2 != null) {
search[1] = search2;
}
ArrayList<Long> usersToLoad = new ArrayList<>();
ArrayList<Long> chatsToLoad = new ArrayList<>();
int resultCount = 0;
LongSparseArray<DialogSearchResult> dialogsResult = new LongSparseArray<>();
SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM dialogs ORDER BY date DESC LIMIT 400");
while (cursor.next()) {
long id = cursor.longValue(0);
DialogSearchResult dialogSearchResult = new DialogSearchResult();
dialogSearchResult.date = cursor.intValue(1);
dialogsResult.put(id, dialogSearchResult);
if (DialogObject.isUserDialog(id)) {
if (!usersToLoad.contains(id)) {
usersToLoad.add(id);
}
} else if (DialogObject.isChatDialog(id)) {
if (!chatsToLoad.contains(-id)) {
chatsToLoad.add(-id);
}
}
}
cursor.dispose();
if (!usersToLoad.isEmpty()) {
cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, status, name FROM users WHERE uid IN(%s)", TextUtils.join(",", usersToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
username = name.substring(usernamePos + 3);
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
}
if (found != 0) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.User user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
DialogSearchResult dialogSearchResult = dialogsResult.get(user.id);
if (user.status != null) {
user.status.expires = cursor.intValue(1);
}
if (found == 1) {
dialogSearchResult.name = AndroidUtilities.generateSearchName(user.first_name, user.last_name, q);
} else {
dialogSearchResult.name = AndroidUtilities.generateSearchName("@" + UserObject.getPublicUsername(user), null, "@" + q);
}
dialogSearchResult.object = user;
dialogSearchResult.dialog.id = user.id;
resultCount++;
}
break;
}
}
}
cursor.dispose();
}
if (!chatsToLoad.isEmpty()) {
cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, name FROM chats WHERE uid IN(%s)", TextUtils.join(",", chatsToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(1);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
for (int a = 0; a < search.length; a++) {
String q = search[a];
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.Chat chat = TLRPC.Chat.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
if (!(chat == null || ChatObject.isNotInChat(chat) || ChatObject.isChannel(chat) && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) && !chat.megagroup)) {
DialogSearchResult dialogSearchResult = dialogsResult.get(-chat.id);
dialogSearchResult.name = AndroidUtilities.generateSearchName(chat.title, null, q);
dialogSearchResult.object = chat;
dialogSearchResult.dialog.id = -chat.id;
resultCount++;
}
}
break;
}
}
}
cursor.dispose();
}
ArrayList<Object> searchResults = new ArrayList<>(resultCount);
for (int a = 0; a < dialogsResult.size(); a++) {
DialogSearchResult dialogSearchResult = dialogsResult.valueAt(a);
if (dialogSearchResult.object != null && dialogSearchResult.name != null) {
searchResults.add(dialogSearchResult);
}
}
cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT u.data, u.status, u.name, u.uid FROM users as u INNER JOIN contacts as c ON u.uid = c.uid");
while (cursor.next()) {
long uid = cursor.longValue(3);
if (dialogsResult.indexOfKey(uid) >= 0) {
continue;
}
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
username = name.substring(usernamePos + 3);
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
}
if (found != 0) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.User user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
DialogSearchResult dialogSearchResult = new DialogSearchResult();
if (user.status != null) {
user.status.expires = cursor.intValue(1);
}
dialogSearchResult.dialog.id = user.id;
dialogSearchResult.object = user;
if (found == 1) {
dialogSearchResult.name = AndroidUtilities.generateSearchName(user.first_name, user.last_name, q);
} else {
dialogSearchResult.name = AndroidUtilities.generateSearchName("@" + UserObject.getPublicUsername(user), null, "@" + q);
}
searchResults.add(dialogSearchResult);
}
break;
}
}
}
cursor.dispose();
Collections.sort(searchResults, (lhs, rhs) -> {
DialogSearchResult res1 = (DialogSearchResult) lhs;
DialogSearchResult res2 = (DialogSearchResult) rhs;
if (res1.date < res2.date) {
return 1;
} else if (res1.date > res2.date) {
return -1;
}
return 0;
});
updateSearchResults(searchResults, searchId);
} catch (Exception e) {
FileLog.e(e);
}
});
}
private void updateSearchResults(final ArrayList<Object> result, final int searchId) {
AndroidUtilities.runOnUIThread(() -> {
if (searchId != lastSearchId) {
return;
}
int oldItemCount = getItemCount();
internalDialogsIsSearching = false;
lastLocalSearchId = searchId;
if (lastGlobalSearchId != searchId) {
searchAdapterHelper.clear();
}
if (gridView.getAdapter() != searchAdapter) {
topBeforeSwitch = getCurrentTop();
searchAdapter.notifyDataSetChanged();
}
for (int a = 0; a < result.size(); a++) {
DialogSearchResult obj = (DialogSearchResult) result.get(a);
if (obj.object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) obj.object;
MessagesController.getInstance(currentAccount).putUser(user, true);
} else if (obj.object instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) obj.object;
MessagesController.getInstance(currentAccount).putChat(chat, true);
}
}
boolean becomeEmpty = !searchResult.isEmpty() && result.isEmpty();
boolean isEmpty = searchResult.isEmpty() && result.isEmpty();
if (becomeEmpty) {
topBeforeSwitch = getCurrentTop();
}
searchResult = result;
searchAdapterHelper.mergeResults(searchResult, null);
int oldItemsCount = lastItemCont;
if (getItemCount() == 0 && !searchAdapterHelper.isSearchInProgress() && !internalDialogsIsSearching) {
searchEmptyView.showProgress(false, true);
} else {
recyclerItemsEnterAnimator.showItemsAnimated(oldItemsCount);
}
notifyDataSetChanged();
checkCurrentList(true);
});
}
public void searchDialogs(final String query) {
if (query != null && query.equals(lastSearchText)) {
return;
}
lastSearchText = query;
if (searchRunnable != null) {
Utilities.searchQueue.cancelRunnable(searchRunnable);
searchRunnable = null;
}
if (searchRunnable2 != null) {
AndroidUtilities.cancelRunOnUIThread(searchRunnable2);
searchRunnable2 = null;
}
searchResult.clear();
searchAdapterHelper.mergeResults(null);
searchAdapterHelper.queryServerSearch(null, true, true, true, true, false, 0, false, 0, 0);
notifyDataSetChanged();
checkCurrentList(true);
if (TextUtils.isEmpty(query)) {
topBeforeSwitch = getCurrentTop();
lastSearchId = -1;
internalDialogsIsSearching = false;
} else {
internalDialogsIsSearching = true;
final int searchId = ++lastSearchId;
searchEmptyView.showProgress(true, true);
Utilities.searchQueue.postRunnable(searchRunnable = () -> {
searchRunnable = null;
searchDialogsInternal(query, searchId);
AndroidUtilities.runOnUIThread(searchRunnable2 = () -> {
searchRunnable2 = null;
if (searchId != lastSearchId) {
return;
}
searchAdapterHelper.queryServerSearch(query, true, true, true, true, false, 0, false, 0, searchId);
});
}, 300);
}
checkCurrentList(false);
}
int lastItemCont;
@Override
public int getItemCount() {
itemsCount = 0;
hintsCell = -1;
resentTitleCell = -1;
recentDialogsStartRow = -1;
searchResultsStartRow = -1;
lastFilledItem = -1;
if (TextUtils.isEmpty(lastSearchText)) {
firstEmptyViewCell = itemsCount++;
hintsCell = itemsCount++;
if (recentSearchObjects.size() > 0) {
resentTitleCell = itemsCount++;
recentDialogsStartRow = itemsCount;
itemsCount += recentSearchObjects.size();
}
lastFilledItem = itemsCount++;
return lastItemCont = itemsCount;
} else {
firstEmptyViewCell = itemsCount++;
searchResultsStartRow = itemsCount;
itemsCount += (searchResult.size() + searchAdapterHelper.getLocalServerSearch().size());
if (itemsCount == 1) {
firstEmptyViewCell = -1;
return lastItemCont = itemsCount = 0;
}
lastFilledItem = itemsCount++;
}
return lastItemCont = itemsCount;
}
public TLRPC.Dialog getItem(int position) {
if (position >= recentDialogsStartRow && recentDialogsStartRow >= 0) {
int index = position - recentDialogsStartRow;
if (index < 0 || index >= recentSearchObjects.size()) {
return null;
}
DialogsSearchAdapter.RecentSearchObject recentSearchObject = recentSearchObjects.get(index);
TLObject object = recentSearchObject.object;
TLRPC.Dialog dialog = new TLRPC.TL_dialog();
if (object instanceof TLRPC.User) {
dialog.id = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Chat) {
dialog.id = -((TLRPC.Chat) object).id;
} else {
return null;
}
return dialog;
}
position--;
if (position < 0) {
return null;
}
if (position < searchResult.size()) {
return ((DialogSearchResult) searchResult.get(position)).dialog;
} else {
position -= searchResult.size();
}
ArrayList<TLObject> arrayList = searchAdapterHelper.getLocalServerSearch();
if (position < arrayList.size()) {
TLObject object = arrayList.get(position);
TLRPC.Dialog dialog = new TLRPC.TL_dialog();
if (object instanceof TLRPC.User) {
dialog.id = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Chat) {
dialog.id = -((TLRPC.Chat) object).id;
} else {
return null;
}
return dialog;
}
return null;
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
if (holder.getItemViewType() == 1 || holder.getItemViewType() == 4) {
return false;
}
return true;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 5: {
view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE, resourcesProvider);
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, dp(100)));
break;
}
case 0: {
view = new ProfileSearchCell(context, resourcesProvider).useCustomPaints().showPremiumBlock(true);
break;
}
default:
case 1: {
view = new View(context);
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, dp(darkTheme && linkToCopy[1] != null ? 109 : 56)));
break;
}
case 2: {
RecyclerListView horizontalListView = new RecyclerListView(context, resourcesProvider) {
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (getParent() != null && getParent().getParent() != null) {
getParent().getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(-1) || canScrollHorizontally(1));
}
return super.onInterceptTouchEvent(e);
}
};
categoryListView = horizontalListView;
horizontalListView.setItemAnimator(null);
horizontalListView.setLayoutAnimation(null);
LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
};
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalListView.setLayoutManager(layoutManager);
horizontalListView.setAdapter(categoryAdapter = new DialogsSearchAdapter.CategoryAdapterRecycler(context, currentAccount, true, true, resourcesProvider) {
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
HintDialogCell cell = (HintDialogCell) holder.itemView;
if (darkTheme || forceDarkThemeForHint) {
cell.setColors(Theme.key_voipgroup_nameText, Theme.key_voipgroup_inviteMembersBackground);
}
TLRPC.TL_topPeer peer = MediaDataController.getInstance(currentAccount).hints.get(position);
TLRPC.Chat chat = null;
TLRPC.User user = null;
long did = 0;
if (peer.peer.user_id != 0) {
did = peer.peer.user_id;
user = MessagesController.getInstance(currentAccount).getUser(peer.peer.user_id);
} else if (peer.peer.channel_id != 0) {
did = -peer.peer.channel_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.channel_id);
} else if (peer.peer.chat_id != 0) {
did = -peer.peer.chat_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.chat_id);
}
boolean animated = did == cell.getDialogId();
cell.setTag(did);
String name = "";
if (user != null) {
name = UserObject.getFirstName(user);
} else if (chat != null) {
name = chat.title;
}
cell.setDialog(did, true, name);
cell.setChecked(selectedDialogs.indexOfKey(did) >= 0, animated);
}
});
horizontalListView.setOnItemClickListener((view1, position) -> {
HintDialogCell cell = (HintDialogCell) view1;
TLRPC.TL_topPeer peer = MediaDataController.getInstance(currentAccount).hints.get(position);
TLRPC.Dialog dialog = new TLRPC.TL_dialog();
TLRPC.Chat chat = null;
TLRPC.User user = null;
long did = 0;
if (peer.peer.user_id != 0) {
did = peer.peer.user_id;
} else if (peer.peer.channel_id != 0) {
did = -peer.peer.channel_id;
} else if (peer.peer.chat_id != 0) {
did = -peer.peer.chat_id;
}
if (cell.isBlocked()) {
showPremiumBlockedToast(cell, did);
return;
}
dialog.id = did;
selectDialog(null, dialog);
cell.setChecked(selectedDialogs.indexOfKey(did) >= 0, true);
});
view = horizontalListView;
break;
}
case 3: {
GraySectionCell graySectionCell = new GraySectionCell(context, resourcesProvider);
graySectionCell.setTextColor(darkTheme ? Theme.key_voipgroup_nameText : Theme.key_graySectionText);
graySectionCell.setBackgroundColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_graySection));
graySectionCell.setText(LocaleController.getString("Recent", R.string.Recent));
view = graySectionCell;
break;
}
case 4: {
view = new View(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(searchLayoutManager.lastItemHeight, MeasureSpec.EXACTLY));
}
};
break;
}
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 0 || holder.getItemViewType() == 5) {
// ShareDialogCell cell = (ShareDialogCell) holder.itemView;
// ProfileSearchCell cell = (ProfileSearchCell) holder.itemView;
CharSequence name = null;
TLObject object = null;
TLRPC.EncryptedChat ec = null;
long id = 0;
if (TextUtils.isEmpty(lastSearchText)) {
if (recentDialogsStartRow >= 0 && position >= recentDialogsStartRow) {
int p = position - recentDialogsStartRow;
DialogsSearchAdapter.RecentSearchObject recentSearchObject = recentSearchObjects.get(p);
object = recentSearchObject.object;
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
id = user.id;
name = ContactsController.formatName(user.first_name, user.last_name);
} else if (object instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) object;
id = -chat.id;
name = chat.title;
} else if (object instanceof TLRPC.TL_encryptedChat) {
TLRPC.TL_encryptedChat chat = (TLRPC.TL_encryptedChat) object;
ec = chat;
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(chat.user_id);
if (user != null) {
id = user.id;
name = ContactsController.formatName(user.first_name, user.last_name);
}
}
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (!TextUtils.isEmpty(foundUserName)) {
int index;
if (name != null && (index = AndroidUtilities.indexOfIgnoreCase(name.toString(), foundUserName)) != -1) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(name);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder;
}
}
}
if (holder.itemView instanceof ProfileSearchCell) {
((ProfileSearchCell) holder.itemView).setData(object, ec, name, null, false, false);
((ProfileSearchCell) holder.itemView).useSeparator = position < getItemCount() - 2;
} else if (holder.itemView instanceof ShareDialogCell) {
((ShareDialogCell) holder.itemView).setDialog(id, selectedDialogs.indexOfKey(id) >= 0, name);
}
return;
}
position--;
if (position < searchResult.size()) {
DialogSearchResult result = (DialogSearchResult) searchResult.get(position);
id = result.dialog.id;
name = result.name;
} else {
position -= searchResult.size();
ArrayList<TLObject> arrayList = searchAdapterHelper.getLocalServerSearch();
object = arrayList.get(position);
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
id = user.id;
name = ContactsController.formatName(user.first_name, user.last_name);
} else {
TLRPC.Chat chat = (TLRPC.Chat) object;
id = -chat.id;
name = chat.title;
}
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (!TextUtils.isEmpty(foundUserName)) {
int index;
if (name != null && (index = AndroidUtilities.indexOfIgnoreCase(name.toString(), foundUserName)) != -1) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(name);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder;
}
}
}
if (holder.itemView instanceof ProfileSearchCell) {
((ProfileSearchCell) holder.itemView).setData(object, ec, name, null, false, false);
((ProfileSearchCell) holder.itemView).useSeparator = position < getItemCount() - 2;
} else if (holder.itemView instanceof ShareDialogCell) {
((ShareDialogCell) holder.itemView).setDialog(id, selectedDialogs.indexOfKey(id) >= 0, name);
}
} else if (holder.getItemViewType() == 2) {
((RecyclerListView) holder.itemView).getAdapter().notifyDataSetChanged();
}
}
@Override
public int getItemViewType(int position) {
if (position == lastFilledItem) {
return 4;
} else if (position == firstEmptyViewCell) {
return 1;
} else if (position == hintsCell) {
return 2;
} else if (position == resentTitleCell) {
return 3;
}
return TextUtils.isEmpty(lastSearchText) ? 0 : 5;
}
public boolean isSearching() {
return !TextUtils.isEmpty(lastSearchText);
}
public int getSpanSize(int spanCount, int position) {
if (position == hintsCell || position == resentTitleCell || position == firstEmptyViewCell || position == lastFilledItem) {
return spanCount;
}
final int viewType = getItemViewType(position);
if (viewType == 0) {
return spanCount;
}
return 1;
}
}
private boolean searchIsVisible;
private boolean searchWasVisibleBeforeTopics;
private void checkCurrentList(boolean force) {
boolean searchVisibleLocal = false;
if (!TextUtils.isEmpty(searchView.searchEditText.getText()) || (keyboardVisible && searchView.searchEditText.hasFocus()) || searchWasVisibleBeforeTopics) {
searchVisibleLocal = true;
updateSearchAdapter = true;
if (selectedTopicDialog == null) {
AndroidUtilities.updateViewVisibilityAnimated(gridView, false, 0.98f, true);
AndroidUtilities.updateViewVisibilityAnimated(searchGridView, true);
}
} else {
if (selectedTopicDialog == null) {
AndroidUtilities.updateViewVisibilityAnimated(gridView, true, 0.98f, true);
AndroidUtilities.updateViewVisibilityAnimated(searchGridView, false);
}
}
if (searchIsVisible != searchVisibleLocal || force) {
searchIsVisible = searchVisibleLocal;
searchAdapter.notifyDataSetChanged();
listAdapter.notifyDataSetChanged();
if (searchIsVisible) {
if (lastOffset == Integer.MAX_VALUE) {
((LinearLayoutManager) searchGridView.getLayoutManager()).scrollToPositionWithOffset(0, -searchGridView.getPaddingTop());
} else {
((LinearLayoutManager) searchGridView.getLayoutManager()).scrollToPositionWithOffset(0, lastOffset - searchGridView.getPaddingTop());
}
searchAdapter.searchDialogs(searchView.searchEditText.getText().toString());
} else {
if (lastOffset == Integer.MAX_VALUE) {
layoutManager.scrollToPositionWithOffset(0, 0);
} else {
layoutManager.scrollToPositionWithOffset(0, 0);
}
}
}
}
}
| DrKLO/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Components/ShareAlert.java |
45,278 | /*
* This is the source code of Telegram for Android v. 5.x.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedFloat;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.DotDividerSpan;
import org.telegram.ui.Components.FlickerLoadingView;
import org.telegram.ui.Components.LayoutHelper;
public class SessionCell extends FrameLayout {
private int currentType;
private TextView nameTextView;
private TextView onlineTextView;
private TextView detailTextView;
private TextView detailExTextView;
private BackupImageView placeholderImageView;
private BackupImageView imageView;
private AvatarDrawable avatarDrawable;
private boolean needDivider;
private boolean showStub;
private AnimatedFloat showStubValue = new AnimatedFloat(this);
FlickerLoadingView globalGradient;
LinearLayout linearLayout;
private int currentAccount = UserConfig.selectedAccount;
public SessionCell(Context context, int type) {
super(context);
linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setWeightSum(1);
currentType = type;
if (type == 1) {
addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 15 : 49), 11, (LocaleController.isRTL ? 49 : 15), 0));
avatarDrawable = new AvatarDrawable();
avatarDrawable.setTextSize(AndroidUtilities.dp(10));
imageView = new BackupImageView(context);
imageView.setRoundRadius(AndroidUtilities.dp(10));
addView(imageView, LayoutHelper.createFrame(20, 20, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 21), 13, (LocaleController.isRTL ? 21 : 0), 0));
} else {
placeholderImageView = new BackupImageView(context);
placeholderImageView.setRoundRadius(AndroidUtilities.dp(10));
addView(placeholderImageView, LayoutHelper.createFrame(42, 42, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 16), 9, (LocaleController.isRTL ? 16 : 0), 0));
imageView = new BackupImageView(context);
imageView.setRoundRadius(AndroidUtilities.dp(10));
addView(imageView, LayoutHelper.createFrame(42, 42, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 16), 9, (LocaleController.isRTL ? 16 : 0), 0));
addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 15 : 72), 6.333f, (LocaleController.isRTL ? 72 : 15), 0));
}
nameTextView = new TextView(context);
nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 15 : 16);
nameTextView.setLines(1);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
onlineTextView = new TextView(context);
onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 12 : 13);
onlineTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP);
if (LocaleController.isRTL) {
linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0));
linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.RIGHT | Gravity.TOP, 10, 0, 0, 0));
} else {
linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 10, 0));
linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 2, 0, 0));
}
int leftMargin;
int rightMargin;
if (LocaleController.isRTL) {
rightMargin = type == 0 ? 72 : 21;
leftMargin = 21;
} else {
leftMargin = type == 0 ? 72 : 21;
rightMargin = 21;
}
detailTextView = new TextView(context);
detailTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 13 : 14);
detailTextView.setLines(1);
detailTextView.setMaxLines(1);
detailTextView.setSingleLine(true);
detailTextView.setEllipsize(TextUtils.TruncateAt.END);
detailTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
addView(detailTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, leftMargin, type == 0 ? 28 : 36, rightMargin, 0));
detailExTextView = new TextView(context);
detailExTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3));
detailExTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, type == 0 ? 13 : 14);
detailExTextView.setLines(1);
detailExTextView.setMaxLines(1);
detailExTextView.setSingleLine(true);
detailExTextView.setEllipsize(TextUtils.TruncateAt.END);
detailExTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
addView(detailExTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, leftMargin, type == 0 ? 46 : 59, rightMargin, 0));
}
private void setContentAlpha(float alpha) {
if (detailExTextView != null) {
detailExTextView.setAlpha(alpha);
}
if (detailTextView != null) {
detailTextView.setAlpha(alpha);
}
if (nameTextView != null) {
nameTextView.setAlpha(alpha);
}
if (onlineTextView != null) {
onlineTextView.setAlpha(alpha);
}
if (imageView != null) {
imageView.setAlpha(alpha);
}
if (placeholderImageView != null) {
placeholderImageView.setAlpha(1f - alpha);
}
if (linearLayout != null) {
linearLayout.setAlpha(alpha);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentType == 0 ? 70 : 90) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY));
}
public void setSession(TLObject object, boolean divider) {
needDivider = divider;
if (object instanceof TLRPC.TL_authorization) {
TLRPC.TL_authorization session = (TLRPC.TL_authorization) object;
imageView.setImageDrawable(createDrawable(session));
StringBuilder stringBuilder = new StringBuilder();
if (session.device_model.length() != 0) {
stringBuilder.append(session.device_model);
}
if (stringBuilder.length() == 0) {
if (session.platform.length() != 0) {
stringBuilder.append(session.platform);
}
if (session.system_version.length() != 0) {
if (session.platform.length() != 0) {
stringBuilder.append(" ");
}
stringBuilder.append(session.system_version);
}
}
nameTextView.setText(stringBuilder);
String timeText;
if ((session.flags & 1) != 0) {
setTag(Theme.key_windowBackgroundWhiteValueText);
timeText = LocaleController.getString("Online", R.string.Online);
} else {
setTag(Theme.key_windowBackgroundWhiteGrayText3);
timeText = LocaleController.stringForMessageListDate(session.date_active);
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (session.country.length() != 0) {
spannableStringBuilder.append(session.country);
}
if (spannableStringBuilder.length() != 0) {
DotDividerSpan dotDividerSpan = new DotDividerSpan();
dotDividerSpan.setTopPadding(AndroidUtilities.dp(1.5f));
spannableStringBuilder.append(" . ").setSpan(dotDividerSpan, spannableStringBuilder.length() - 2, spannableStringBuilder.length() - 1, 0);
}
spannableStringBuilder.append(timeText);
detailExTextView.setText(spannableStringBuilder);
stringBuilder = new StringBuilder();
stringBuilder.append(session.app_name);
stringBuilder.append(" ").append(session.app_version);
detailTextView.setText(stringBuilder);
} else if (object instanceof TLRPC.TL_webAuthorization) {
TLRPC.TL_webAuthorization session = (TLRPC.TL_webAuthorization) object;
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(session.bot_id);
nameTextView.setText(session.domain);
String name;
if (user != null) {
avatarDrawable.setInfo(currentAccount, user);
name = UserObject.getFirstName(user);
imageView.setForUserOrChat(user, avatarDrawable);
} else {
name = "";
}
setTag(Theme.key_windowBackgroundWhiteGrayText3);
onlineTextView.setText(LocaleController.stringForMessageListDate(session.date_active));
onlineTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3));
StringBuilder stringBuilder = new StringBuilder();
if (session.ip.length() != 0) {
stringBuilder.append(session.ip);
}
if (session.region.length() != 0) {
if (stringBuilder.length() != 0) {
stringBuilder.append(" ");
}
stringBuilder.append("— ");
stringBuilder.append(session.region);
}
detailExTextView.setText(stringBuilder);
stringBuilder = new StringBuilder();
if (!TextUtils.isEmpty(name)) {
stringBuilder.append(name);
}
if (session.browser.length() != 0 ) {
if (stringBuilder.length() != 0) {
stringBuilder.append(", ");
}
stringBuilder.append(session.browser);
}
if (session.platform.length() != 0) {
if (stringBuilder.length() != 0) {
stringBuilder.append(", ");
}
stringBuilder.append(session.platform);
}
detailTextView.setText(stringBuilder);
}
if (showStub) {
showStub = false;
invalidate();
}
}
public static Drawable createDrawable(TLRPC.TL_authorization session) {
String platform = session.platform.toLowerCase();
if (platform.isEmpty()) {
platform = session.system_version.toLowerCase();
}
String deviceModel = session.device_model.toLowerCase();
int iconId;
int colorKey, colorKey2;
if (deviceModel.contains("safari")) {
iconId = R.drawable.device_web_safari;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (deviceModel.contains("edge")) {
iconId = R.drawable.device_web_edge;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (deviceModel.contains("chrome")) {
iconId = R.drawable.device_web_chrome;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (deviceModel.contains("opera")) {
iconId = R.drawable.device_web_opera;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (deviceModel.contains("firefox")) {
iconId = R.drawable.device_web_firefox;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (deviceModel.contains("vivaldi")) {
iconId = R.drawable.device_web_other;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
} else if (platform.contains("ios")) {
iconId = deviceModel.contains("ipad") ? R.drawable.device_tablet_ios : R.drawable.device_phone_ios;
colorKey = Theme.key_avatar_backgroundBlue;
colorKey2 = Theme.key_avatar_background2Blue;
} else if (platform.contains("windows")) {
iconId = R.drawable.device_desktop_win;
colorKey = Theme.key_avatar_backgroundCyan;
colorKey2 = Theme.key_avatar_background2Cyan;
} else if (platform.contains("macos")) {
iconId = R.drawable.device_desktop_osx;
colorKey = Theme.key_avatar_backgroundCyan;
colorKey2 = Theme.key_avatar_background2Cyan;
} else if (platform.contains("android")) {
iconId = deviceModel.contains("tab") ? R.drawable.device_tablet_android : R.drawable.device_phone_android;
colorKey = Theme.key_avatar_backgroundGreen;
colorKey2 = Theme.key_avatar_background2Green;
} else {
if (session.app_name.toLowerCase().contains("desktop")) {
iconId = R.drawable.device_desktop_other;
colorKey = Theme.key_avatar_backgroundCyan;
colorKey2 = Theme.key_avatar_background2Cyan;
} else {
iconId = R.drawable.device_web_other;
colorKey = Theme.key_avatar_backgroundPink;
colorKey2 = Theme.key_avatar_background2Pink;
}
}
Drawable iconDrawable = ContextCompat.getDrawable(ApplicationLoader.applicationContext, iconId).mutate();
iconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_avatar_text), PorterDuff.Mode.SRC_IN));
Drawable bgDrawable = new CircleGradientDrawable(AndroidUtilities.dp(42), Theme.getColor(colorKey), Theme.getColor(colorKey2));
CombinedDrawable combinedDrawable = new CombinedDrawable(bgDrawable, iconDrawable);
return combinedDrawable;
}
public static class CircleGradientDrawable extends Drawable {
private Paint paint;
private int size, colorTop, colorBottom;
public CircleGradientDrawable(int size, int colorTop, int colorBottom) {
this.size = size;
this.colorTop = colorTop;
this.colorBottom = colorBottom;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShader(new LinearGradient(0, 0, 0, size, new int[] {colorTop, colorBottom}, new float[] {0, 1}, Shader.TileMode.CLAMP));
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawCircle(getBounds().centerX(), getBounds().centerY(), Math.min(getBounds().width(), getBounds().height()) / 2f, paint);
}
@Override
public void setAlpha(int i) {
paint.setAlpha(i);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
@Override
public int getIntrinsicHeight() {
return size;
}
@Override
public int getIntrinsicWidth() {
return size;
}
}
@Override
protected void onDraw(Canvas canvas) {
float stubAlpha = showStubValue.set(showStub ? 1 : 0);
setContentAlpha(1f - stubAlpha);
if (stubAlpha > 0 && globalGradient != null) {
if (stubAlpha < 1f) {
AndroidUtilities.rectTmp.set(0, 0, getWidth(), getHeight());
canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * stubAlpha), Canvas.ALL_SAVE_FLAG);
}
globalGradient.updateColors();
globalGradient.updateGradient();
if (getParent() != null) {
View parent = (View) getParent();
globalGradient.setParentSize(parent.getMeasuredWidth(), parent.getMeasuredHeight(), -getX());
}
float y = linearLayout.getTop() + nameTextView.getTop() + AndroidUtilities.dp(12);
float x = linearLayout.getX();
AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.2f, y + AndroidUtilities.dp(4));
canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint());
y = linearLayout.getTop() + detailTextView.getTop() - AndroidUtilities.dp(1);
x = linearLayout.getX();
AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.4f, y + AndroidUtilities.dp(4));
canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint());
y = linearLayout.getTop() + detailExTextView.getTop() - AndroidUtilities.dp(1);
x = linearLayout.getX();
AndroidUtilities.rectTmp.set(x, y - AndroidUtilities.dp(4), x + getMeasuredWidth() * 0.3f, y + AndroidUtilities.dp(4));
canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), globalGradient.getPaint());
invalidate();
if (stubAlpha < 1f) {
canvas.restore();
}
}
if (needDivider) {
int margin = currentType == 1 ? 49 : 72;
canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(margin), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(margin) : 0), getMeasuredHeight() - 1, Theme.dividerPaint);
}
}
public void showStub(FlickerLoadingView globalGradient) {
this.globalGradient = globalGradient;
showStub = true;
Drawable iconDrawable = ContextCompat.getDrawable(ApplicationLoader.applicationContext, AndroidUtilities.isTablet() ? R.drawable.device_tablet_android : R.drawable.device_phone_android).mutate();
iconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_avatar_text), PorterDuff.Mode.SRC_IN));
CombinedDrawable combinedDrawable = new CombinedDrawable(Theme.createCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_avatar_backgroundGreen)), iconDrawable);
if (placeholderImageView != null) {
placeholderImageView.setImageDrawable(combinedDrawable);
} else {
imageView.setImageDrawable(combinedDrawable);
}
invalidate();
}
public boolean isStub() {
return showStub;
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Cells/SessionCell.java |
45,279 | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 com.dianping.cat.message.codec;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import io.netty.buffer.ByteBuf;
import org.unidal.helper.Splitters;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.spi.MessageTree;
public class WaterfallMessageCodec {
public static final String ID = "waterfall";
private static final String VERSION = "WF2"; // Waterfall version 2
private BufferWriter m_writer = new HtmlEncodingBufferWriter();
private BufferHelper m_bufferHelper = new BufferHelper(m_writer);
private String[] m_colors = { "#0066ff", "#006699", "#006633", "#0033ff", "#003399", "#003333" };
protected int calculateLines(Transaction t) {
int count = 1;
for (Message child : t.getChildren()) {
if (child instanceof Transaction) {
count += calculateLines((Transaction) child);
} else if (child instanceof Event) {
if (child.getType().equals("RemoteCall")) {
count++;
}
}
}
return count;
}
public void encode(MessageTree tree, ByteBuf buf) {
Message message = tree.getMessage();
if (message instanceof Transaction) {
int count = 0;
int index = buf.writerIndex();
BufferHelper helper = m_bufferHelper;
Transaction t = (Transaction) message;
Locator locator = new Locator();
Ruler ruler = new Ruler((int) t.getDurationInMicros());
ruler.setWidth(1400);
ruler.setHeight(18 * calculateLines(t) + 10);
ruler.setOffsetX(200);
ruler.setOffsetY(10);
buf.writeInt(0); // place-holder
count += helper.table1(buf);
count += helper.crlf(buf);
count += encodeHeader(tree, buf, ruler);
count += encodeRuler(buf, locator, ruler);
count += encodeTransaction(tree, t, buf, locator, ruler);
count += encodeFooter(tree, buf);
count += helper.table2(buf);
buf.setInt(index, count);
}
}
protected int encodeFooter(MessageTree tree, ByteBuf buf) {
BufferHelper helper = m_bufferHelper;
XmlBuilder b = new XmlBuilder();
StringBuilder sb = b.getResult();
b.tag2("g");
b.tag2("svg");
sb.append("</td></tr>");
return helper.write(buf, sb.toString());
}
protected int encodeHeader(MessageTree tree, ByteBuf buf, Ruler ruler) {
BufferHelper helper = m_bufferHelper;
XmlBuilder b = new XmlBuilder();
StringBuilder sb = b.getResult();
sb.append("<tr class=\"header\"><td>");
sb.append(VERSION).append(" ").append(tree.getDomain()).append(" ");
sb.append(tree.getHostName()).append(" ").append(tree.getIpAddress()).append(" ");
sb.append(tree.getThreadGroupName()).append(" ").append(tree.getThreadId()).append(" ");
sb.append(tree.getThreadName()).append(" ").append(tree.getMessageId()).append(" ");
sb.append(tree.getParentMessageId()).append(" ").append(tree.getRootMessageId()).append(" ");
sb.append(tree.getSessionToken()).append(" ");
sb.append("</td></tr>");
sb.append("<tr><td>");
int height = ruler.getHeight();
int width = ruler.getWidth();
b.add("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\r\n");
b.tag1("svg", "x", 0, "y", 0, "width", width, "height", height, "viewBox", "0,0," + width + "," + height, "xmlns",
"http://www.w3.org/2000/svg", "version", "1.1");
b.tag1("g", "font-size", "12", "stroke", "gray");
return helper.write(buf, sb.toString());
}
protected int encodeRemoteCall(MessageTree tree, Event event, ByteBuf buf, Locator locator, Ruler ruler) {
int count = 0;
locator.downLevel(true);
locator.nextLine();
count += encodeRemoteCallLine(tree, event, buf, locator, ruler);
locator.upLevel();
return count;
}
protected int encodeRemoteCallLine(MessageTree tree, Event event, ByteBuf buf, Locator locator, Ruler ruler) {
BufferHelper helper = m_bufferHelper;
XmlBuilder b = new XmlBuilder();
StringBuilder sb = b.getResult();
int width = 6;
int height = 18;
int x = 0;
int y = locator.getLine() * height + ruler.getOffsetY();
String logviewId = String.valueOf(event.getData());
b.branch(locator, x, y, width, height);
x += locator.getLevel() * width;
b.tagWithText("text", "<a href='#'>[:: show ::]</a>", "x", x + 2, "y", y - 5, "font-size", "16", "stroke-width", "0",
"fill", "blue", "onclick", "popup('" + logviewId + "');");
return helper.write(buf, sb.toString());
}
protected int encodeRuler(ByteBuf buf, Locator locator, Ruler ruler) {
BufferHelper helper = m_bufferHelper;
XmlBuilder b = new XmlBuilder();
StringBuilder sb = b.getResult();
PathBuilder p = new PathBuilder();
int height = ruler.getHeight();
b.tag1("g", "id", "ruler", "font-size", "12", "text-anchor", "middle", "stroke", "black", "stroke-width", "1");
int unitNum = ruler.getUnitNum();
int unitStep = ruler.getUnitStep();
int unit = (int) ruler.getUnit();
int x = ruler.getOffsetX();
int y = 10;
for (int i = 0; i <= unitNum; i++) {
String text;
if (unitStep >= 1000) {
text = (i * unitStep / 1000) + "ms";
} else {
text = (i * unitStep) + "us";
}
b.tagWithText("text", text, "x", x + i * unit, "y", y, "stroke-width", "0");
}
for (int i = 0; i <= unitNum; i++) {
b.tag("path", "d", p.moveTo(x + i * unit, y + 6).v(height).build(), "stroke-dasharray", "3,4");
}
b.tag2("g");
return helper.write(buf, sb.toString());
}
protected int encodeTransaction(MessageTree tree, Transaction transaction, ByteBuf buf, Locator locator, Ruler ruler) {
List<Message> children = getVisibleChildren(transaction);
int count = 0;
locator.downLevel(children.isEmpty());
locator.nextLine();
count += encodeTransactionLine(tree, transaction, buf, locator, ruler);
int len = children.size();
for (int i = 0; i < len; i++) {
Message child = children.get(i);
locator.setLast(i == len - 1);
if (child instanceof Transaction) {
count += encodeTransaction(tree, (Transaction) child, buf, locator, ruler);
} else if (child instanceof Event && "RemoteCall".equals(child.getType())) {
count += encodeRemoteCall(tree, (Event) child, buf, locator, ruler);
}
}
locator.upLevel();
return count;
}
protected int encodeTransactionLine(MessageTree tree, Transaction t, ByteBuf buf, Locator locator, Ruler ruler) {
BufferHelper helper = m_bufferHelper;
XmlBuilder b = new XmlBuilder();
int width = 6;
int height = 18;
int x = 0;
int y = locator.getLine() * height + ruler.getOffsetY();
String tid = "t" + locator.getLine();
long t0 = tree.getMessage().getTimestamp();
long t1 = t.getTimestamp();
int rx = ruler.calcX((t1 - t0) * 1000);
int rw = ruler.calcWidth(t.getDurationInMicros() * 1000);
int[] segments = getTransactionDurationSegments(t);
b.branch(locator, x, y, width, height);
x += locator.getLevel() * width;
if (t.getStatus().equals("0")) {
b.tag1("text", "x", x, "y", y - 5, "font-weight", "bold", "stroke-width", "0");
} else {
b.tag1("text", "x", x, "y", y - 5, "font-weight", "bold", "stroke-width", "0", "fill", "red");
}
b.add(t.getType()).newLine();
b.tag("set", "attributeName", "fill", "to", "red", "begin", tid + ".mouseover", "end", tid + ".mouseout");
b.tag2("text");
if (segments == null) {
String durationInMillis = String.format("%.2f %s", t.getDurationInMicros() / 1000.0, t.getName());
b.tag("rect", "x", rx + 1, "y", y - 15, "width", rw, "height", height - 2, "fill", "#0066ff", "opacity", "0.5");
b.tagWithText("text", durationInMillis, "x", rx + 5, "y", y - 3, "font-size", "11", "stroke-width", "0");
} else {
int index = 0;
for (int segment : segments) {
int w = ruler.calcWidth(segment);
String durationInMillis = String.format("%.2f %s", segment / 1000.0 / 1000.0, index == 0 ? t.getName() : "");
String color = m_colors[index % m_colors.length];
b.tag("rect", "x", rx + 1, "y", y - 15, "width", w, "height", height - 2, "fill", color, "opacity", "0.5");
b.tagWithText("text", durationInMillis, "x", rx + 5, "y", y - 3, "font-size", "11", "stroke-width", "0");
index++;
rx += w;
}
}
b.tag("rect", "id", tid, "x", ruler.getOffsetX() + 1, "y", y - 15, "width", ruler.getWidth(), "height", height,
"fill", "#ffffff", "stroke-width", "0", "opacity", "0.01");
return helper.write(buf, b.getResult().toString());
}
private int[] getTransactionDurationSegments(Transaction t) {
String data = t.getData().toString();
if (data.startsWith("_m=")) {
int pos = data.indexOf('&');
String str;
if (pos < 0) {
str = data.substring(3);
} else {
str = data.substring(3, pos);
}
List<String> parts = Splitters.by(',').split(str);
int len = parts.size();
int[] segments = new int[len];
for (int i = 0; i < len; i++) {
String part = parts.get(i);
try {
segments[i] = Integer.parseInt(part) * 1000;
} catch (Exception e) {
// ignore it
}
}
return segments;
} else if (data.startsWith("_u=")) {
int pos = data.indexOf('&');
String str;
if (pos < 0) {
str = data.substring(3);
} else {
str = data.substring(3, pos);
}
List<String> parts = Splitters.by(',').split(str);
int len = parts.size();
int[] segments = new int[len];
for (int i = 0; i < len; i++) {
String part = parts.get(i);
try {
segments[i] = Integer.parseInt(part);
} catch (Exception e) {
// ignore it
}
}
return segments;
} else {
return null;
}
}
protected List<Message> getVisibleChildren(Transaction parent) {
List<Message> children = new ArrayList<Message>();
for (Message child : parent.getChildren()) {
if (child instanceof Transaction) {
children.add(child);
} else if (child instanceof Event && "RemoteCall".equals(child.getType())) {
children.add(child);
}
}
return children;
}
public void setBufferWriter(BufferWriter writer) {
m_writer = writer;
m_bufferHelper = new BufferHelper(m_writer);
}
protected static class BufferHelper {
private static byte[] TABLE1 = "<table class=\"logview\">".getBytes();
private static byte[] TABLE2 = "</table>".getBytes();
private static byte[] TR1 = "<tr>".getBytes();
private static byte[] TR2 = "</tr>".getBytes();
private static byte[] TD1 = "<td>".getBytes();
private static byte[] TD2 = "</td>".getBytes();
private static byte[] NBSP = " ".getBytes();
private static byte[] CRLF = "\r\n".getBytes();
private BufferWriter m_writer;
public BufferHelper(BufferWriter writer) {
m_writer = writer;
}
public int crlf(ByteBuf buf) {
buf.writeBytes(CRLF);
return CRLF.length;
}
public int nbsp(ByteBuf buf, int count) {
for (int i = 0; i < count; i++) {
buf.writeBytes(NBSP);
}
return count * NBSP.length;
}
public int table1(ByteBuf buf) {
buf.writeBytes(TABLE1);
return TABLE1.length;
}
public int table2(ByteBuf buf) {
buf.writeBytes(TABLE2);
return TABLE2.length;
}
public int td(ByteBuf buf, String str) {
return td(buf, str, null);
}
public int td(ByteBuf buf, String str, String attributes) {
if (str == null) {
str = "null";
}
byte[] data = str.getBytes();
int count = 0;
if (attributes == null) {
buf.writeBytes(TD1);
count += TD1.length;
} else {
String tag = "<td " + attributes + ">";
byte[] bytes = tag.getBytes();
buf.writeBytes(bytes);
count += bytes.length;
}
buf.writeBytes(data);
count += data.length;
buf.writeBytes(TD2);
count += TD2.length;
return count;
}
public int td1(ByteBuf buf) {
buf.writeBytes(TD1);
return TD1.length;
}
public int td1(ByteBuf buf, String attributes) {
if (attributes == null) {
buf.writeBytes(TD1);
return TD1.length;
} else {
String tag = "<td " + attributes + ">";
byte[] bytes = tag.getBytes();
buf.writeBytes(bytes);
return bytes.length;
}
}
public int td2(ByteBuf buf) {
buf.writeBytes(TD2);
return TD2.length;
}
public int tr1(ByteBuf buf, String styleClass) {
if (styleClass == null) {
buf.writeBytes(TR1);
return TR1.length;
} else {
String tag = "<tr class=\"" + styleClass + "\">";
byte[] bytes = tag.getBytes();
buf.writeBytes(bytes);
return bytes.length;
}
}
public int tr2(ByteBuf buf) {
buf.writeBytes(TR2);
return TR2.length;
}
public int write(ByteBuf buf, byte b) {
buf.writeByte(b);
return 1;
}
public int write(ByteBuf buf, String str) {
if (str == null) {
str = "null";
}
byte[] data = str.getBytes();
buf.writeBytes(data);
return data.length;
}
public int writeRaw(ByteBuf buf, String str) {
if (str == null) {
str = "null";
}
byte[] data;
try {
data = str.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
data = str.getBytes();
}
return m_writer.writeTo(buf, data);
}
}
protected static class Locator {
private int m_level;
private int m_line;
private Stack<Boolean> m_last = new Stack<Boolean>();
private Stack<Integer> m_flags = new Stack<Integer>();
public void downLevel(boolean atomic) {
if (m_level > 0) {
boolean last = m_last.peek();
m_flags.pop();
if (last) {
m_flags.push(6); // 00110
} else {
m_flags.push(22); // 10110
}
for (int i = 0; i < m_level - 1; i++) {
Integer flag = m_flags.get(i);
int f = flag;
if (flag == 6) { // 00110
f = 0; // 00000
} else if (flag == 22) { // 10110
f = 20; // 10100
}
m_flags.set(i, f);
}
}
boolean root = m_level == 0;
if (atomic) {
if (root) {
m_flags.push(1); // 00001
} else {
m_flags.push(9); // 01001
}
} else {
if (root) {
m_flags.push(17); // 10001
} else {
m_flags.push(25); // 11001
}
}
m_last.push(root ? true : false);
m_level++;
}
public Stack<Integer> getFlags() {
return m_flags;
}
public boolean getLast(int level) {
return m_last.get(level);
}
public int getLevel() {
return m_level;
}
public int getLine() {
return m_line;
}
public boolean isFirst() {
return m_level == 1;
}
public boolean isLast() {
return m_last.peek();
}
public void setLast(boolean last) {
m_last.pop();
m_last.push(last);
}
public void nextLine() {
m_line++;
}
@Override
public String toString() {
return String.format("Locator[level=%s, line=%s, first=%s, last=%s]", m_level, m_line, isFirst(), isLast());
}
public void upLevel() {
m_level--;
m_last.pop();
m_flags.pop();
}
}
protected static class PathBuilder {
private int m_marker;
private StringBuilder m_sb = new StringBuilder(64);
public String build() {
String result = m_sb.toString();
m_sb.setLength(0);
return result;
}
public PathBuilder h(int deltaX) {
m_sb.append(" h").append(deltaX);
return this;
}
public PathBuilder m(int deltaX, int deltaY) {
m_sb.append(" m").append(deltaX).append(',').append(deltaY);
return this;
}
public PathBuilder mark() {
m_marker = m_sb.length();
return this;
}
public PathBuilder moveTo(int x, int y) {
m_sb.append('M').append(x).append(',').append(y);
return this;
}
public PathBuilder repeat(int count) {
int pos = m_sb.length();
for (int i = 0; i < count; i++) {
m_sb.append(m_sb.subSequence(m_marker, pos));
}
return this;
}
public PathBuilder v(int deltaY) {
m_sb.append(" v").append(deltaY);
return this;
}
}
protected static class Ruler {
private static final int[] UNITS = { 1, 2, 3, 5 };
public int m_width;
private int m_maxValue;
private int m_unitNum;
private int m_unitStep;
private int m_height;
private int m_offsetX;
private int m_offsetY;
public Ruler(int maxValue) {
m_maxValue = maxValue;
int e = 1;
int value = maxValue;
while (true) {
if (value > 50) {
value = (value + 9) / 10;
e *= 10;
} else {
if (value < 6) {
m_unitNum = value;
m_unitStep = e;
} else {
for (int unit : UNITS) {
int num = (value + unit - 1) / unit;
if (num >= 6 && num <= 10) {
m_unitNum = num;
m_unitStep = unit * e;
break;
}
}
}
break;
}
}
}
public int calcWidth(long timeInMicros) {
int w = (int) (timeInMicros * getUnit() / m_unitStep / 1000);
if (w == 0 && timeInMicros > 0) {
w = 1;
}
return w;
}
public int calcX(long timeInMillis) {
int w = (int) (timeInMillis * getUnit() / m_unitStep);
if (w == 0 && timeInMillis > 0) {
w = 1;
}
return w + m_offsetX;
}
public int getHeight() {
return m_height;
}
public void setHeight(int height) {
m_height = height;
}
public int getMaxValue() {
return m_maxValue;
}
public int getOffsetX() {
return m_offsetX;
}
public void setOffsetX(int offsetX) {
m_offsetX = offsetX;
}
public int getOffsetY() {
return m_offsetY;
}
public void setOffsetY(int offsetY) {
m_offsetY = offsetY;
}
public double getUnit() {
return (m_width - m_offsetX - 20) * 1.0 / m_unitNum;
}
public int getUnitNum() {
return m_unitNum;
}
public int getUnitStep() {
return m_unitStep;
}
public int getWidth() {
return m_width;
}
public void setWidth(int width) {
m_width = width;
}
@Override
public String toString() {
return String.format("[%s, %s, %s]", m_maxValue, m_unitNum, m_unitStep);
}
}
protected static class XmlBuilder {
private boolean m_compact;
private int m_level;
private StringBuilder m_sb = new StringBuilder(8192);
public XmlBuilder add(String text) {
m_sb.append(text);
return this;
}
public void branch(Locator locator, int x, int y, int width, int height) {
PathBuilder p = new PathBuilder();
int w = width / 2;
int h = height / 2;
int r = 2;
for (Integer flag : locator.getFlags()) {
int cx = x + w;
int cy = y - h;
if ((flag & 2) != 0) { // 00010
tag("path", "d", p.moveTo(cx, cy).h(w).build());
}
if ((flag & 4) != 0) { // 00100
tag("path", "d", p.moveTo(cx, cy).v(-h).build());
}
if ((flag & 8) != 0) { // 01000
tag("path", "d", p.moveTo(cx, cy).h(-w).build());
}
if ((flag & 16) != 0) { // 10000
tag("path", "d", p.moveTo(cx, cy).v(h).build());
}
if ((flag & 1) != 0) { // 00001
m_sb.append("<circle cx=\"").append(cx).append("\" cy=\"").append(cy).append("\" r=\"").append(r)
.append("\" stroke=\"red\" fill=\"white\"/>");
}
x += width;
}
}
public XmlBuilder element(String name, String value) {
indent();
m_sb.append('<').append(name).append('>');
m_sb.append(value);
m_sb.append("</").append(name).append(">");
newLine();
return this;
}
public StringBuilder getResult() {
return m_sb;
}
public XmlBuilder indent() {
if (!m_compact) {
for (int i = m_level - 1; i >= 0; i--) {
m_sb.append(" ");
}
}
return this;
}
public XmlBuilder newLine() {
m_sb.append("\r\n");
return this;
}
public XmlBuilder tag(String name, Object... attributes) {
return tagWithText(name, null, attributes);
}
public XmlBuilder tag1(String name, Object... attributes) {
indent();
m_sb.append('<').append(name);
int len = attributes.length;
for (int i = 0; i < len; i += 2) {
Object key = attributes[i];
Object val = attributes[i + 1];
if (val != null) {
m_sb.append(' ').append(key).append("=\"").append(val).append('"');
}
}
m_sb.append(">");
newLine();
m_level++;
return this;
}
public XmlBuilder tag2(String name) {
m_level--;
indent();
m_sb.append("</").append(name).append(">");
newLine();
return this;
}
public XmlBuilder tagWithText(String name, Object text, Object... attributes) {
indent();
m_sb.append('<').append(name);
int len = attributes.length;
for (int i = 0; i < len; i += 2) {
Object key = attributes[i];
Object val = attributes[i + 1];
if (val != null) {
m_sb.append(' ').append(key).append("=\"").append(val).append('"');
}
}
if (text == null) {
m_sb.append("/>");
} else {
m_sb.append('>').append(text).append("</").append(name).append('>');
}
newLine();
return this;
}
}
}
| dianping/cat | cat-core/src/main/java/com/dianping/cat/message/codec/WaterfallMessageCodec.java |
45,280 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Components;
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.LongSparseArray;
import android.util.Property;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.ColorUtils;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.FloatValueHolder;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.AnimationNotificationsLocker;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.DocumentObject;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.VideoEditedInfo;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.ActionBarMenuSubItem;
import org.telegram.ui.ActionBar.ActionBarPopupWindow;
import org.telegram.ui.ActionBar.AdjustPanLayoutHelper;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.BottomSheet;
import org.telegram.ui.ActionBar.INavigationLayout;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.BasePermissionsActivity;
import org.telegram.ui.Business.ChatAttachAlertQuickRepliesLayout;
import org.telegram.ui.Business.QuickRepliesController;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PassportActivity;
import org.telegram.ui.PaymentFormActivity;
import org.telegram.ui.PhotoPickerActivity;
import org.telegram.ui.PhotoPickerSearchActivity;
import org.telegram.ui.PhotoViewer;
import org.telegram.ui.PremiumPreviewFragment;
import org.telegram.ui.Stories.recorder.StoryEntry;
import org.telegram.ui.WebAppDisclaimerAlert;
import org.telegram.ui.bots.BotWebViewContainer;
import org.telegram.ui.bots.BotWebViewMenuContainer;
import org.telegram.ui.bots.ChatAttachAlertBotWebViewLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class ChatAttachAlert extends BottomSheet implements NotificationCenter.NotificationCenterDelegate, BottomSheet.BottomSheetDelegateInterface {
public ChatActivity.ThemeDelegate parentThemeDelegate;
private final NumberTextView captionLimitView;
public boolean forUser;
public boolean isPhotoPicker;
public boolean isStickerMode;
public Utilities.Callback2<String, TLRPC.InputDocument> customStickerHandler;
private int currentLimit;
private int codepointCount;
public boolean canOpenPreview = false;
private boolean isSoundPicker = false;
public boolean isStoryLocationPicker = false;
public boolean isBizLocationPicker = false;
public boolean isStoryAudioPicker = false;
private ImageUpdater.AvatarFor setAvatarFor;
public boolean pinnedToTop;
private PasscodeView passcodeView;
private ChatAttachRestrictedLayout restrictedLayout;
public ImageUpdater parentImageUpdater;
public boolean destroyed;
public boolean allowEnterCaption;
private ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate documentsDelegate;
public long dialogId;
private boolean overrideBackgroundColor;
public TLRPC.Chat getChat() {
if (baseFragment instanceof ChatActivity) {
return ((ChatActivity) baseFragment).getCurrentChat();
} else {
return MessagesController.getInstance(currentAccount).getChat(-dialogId);
}
}
public void setCanOpenPreview(boolean canOpenPreview) {
this.canOpenPreview = canOpenPreview;
selectedArrowImageView.setVisibility(canOpenPreview && avatarPicker != 2 ? View.VISIBLE : View.GONE);
}
public float getClipLayoutBottom() {
float alphaOffset = (frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(84)) * (1f - frameLayout2.getAlpha());
return frameLayout2.getMeasuredHeight() - alphaOffset;
}
public void showBotLayout(long id, boolean animated) {
showBotLayout(id, null, false, animated);
}
public void showBotLayout(long id, String startCommand, boolean justAdded, boolean animated) {
if (botAttachLayouts.get(id) == null || !Objects.equals(startCommand, botAttachLayouts.get(id).getStartCommand()) || botAttachLayouts.get(id).needReload()) {
if (baseFragment instanceof ChatActivity) {
ChatAttachAlertBotWebViewLayout webViewLayout = new ChatAttachAlertBotWebViewLayout(this, getContext(), resourcesProvider);
botAttachLayouts.put(id, webViewLayout);
botAttachLayouts.get(id).setDelegate(new BotWebViewContainer.Delegate() {
private ValueAnimator botButtonAnimator;
@Override
public void onWebAppSetupClosingBehavior(boolean needConfirmation) {
webViewLayout.setNeedCloseConfirmation(needConfirmation);
}
@Override
public void onCloseRequested(Runnable callback) {
if (currentAttachLayout != webViewLayout) {
return;
}
ChatAttachAlert.this.setFocusable(false);
ChatAttachAlert.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
dismiss();
AndroidUtilities.runOnUIThread(() -> {
if (callback != null) {
callback.run();
}
}, 150);
}
@Override
public void onWebAppSetActionBarColor(int color, boolean isOverrideColor) {
int from = ((ColorDrawable) actionBar.getBackground()).getColor();
int to = color;
BotWebViewMenuContainer.ActionBarColorsAnimating actionBarColorsAnimating = new BotWebViewMenuContainer.ActionBarColorsAnimating();
actionBarColorsAnimating.setFrom(overrideBackgroundColor ? from : 0, resourcesProvider);
overrideBackgroundColor = isOverrideColor;
// actionBarIsLight = ColorUtils.calculateLuminance(color) < 0.5f;
actionBarColorsAnimating.setTo(overrideBackgroundColor ? to : 0, resourcesProvider);
ValueAnimator animator = ValueAnimator.ofFloat(0, 1).setDuration(200);
animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
animator.addUpdateListener(animation -> {
float progress = (float) animation.getAnimatedValue();
actionBar.setBackgroundColor(ColorUtils.blendARGB(from, to, progress));
webViewLayout.setCustomActionBarBackground(ColorUtils.blendARGB(from, to, progress));
currentAttachLayout.invalidate();
sizeNotifierFrameLayout.invalidate();
actionBarColorsAnimating.updateActionBar(actionBar, progress);
});
animator.start();
}
@Override
public void onWebAppSetBackgroundColor(int color) {
webViewLayout.setCustomBackground(color);
}
@Override
public void onWebAppOpenInvoice(String slug, TLObject response) {
BaseFragment parentFragment = baseFragment;
PaymentFormActivity paymentFormActivity = null;
if (response instanceof TLRPC.TL_payments_paymentForm) {
TLRPC.TL_payments_paymentForm form = (TLRPC.TL_payments_paymentForm) response;
MessagesController.getInstance(currentAccount).putUsers(form.users, false);
paymentFormActivity = new PaymentFormActivity(form, slug, parentFragment);
} else if (response instanceof TLRPC.TL_payments_paymentReceipt) {
paymentFormActivity = new PaymentFormActivity((TLRPC.TL_payments_paymentReceipt) response);
}
if (paymentFormActivity != null) {
webViewLayout.scrollToTop();
AndroidUtilities.hideKeyboard(webViewLayout);
OverlayActionBarLayoutDialog overlayActionBarLayoutDialog = new OverlayActionBarLayoutDialog(parentFragment.getParentActivity(), resourcesProvider);
overlayActionBarLayoutDialog.show();
paymentFormActivity.setPaymentFormCallback(status -> {
if (status != PaymentFormActivity.InvoiceStatus.PENDING) {
overlayActionBarLayoutDialog.dismiss();
}
webViewLayout.getWebViewContainer().onInvoiceStatusUpdate(slug, status.name().toLowerCase(Locale.ROOT));
});
paymentFormActivity.setResourcesProvider(resourcesProvider);
overlayActionBarLayoutDialog.addFragment(paymentFormActivity);
}
}
@Override
public void onWebAppExpand() {
if (currentAttachLayout != webViewLayout) {
return;
}
if (webViewLayout.canExpandByRequest()) {
webViewLayout.scrollToTop();
}
}
@Override
public void onWebAppSwitchInlineQuery(TLRPC.User botUser, String query, List<String> chatTypes) {
if (chatTypes.isEmpty()) {
if (baseFragment instanceof ChatActivity) {
((ChatActivity) baseFragment).getChatActivityEnterView().setFieldText("@" + UserObject.getPublicUsername(botUser) + " " + query);
}
dismiss(true);
} else {
Bundle args = new Bundle();
args.putInt("dialogsType", DialogsActivity.DIALOGS_TYPE_START_ATTACH_BOT);
args.putBoolean("onlySelect", true);
args.putBoolean("allowGroups", chatTypes.contains("groups"));
args.putBoolean("allowLegacyGroups", chatTypes.contains("groups"));
args.putBoolean("allowMegagroups", chatTypes.contains("groups"));
args.putBoolean("allowUsers", chatTypes.contains("users"));
args.putBoolean("allowChannels", chatTypes.contains("channels"));
args.putBoolean("allowBots", chatTypes.contains("bots"));
DialogsActivity dialogsActivity = new DialogsActivity(args);
OverlayActionBarLayoutDialog overlayActionBarLayoutDialog = new OverlayActionBarLayoutDialog(getContext(), resourcesProvider);
dialogsActivity.setDelegate((fragment, dids, message1, param, topicsFragment) -> {
long did = dids.get(0).dialogId;
Bundle args1 = new Bundle();
args1.putBoolean("scrollToTopOnResume", true);
if (DialogObject.isEncryptedDialog(did)) {
args1.putInt("enc_id", DialogObject.getEncryptedChatId(did));
} else if (DialogObject.isUserDialog(did)) {
args1.putLong("user_id", did);
} else {
args1.putLong("chat_id", -did);
}
args1.putString("start_text", "@" + UserObject.getPublicUsername(botUser) + " " + query);
BaseFragment lastFragment = baseFragment;
if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args1, lastFragment)) {
overlayActionBarLayoutDialog.dismiss();
dismiss(true);
lastFragment.presentFragment(new INavigationLayout.NavigationParams(new ChatActivity(args1)).setRemoveLast(true));
}
return true;
});
overlayActionBarLayoutDialog.show();
overlayActionBarLayoutDialog.addFragment(dialogsActivity);
}
}
@Override
public void onSetupMainButton(boolean isVisible, boolean isActive, String text, int color, int textColor, boolean isProgressVisible) {
if (currentAttachLayout != webViewLayout || !webViewLayout.isBotButtonAvailable() && startCommand == null) {
return;
}
botMainButtonTextView.setClickable(isActive);
botMainButtonTextView.setText(text);
botMainButtonTextView.setTextColor(textColor);
botMainButtonTextView.setBackground(BotWebViewContainer.getMainButtonRippleDrawable(color));
if (botButtonWasVisible != isVisible) {
botButtonWasVisible = isVisible;
if (botButtonAnimator != null) {
botButtonAnimator.cancel();
}
botButtonAnimator = ValueAnimator.ofFloat(isVisible ? 0 : 1, isVisible ? 1 : 0).setDuration(250);
botButtonAnimator.addUpdateListener(animation -> {
float value = (float) animation.getAnimatedValue();
buttonsRecyclerView.setAlpha(1f - value);
botMainButtonTextView.setAlpha(value);
botMainButtonOffsetY = value * AndroidUtilities.dp(36);
shadow.setTranslationY(botMainButtonOffsetY);
buttonsRecyclerView.setTranslationY(botMainButtonOffsetY);
});
botButtonAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
if (isVisible) {
botMainButtonTextView.setAlpha(0f);
botMainButtonTextView.setVisibility(View.VISIBLE);
int offsetY = AndroidUtilities.dp(36);
for (int i = 0; i < botAttachLayouts.size(); i++) {
botAttachLayouts.valueAt(i).setMeasureOffsetY(offsetY);
}
} else {
buttonsRecyclerView.setAlpha(0f);
buttonsRecyclerView.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (!isVisible) {
botMainButtonTextView.setVisibility(View.GONE);
} else {
buttonsRecyclerView.setVisibility(View.GONE);
}
int offsetY = isVisible ? AndroidUtilities.dp(36) : 0;
for (int i = 0; i < botAttachLayouts.size(); i++) {
botAttachLayouts.valueAt(i).setMeasureOffsetY(offsetY);
}
if (botButtonAnimator == animation) {
botButtonAnimator = null;
}
}
});
botButtonAnimator.start();
}
botProgressView.setProgressColor(textColor);
if (botButtonProgressWasVisible != isProgressVisible) {
botProgressView.animate().cancel();
if (isProgressVisible) {
botProgressView.setAlpha(0f);
botProgressView.setVisibility(View.VISIBLE);
}
botProgressView.animate().alpha(isProgressVisible ? 1f : 0f)
.scaleX(isProgressVisible ? 1f : 0.1f)
.scaleY(isProgressVisible ? 1f : 0.1f)
.setDuration(250)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
botButtonProgressWasVisible = isProgressVisible;
if (!isProgressVisible) {
botProgressView.setVisibility(View.GONE);
}
}
}).start();
}
}
@Override
public void onSetBackButtonVisible(boolean visible) {
AndroidUtilities.updateImageViewImageAnimated(actionBar.getBackButton(), visible ? R.drawable.ic_ab_back : R.drawable.ic_close_white);
}
@Override
public void onSetSettingsButtonVisible(boolean visible) {
if (webViewLayout.settingsItem != null) {
webViewLayout.settingsItem.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
@Override
public boolean isClipboardAvailable() {
return MediaDataController.getInstance(currentAccount).botInAttachMenu(id);
}
});
MessageObject replyingObject = ((ChatActivity) baseFragment).getChatActivityEnterView().getReplyingMessageObject();
botAttachLayouts.get(id).requestWebView(currentAccount, ((ChatActivity) baseFragment).getDialogId(), id, false, replyingObject != null ? replyingObject.messageOwner.id : 0, startCommand);
}
}
if (botAttachLayouts.get(id) != null) {
botAttachLayouts.get(id).disallowSwipeOffsetAnimation();
showLayout(botAttachLayouts.get(id), -id, animated);
if (justAdded) {
botAttachLayouts.get(id).showJustAddedBulletin();
}
}
}
public boolean checkCaption(CharSequence text) {
if (baseFragment instanceof ChatActivity) {
long dialogId = ((ChatActivity) baseFragment).getDialogId();
return ChatActivityEnterView.checkPremiumAnimatedEmoji(currentAccount, dialogId, baseFragment, sizeNotifierFrameLayout, text);
} else {
return false;
}
}
public void avatarFor(ImageUpdater.AvatarFor avatarFor) {
setAvatarFor = avatarFor;
}
public ImageUpdater.AvatarFor getAvatarFor() {
return setAvatarFor;
}
public void setImageUpdater(ImageUpdater imageUpdater) {
parentImageUpdater = imageUpdater;
}
public void setupPhotoPicker(String title) {
avatarPicker = 1;
isPhotoPicker = true;
avatarSearch = false;
typeButtonsAvailable = false;
videosEnabled = false;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
selectedTextView.setText(title);
if (photoLayout != null) {
photoLayout.updateAvatarPicker();
}
}
public void presentFragment(PhotoPickerActivity fragment) {
if (baseFragment != null) {
baseFragment.presentFragment(fragment);
} else {
BaseFragment lastFragment = LaunchActivity.getLastFragment();
if (lastFragment != null) {
lastFragment.presentFragment(fragment);
}
}
}
public void setDialogId(long dialogId) {
this.dialogId = dialogId;
}
public interface ChatAttachViewDelegate {
default boolean selectItemOnClicking() {
return false;
}
void didPressedButton(int button, boolean arg, boolean notify, int scheduleDate, boolean forceDocument);
default void onCameraOpened() {
}
default View getRevealView() {
return null;
}
default void didSelectBot(TLRPC.User user) {
}
default boolean needEnterComment() {
return false;
}
default void doOnIdle(Runnable runnable) {
runnable.run();
}
default void openAvatarsSearch() {
}
default void onWallpaperSelected(Object object) {
}
default void sendAudio(ArrayList<MessageObject> audios, CharSequence caption, boolean notify, int scheduleDate) {
}
}
public float translationProgress = 0;
public final Property<AttachAlertLayout, Float> ATTACH_ALERT_LAYOUT_TRANSLATION = new AnimationProperties.FloatProperty<AttachAlertLayout>("translation") {
@Override
public void setValue(AttachAlertLayout object, float value) {
translationProgress = value;
if (nextAttachLayout == null) {
return;
}
if (nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview || currentAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview) {
int width = Math.max(nextAttachLayout.getWidth(), currentAttachLayout.getWidth());
if (nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview) {
currentAttachLayout.setTranslationX(value * -width);
nextAttachLayout.setTranslationX((1f - value) * width);
} else {
currentAttachLayout.setTranslationX(value * width);
nextAttachLayout.setTranslationX(-width * (1f - value));
}
} else {
if (value > 0.7f) {
float alpha = 1.0f - (1.0f - value) / 0.3f;
if (nextAttachLayout == locationLayout) {
currentAttachLayout.setAlpha(1.0f - alpha);
nextAttachLayout.setAlpha(1.0f);
} else {
nextAttachLayout.setAlpha(alpha);
nextAttachLayout.onHideShowProgress(alpha);
}
} else {
if (nextAttachLayout == locationLayout) {
nextAttachLayout.setAlpha(0.0f);
}
}
if (nextAttachLayout == pollLayout || currentAttachLayout == pollLayout) {
updateSelectedPosition(nextAttachLayout == pollLayout ? 1 : 0);
}
nextAttachLayout.setTranslationY(AndroidUtilities.dp(78) * value);
currentAttachLayout.onHideShowProgress(1.0f - Math.min(1.0f, value / 0.7f));
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
}
if (viewChangeAnimator != null) {
updateSelectedPosition(1);
}
containerView.invalidate();
}
@Override
public Float get(AttachAlertLayout object) {
return translationProgress;
}
};
public static class AttachAlertLayout extends FrameLayout {
protected final Theme.ResourcesProvider resourcesProvider;
protected ChatAttachAlert parentAlert;
public AttachAlertLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.resourcesProvider = resourcesProvider;
parentAlert = alert;
}
public boolean onSheetKeyDown(int keyCode, KeyEvent event) {
return false;
}
public boolean onDismiss() {
return false;
}
public boolean onCustomMeasure(View view, int width, int height) {
return false;
}
public boolean onCustomLayout(View view, int left, int top, int right, int bottom) {
return false;
}
public boolean onContainerViewTouchEvent(MotionEvent event) {
return false;
}
public void onPreMeasure(int availableWidth, int availableHeight) {
}
public void onMenuItemClick(int id) {
}
public boolean hasCustomBackground() {
return false;
}
public int getCustomBackground() {
return 0;
}
public boolean hasCustomActionBarBackground() {
return false;
}
public int getCustomActionBarBackground() {
return 0;
}
public void onButtonsTranslationYUpdated() {
}
public boolean canScheduleMessages() {
return true;
}
public void checkColors() {
}
public ArrayList<ThemeDescription> getThemeDescriptions() {
return null;
}
public void onPause() {
}
public void onResume() {
}
public boolean onDismissWithTouchOutside() {
return true;
}
public boolean canDismissWithTouchOutside() {
return true;
}
public void onDismissWithButtonClick(int item) {
}
public void onContainerTranslationUpdated(float currentPanTranslationY) {
}
public void onHideShowProgress(float progress) {
}
public void onOpenAnimationEnd() {
}
public void onInit(boolean hasVideo, boolean hasPhoto, boolean hasDocuments) {
}
public int getSelectedItemsCount() {
return 0;
}
public void onSelectedItemsCountChanged(int count) {
}
public void applyCaption(CharSequence text) {
}
public void onDestroy() {
}
public void onHide() {
}
public void onHidden() {
}
public int getCurrentItemTop() {
return 0;
}
public int getFirstOffset() {
return 0;
}
public int getButtonsHideOffset() {
return AndroidUtilities.dp(needsActionBar() != 0 ? 12 : 17);
}
public int getListTopPadding() {
return 0;
}
public int needsActionBar() {
return 0;
}
public void sendSelectedItems(boolean notify, int scheduleDate) {
}
public void onShow(AttachAlertLayout previousLayout) {
}
public void onShown() {
}
public void scrollToTop() {
}
public boolean onBackPressed() {
return false;
}
public int getThemedColor(int key) {
return Theme.getColor(key, resourcesProvider);
}
public boolean shouldHideBottomButtons() {
return true;
}
public void onPanTransitionStart(boolean keyboardVisible, int contentHeight) {
}
public void onPanTransitionEnd() {
}
}
@Nullable
public final BaseFragment baseFragment;
public boolean inBubbleMode;
private ActionBarPopupWindow sendPopupWindow;
private ActionBarPopupWindow.ActionBarPopupWindowLayout sendPopupLayout;
private ActionBarMenuSubItem[] itemCells;
private View shadow;
private ChatAttachAlertPhotoLayout photoLayout;
private ChatAttachAlertContactsLayout contactsLayout;
private ChatAttachAlertAudioLayout audioLayout;
private ChatAttachAlertPollLayout pollLayout;
private ChatAttachAlertLocationLayout locationLayout;
private ChatAttachAlertDocumentLayout documentLayout;
private ChatAttachAlertPhotoLayoutPreview photoPreviewLayout;
public ChatAttachAlertColorsLayout colorsLayout;
private ChatAttachAlertQuickRepliesLayout quickRepliesLayout;
private AttachAlertLayout[] layouts = new AttachAlertLayout[8];
private LongSparseArray<ChatAttachAlertBotWebViewLayout> botAttachLayouts = new LongSparseArray<>();
private AttachAlertLayout currentAttachLayout;
private AttachAlertLayout nextAttachLayout;
private FrameLayout frameLayout2;
public EditTextEmoji commentTextView;
private int[] commentTextViewLocation = new int[2];
private FrameLayout writeButtonContainer;
private ImageView writeButton;
private Drawable writeButtonDrawable;
private View selectedCountView;
private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
private RectF rect = new RectF();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private AnimatorSet commentsAnimator;
protected int avatarPicker;
protected boolean avatarSearch;
protected boolean typeButtonsAvailable;
private boolean stories;
boolean sendButtonEnabled = true;
private float sendButtonEnabledProgress = 1f;
private ValueAnimator sendButtonColorAnimator;
private long selectedId;
protected float cornerRadius = 1.0f;
public ActionBar actionBar;
private View actionBarShadow;
private AnimatorSet actionBarAnimation;
private AnimatorSet menuAnimator;
protected ActionBarMenuItem selectedMenuItem;
@Nullable
protected ActionBarMenuItem searchItem;
protected ActionBarMenuItem doneItem;
protected FrameLayout headerView;
protected TextView selectedTextView;
protected ActionBarMenuItem optionsItem;
protected LinearLayout selectedView;
protected ImageView selectedArrowImageView;
protected LinearLayout mediaPreviewView;
protected TextView mediaPreviewTextView;
private float baseSelectedTextViewTranslationY;
private boolean menuShowed;
public SizeNotifierFrameLayout sizeNotifierFrameLayout;
private boolean openTransitionFinished;
private Object viewChangeAnimator;
private boolean enterCommentEventSent;
protected RecyclerListView buttonsRecyclerView;
private LinearLayoutManager buttonsLayoutManager;
private ButtonsAdapter buttonsAdapter;
private boolean botButtonProgressWasVisible = false;
private RadialProgressView botProgressView;
private boolean botButtonWasVisible = false;
private TextView botMainButtonTextView;
private float botMainButtonOffsetY;
protected MessageObject editingMessageObject;
private boolean buttonPressed;
public final int currentAccount = UserConfig.selectedAccount;
private boolean documentsEnabled = true;
private boolean photosEnabled = true;
private boolean videosEnabled = true;
private boolean musicEnabled = true;
private boolean pollsEnabled = true;
private boolean plainTextEnabled = true;
protected int maxSelectedPhotos = -1;
protected boolean allowOrder = true;
protected boolean openWithFrontFaceCamera;
private float captionEditTextTopOffset;
private float chatActivityEnterViewAnimateFromTop;
private ValueAnimator topBackgroundAnimator;
private int attachItemSize = AndroidUtilities.dp(85);
private DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
protected ChatAttachViewDelegate delegate;
public int[] scrollOffsetY = new int[2];
private int previousScrollOffsetY;
private float fromScrollY;
private float toScrollY;
protected boolean paused;
private final Paint attachButtonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float bottomPannelTranslation;
private final boolean forceDarkTheme;
private final boolean showingFromDialog;
protected boolean captionLimitBulletinShown = false;
private class AttachButton extends FrameLayout {
private TextView textView;
private RLottieImageView imageView;
private boolean checked;
private int backgroundKey;
private int textKey;
private float checkedState;
private Animator checkAnimator;
private int currentId;
public AttachButton(Context context) {
super(context);
setWillNotDraw(false);
setFocusable(true);
imageView = new RLottieImageView(context) {
@Override
public void setScaleX(float scaleX) {
super.setScaleX(scaleX);
AttachButton.this.invalidate();
}
};
imageView.setScaleType(ImageView.ScaleType.CENTER);
addView(imageView, LayoutHelper.createFrame(32, 32, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 18, 0, 0));
textView = new TextView(context);
textView.setMaxLines(2);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setTextColor(getThemedColor(Theme.key_dialogTextGray2));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
textView.setLineSpacing(-AndroidUtilities.dp(2), 1.0f);
textView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 62, 0, 0));
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setText(textView.getText());
info.setEnabled(true);
info.setSelected(checked);
}
void updateCheckedState(boolean animate) {
if (checked == (currentId == selectedId)) {
return;
}
checked = currentId == selectedId;
if (checkAnimator != null) {
checkAnimator.cancel();
}
if (animate) {
if (checked) {
imageView.setProgress(0.0f);
imageView.playAnimation();
}
checkAnimator = ObjectAnimator.ofFloat(this, "checkedState", checked ? 1f : 0f);
checkAnimator.setDuration(200);
checkAnimator.start();
} else {
imageView.stopAnimation();
imageView.setProgress(0.0f);
setCheckedState(checked ? 1f : 0f);
}
}
@Keep
public void setCheckedState(float state) {
checkedState = state;
imageView.setScaleX(1.0f - 0.06f * state);
imageView.setScaleY(1.0f - 0.06f * state);
textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(textKey), checkedState));
invalidate();
}
@Keep
public float getCheckedState() {
return checkedState;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
updateCheckedState(false);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(attachItemSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(84), MeasureSpec.EXACTLY));
}
public void setTextAndIcon(int id, CharSequence text, RLottieDrawable drawable, int background, int textColor) {
currentId = id;
textView.setText(text);
imageView.setAnimation(drawable);
backgroundKey = background;
textKey = textColor;
textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(textKey), checkedState));
}
public void setTextAndIcon(int id, CharSequence text, Drawable drawable, int background, int textColor) {
currentId = id;
textView.setText(text);
imageView.setImageDrawable(drawable);
backgroundKey = background;
textKey = textColor;
textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(textKey), checkedState));
}
@Override
protected void onDraw(Canvas canvas) {
float scale = imageView.getScaleX() + 0.06f * checkedState;
float radius = AndroidUtilities.dp(23) * scale;
float cx = imageView.getLeft() + imageView.getMeasuredWidth() / 2f;
float cy = imageView.getTop() + imageView.getMeasuredWidth() / 2f;
attachButtonPaint.setColor(getThemedColor(backgroundKey));
attachButtonPaint.setStyle(Paint.Style.STROKE);
attachButtonPaint.setStrokeWidth(AndroidUtilities.dp(3) * scale);
attachButtonPaint.setAlpha(Math.round(255f * checkedState));
canvas.drawCircle(cx, cy, radius - 0.5f * attachButtonPaint.getStrokeWidth(), attachButtonPaint);
attachButtonPaint.setAlpha(255);
attachButtonPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(cx, cy, radius - AndroidUtilities.dp(5) * checkedState, attachButtonPaint);
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
}
private class AttachBotButton extends FrameLayout {
private BackupImageView imageView;
private TextView nameTextView;
private AvatarDrawable avatarDrawable = new AvatarDrawable();
private TLRPC.User currentUser;
private TLRPC.TL_attachMenuBot attachMenuBot;
private float checkedState;
private Boolean checked;
private ValueAnimator checkAnimator;
private int textColor;
private int iconBackgroundColor;
private View selector;
public AttachBotButton(Context context) {
super(context);
setWillNotDraw(false);
setFocusable(true);
setFocusableInTouchMode(true);
imageView = new BackupImageView(context) {
{
imageReceiver.setDelegate((imageReceiver1, set, thumb, memCache) -> {
Drawable drawable = imageReceiver1.getDrawable();
if (drawable instanceof RLottieDrawable) {
((RLottieDrawable) drawable).setCustomEndFrame(0);
((RLottieDrawable) drawable).stop();
((RLottieDrawable) drawable).setProgress(0, false);
}
});
}
@Override
public void setScaleX(float scaleX) {
super.setScaleX(scaleX);
AttachBotButton.this.invalidate();
}
};
imageView.setRoundRadius(AndroidUtilities.dp(25));
addView(imageView, LayoutHelper.createFrame(46, 46, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 9, 0, 0));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
selector = new View(context);
selector.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 1, AndroidUtilities.dp(23)));
addView(selector, LayoutHelper.createFrame(46, 46, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 9, 0, 0));
}
nameTextView = new TextView(context);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
nameTextView.setLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 6, 60, 6, 0));
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setEnabled(true);
if (selector != null && checked) {
info.setCheckable(true);
info.setChecked(true);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(attachItemSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(100), MeasureSpec.EXACTLY));
}
public void setCheckedState(float state) {
checkedState = state;
imageView.setScaleX(1.0f - 0.06f * state);
imageView.setScaleY(1.0f - 0.06f * state);
nameTextView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), textColor, checkedState));
invalidate();
}
private void updateMargins() {
MarginLayoutParams params = (MarginLayoutParams) nameTextView.getLayoutParams();
params.topMargin = AndroidUtilities.dp(attachMenuBot != null ? 62 : 60);
params = (MarginLayoutParams) imageView.getLayoutParams();
params.topMargin = AndroidUtilities.dp(attachMenuBot != null ? 11 : 9);
}
@Override
protected void onDraw(Canvas canvas) {
if (attachMenuBot != null) {
float imageScale = imageView.getScaleX();
float scale = imageScale + 0.06f * checkedState;
float radius = AndroidUtilities.dp(23) * scale;
float cx = imageView.getLeft() + imageView.getMeasuredWidth() / 2f;
float cy = imageView.getTop() + imageView.getMeasuredWidth() / 2f;
attachButtonPaint.setColor(iconBackgroundColor);
attachButtonPaint.setStyle(Paint.Style.STROKE);
attachButtonPaint.setStrokeWidth(AndroidUtilities.dp(3) * scale);
attachButtonPaint.setAlpha(Math.round(255f * checkedState));
canvas.drawCircle(cx, cy, radius - 0.5f * attachButtonPaint.getStrokeWidth(), attachButtonPaint);
attachButtonPaint.setAlpha(255);
attachButtonPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(cx, cy, radius - AndroidUtilities.dp(5) * checkedState, attachButtonPaint);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
updateCheckedState(false);
}
void updateCheckedState(boolean animate) {
boolean newChecked = attachMenuBot != null && -currentUser.id == selectedId;
if (checked != null && checked == newChecked && animate) {
return;
}
checked = newChecked;
if (checkAnimator != null) {
checkAnimator.cancel();
}
RLottieDrawable drawable = imageView.getImageReceiver().getLottieAnimation();
if (animate) {
if (checked && drawable != null) {
drawable.setAutoRepeat(0);
drawable.setCustomEndFrame(-1);
drawable.setProgress(0, false);
drawable.start();
}
checkAnimator = ValueAnimator.ofFloat(checked ? 0f : 1f, checked ? 1f : 0f);
checkAnimator.addUpdateListener(animation -> setCheckedState((float) animation.getAnimatedValue()));
checkAnimator.setDuration(200);
checkAnimator.start();
} else {
if (drawable != null) {
drawable.stop();
drawable.setProgress(0, false);
}
setCheckedState(checked ? 1f : 0f);
}
}
public void setUser(TLRPC.User user) {
if (user == null) {
return;
}
nameTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray2));
currentUser = user;
nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name));
avatarDrawable.setInfo(currentAccount, user);
imageView.setForUserOrChat(user, avatarDrawable);
imageView.setSize(-1, -1);
imageView.setColorFilter(null);
attachMenuBot = null;
selector.setVisibility(VISIBLE);
updateMargins();
setCheckedState(0f);
invalidate();
}
public void setAttachBot(TLRPC.User user, TLRPC.TL_attachMenuBot bot) {
if (user == null || bot == null) {
return;
}
nameTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray2));
currentUser = user;
nameTextView.setText(bot.short_name);
avatarDrawable.setInfo(currentAccount, user);
boolean animated = true;
TLRPC.TL_attachMenuBotIcon icon = MediaDataController.getAnimatedAttachMenuBotIcon(bot);
if (icon == null) {
icon = MediaDataController.getStaticAttachMenuBotIcon(bot);
animated = false;
}
if (icon != null) {
textColor = getThemedColor(Theme.key_chat_attachContactText);
iconBackgroundColor = getThemedColor(Theme.key_chat_attachContactBackground);
for (TLRPC.TL_attachMenuBotIconColor color : icon.colors) {
switch (color.name) {
case MediaDataController.ATTACH_MENU_BOT_COLOR_LIGHT_ICON:
if (!Theme.getCurrentTheme().isDark()) {
iconBackgroundColor = color.color;
}
break;
case MediaDataController.ATTACH_MENU_BOT_COLOR_LIGHT_TEXT:
if (!Theme.getCurrentTheme().isDark()) {
textColor = color.color;
}
break;
case MediaDataController.ATTACH_MENU_BOT_COLOR_DARK_ICON:
if (Theme.getCurrentTheme().isDark()) {
iconBackgroundColor = color.color;
}
break;
case MediaDataController.ATTACH_MENU_BOT_COLOR_DARK_TEXT:
if (Theme.getCurrentTheme().isDark()) {
textColor = color.color;
}
break;
}
}
textColor = ColorUtils.setAlphaComponent(textColor, 0xFF);
iconBackgroundColor = ColorUtils.setAlphaComponent(iconBackgroundColor, 0xFF);
TLRPC.Document iconDoc = icon.icon;
imageView.getImageReceiver().setAllowStartLottieAnimation(false);
imageView.setImage(ImageLocation.getForDocument(iconDoc), String.valueOf(bot.bot_id), animated ? "tgs" : "svg", DocumentObject.getSvgThumb(iconDoc, Theme.key_windowBackgroundGray, 1f), bot);
}
imageView.setSize(AndroidUtilities.dp(28), AndroidUtilities.dp(28));
imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_attachIcon), PorterDuff.Mode.SRC_IN));
attachMenuBot = bot;
selector.setVisibility(GONE);
updateMargins();
setCheckedState(0f);
invalidate();
}
}
private ArrayList<android.graphics.Rect> exclusionRects = new ArrayList<>();
private android.graphics.Rect exclustionRect = new Rect();
float currentPanTranslationY;
public ChatAttachAlert(Context context, final BaseFragment parentFragment, boolean forceDarkTheme, boolean showingFromDialog) {
this(context, parentFragment, forceDarkTheme, showingFromDialog, true, null);
}
@SuppressLint("ClickableViewAccessibility")
public ChatAttachAlert(Context context, final @Nullable BaseFragment parentFragment, boolean forceDarkTheme, boolean showingFromDialog, boolean needCamera, Theme.ResourcesProvider resourcesProvider) {
super(context, false, resourcesProvider);
if (parentFragment instanceof ChatActivity) {
setImageReceiverNumLevel(0, 4);
}
this.forceDarkTheme = forceDarkTheme;
this.showingFromDialog = showingFromDialog;
drawNavigationBar = true;
inBubbleMode = parentFragment instanceof ChatActivity && parentFragment.isInBubbleMode();
openInterpolator = new OvershootInterpolator(0.7f);
baseFragment = parentFragment;
useSmoothKeyboard = true;
setDelegate(this);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.reloadInlineHints);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.attachMenuBotsDidLoad);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.currentUserPremiumStatusChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.quickRepliesUpdated);
exclusionRects.add(exclustionRect);
sizeNotifierFrameLayout = new SizeNotifierFrameLayout(context) {
private Bulletin.Delegate bulletinDelegate = new Bulletin.Delegate() {
@Override
public int getBottomOffset(int tag) {
return getHeight() - frameLayout2.getTop() + AndroidUtilities.dp(52);
}
};
private int lastNotifyWidth;
private RectF rect = new RectF();
private boolean ignoreLayout;
private float initialTranslationY;
AdjustPanLayoutHelper adjustPanLayoutHelper = new AdjustPanLayoutHelper(this) {
@Override
protected void onTransitionStart(boolean keyboardVisible, int contentHeight) {
super.onTransitionStart(keyboardVisible, contentHeight);
if (previousScrollOffsetY > 0 && previousScrollOffsetY != scrollOffsetY[0] && keyboardVisible) {
fromScrollY = previousScrollOffsetY;
toScrollY = scrollOffsetY[0];
} else {
fromScrollY = -1;
}
invalidate();
if (currentAttachLayout instanceof ChatAttachAlertBotWebViewLayout) {
if (!botButtonWasVisible) {
if (keyboardVisible) {
shadow.setVisibility(GONE);
buttonsRecyclerView.setVisibility(GONE);
} else {
shadow.setVisibility(VISIBLE);
buttonsRecyclerView.setVisibility(VISIBLE);
}
}
}
currentAttachLayout.onPanTransitionStart(keyboardVisible, contentHeight);
}
@Override
protected void onTransitionEnd() {
super.onTransitionEnd();
updateLayout(currentAttachLayout, false, 0);
previousScrollOffsetY = scrollOffsetY[0];
currentAttachLayout.onPanTransitionEnd();
if (currentAttachLayout instanceof ChatAttachAlertBotWebViewLayout) {
if (!botButtonWasVisible) {
int offsetY = keyboardVisible ? AndroidUtilities.dp(84) : 0;
for (int i = 0; i < botAttachLayouts.size(); i++) {
botAttachLayouts.valueAt(i).setMeasureOffsetY(offsetY);
}
}
}
}
@Override
protected void onPanTranslationUpdate(float y, float progress, boolean keyboardVisible) {
currentPanTranslationY = y;
if (fromScrollY > 0) {
currentPanTranslationY += (fromScrollY - toScrollY) * (1f - progress);
}
actionBar.setTranslationY(currentPanTranslationY);
selectedMenuItem.setTranslationY(currentPanTranslationY);
if (searchItem != null) {
searchItem.setTranslationY(currentPanTranslationY);
}
doneItem.setTranslationY(currentPanTranslationY);
actionBarShadow.setTranslationY(currentPanTranslationY);
updateSelectedPosition(0);
setCurrentPanTranslationY(currentPanTranslationY);
invalidate();
frameLayout2.invalidate();
updateCommentTextViewPosition();
if (currentAttachLayout != null) {
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
}
}
@Override
protected boolean heightAnimationEnabled() {
if (isDismissed() || !openTransitionFinished) {
return false;
}
return currentAttachLayout != pollLayout && !commentTextView.isPopupVisible() || currentAttachLayout == pollLayout && !pollLayout.isPopupVisible();
}
};
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (currentAttachLayout.onContainerViewTouchEvent(ev)) {
return true;
}
if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY[0] != 0 && ev.getY() < getCurrentTop() && actionBar.getAlpha() == 0.0f) {
onDismissWithTouchOutside();
return true;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (currentAttachLayout.onContainerViewTouchEvent(event)) {
return true;
}
return !isDismissed() && super.onTouchEvent(event);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int totalHeight;
if (getLayoutParams().height > 0) {
totalHeight = getLayoutParams().height;
} else {
totalHeight = MeasureSpec.getSize(heightMeasureSpec);
}
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
ignoreLayout = true;
setPadding(backgroundPaddingLeft, AndroidUtilities.statusBarHeight, backgroundPaddingLeft, 0);
ignoreLayout = false;
}
int availableHeight = totalHeight - getPaddingTop();
int availableWidth = MeasureSpec.getSize(widthMeasureSpec) - backgroundPaddingLeft * 2;
if (AndroidUtilities.isTablet()) {
selectedMenuItem.setAdditionalYOffset(-AndroidUtilities.dp(3));
} else if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) {
selectedMenuItem.setAdditionalYOffset(0);
} else {
selectedMenuItem.setAdditionalYOffset(-AndroidUtilities.dp(3));
}
LayoutParams layoutParams = (LayoutParams) actionBarShadow.getLayoutParams();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight();
layoutParams = (LayoutParams) doneItem.getLayoutParams();
layoutParams.height = ActionBar.getCurrentActionBarHeight();
ignoreLayout = true;
int newSize = (int) (availableWidth / Math.min(4.5f, buttonsAdapter.getItemCount()));
if (attachItemSize != newSize) {
attachItemSize = newSize;
AndroidUtilities.runOnUIThread(() -> buttonsAdapter.notifyDataSetChanged());
}
ignoreLayout = false;
onMeasureInternal(widthMeasureSpec, MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY));
}
private void onMeasureInternal(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
widthSize -= backgroundPaddingLeft * 2;
int keyboardSize = 0;
if (!commentTextView.isWaitingForKeyboardOpen() && keyboardSize <= AndroidUtilities.dp(20) && !commentTextView.isPopupShowing() && !commentTextView.isAnimatePopupClosing()) {
ignoreLayout = true;
commentTextView.hideEmojiView();
ignoreLayout = false;
}
if (pollLayout != null && keyboardSize <= AndroidUtilities.dp(20) && !pollLayout.isWaitingForKeyboardOpen() && !pollLayout.isPopupShowing() && !pollLayout.isAnimatePopupClosing()) {
ignoreLayout = true;
pollLayout.hideEmojiView();
ignoreLayout = false;
}
if (keyboardSize <= AndroidUtilities.dp(20)) {
int paddingBottom;
if (keyboardVisible) {
paddingBottom = 0;
} else {
if (currentAttachLayout == pollLayout && pollLayout.emojiView != null) {
paddingBottom = pollLayout.getEmojiPadding();
} else {
paddingBottom = commentTextView.getEmojiPadding();
}
}
if (!AndroidUtilities.isInMultiwindow) {
heightSize -= paddingBottom;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
}
ignoreLayout = true;
currentAttachLayout.onPreMeasure(widthSize, heightSize);
if (nextAttachLayout != null) {
nextAttachLayout.onPreMeasure(widthSize, heightSize);
}
ignoreLayout = false;
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child == null || child.getVisibility() == GONE) {
continue;
}
if (commentTextView != null && commentTextView.isPopupView(child) || pollLayout != null && child == pollLayout.emojiView) {
if (inBubbleMode) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize + getPaddingTop(), MeasureSpec.EXACTLY));
} else if (AndroidUtilities.isInMultiwindow || AndroidUtilities.isTablet()) {
if (AndroidUtilities.isTablet()) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(AndroidUtilities.isTablet() ? 200 : 320), heightSize - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
}
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
}
} else {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (lastNotifyWidth != r - l) {
lastNotifyWidth = r - l;
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
}
final int count = getChildCount();
if (Build.VERSION.SDK_INT >= 29) {
exclustionRect.set(l, t, r, b);
setSystemGestureExclusionRects(exclusionRects);
}
int keyboardSize = measureKeyboardHeight();
int paddingBottom = getPaddingBottom();
if (keyboardVisible) {
paddingBottom += 0;
} else {
if (pollLayout != null && currentAttachLayout == pollLayout && pollLayout.emojiView != null) {
paddingBottom += keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? pollLayout.getEmojiPadding() : 0;
} else {
paddingBottom += keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? commentTextView.getEmojiPadding() : 0;
}
}
setBottomClip(paddingBottom);
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.LEFT;
}
final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = (r - l) - width - lp.rightMargin - getPaddingRight() - backgroundPaddingLeft;
break;
case Gravity.LEFT:
default:
childLeft = lp.leftMargin + getPaddingLeft();
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = lp.topMargin + getPaddingTop();
break;
case Gravity.CENTER_VERTICAL:
childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
break;
default:
childTop = lp.topMargin;
}
if (commentTextView != null && commentTextView.isPopupView(child) || pollLayout != null && child == pollLayout.emojiView) {
if (AndroidUtilities.isTablet()) {
childTop = getMeasuredHeight() - child.getMeasuredHeight();
} else {
childTop = getMeasuredHeight() + keyboardSize - child.getMeasuredHeight();
}
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
notifyHeightChanged();
updateLayout(currentAttachLayout, false, 0);
updateLayout(nextAttachLayout, false, 0);
}
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
private float getY(View child) {
if (child instanceof AttachAlertLayout) {
AttachAlertLayout layout = (AttachAlertLayout) child;
int actionBarType = layout.needsActionBar();
int offset = AndroidUtilities.dp(13) + (int) ((headerView != null ? headerView.getAlpha() : 0f) * AndroidUtilities.dp(26));
int top = getScrollOffsetY(0) - backgroundPaddingTop - offset;
if (currentSheetAnimationType == 1 || viewChangeAnimator != null) {
top += child.getTranslationY();
}
int y = top + AndroidUtilities.dp(20);
int h = (actionBarType != 0 ? ActionBar.getCurrentActionBarHeight() : backgroundPaddingTop);
if (actionBarType != 2 && top + backgroundPaddingTop < h) {
float toMove = offset;
if (layout == locationLayout) {
toMove += AndroidUtilities.dp(11);
} else if (layout == pollLayout) {
toMove -= AndroidUtilities.dp(3);
} else {
toMove += AndroidUtilities.dp(4);
}
float availableToMove = h - toMove + AndroidUtilities.statusBarHeight;
y -= (int) (availableToMove * actionBar.getAlpha());
}
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
y += AndroidUtilities.statusBarHeight;
}
return y;
}
return 0;
}
private void drawChildBackground(Canvas canvas, View child) {
if (child instanceof AttachAlertLayout) {
canvas.save();
canvas.translate(0, currentPanTranslationY);
int viewAlpha = (int) (255 * child.getAlpha());
AttachAlertLayout layout = (AttachAlertLayout) child;
int actionBarType = layout.needsActionBar();
int offset = AndroidUtilities.dp(13) + (int) ((headerView != null ? headerView.getAlpha() : 0f) * AndroidUtilities.dp(26));
int top = getScrollOffsetY(0) - backgroundPaddingTop - offset;
if (currentSheetAnimationType == 1 || viewChangeAnimator != null) {
top += child.getTranslationY();
}
int y = top + AndroidUtilities.dp(20);
int height = getMeasuredHeight() + AndroidUtilities.dp(45) + backgroundPaddingTop;
float rad = 1.0f;
int h = (actionBarType != 0 ? ActionBar.getCurrentActionBarHeight() : backgroundPaddingTop);
if (actionBarType == 2) {
if (top < h) {
rad = Math.max(0, 1.0f - (h - top) / (float) backgroundPaddingTop);
}
} else {
float toMove = offset;
if (layout == locationLayout) {
toMove += AndroidUtilities.dp(11);
} else if (layout == pollLayout) {
toMove -= AndroidUtilities.dp(3);
} else {
toMove += AndroidUtilities.dp(4);
}
float moveProgress = actionBar.getAlpha();
float availableToMove = h - toMove + AndroidUtilities.statusBarHeight;
int diff = (int) (availableToMove * moveProgress);
top -= diff;
y -= diff;
height += diff;
rad = 1.0f - moveProgress;
}
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
top += AndroidUtilities.statusBarHeight;
y += AndroidUtilities.statusBarHeight;
height -= AndroidUtilities.statusBarHeight;
}
int backgroundColor = currentAttachLayout.hasCustomBackground() ? currentAttachLayout.getCustomBackground() : getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground);
shadowDrawable.setAlpha(viewAlpha);
shadowDrawable.setBounds(0, top, getMeasuredWidth(), height);
shadowDrawable.draw(canvas);
if (actionBarType == 2) {
Theme.dialogs_onlineCirclePaint.setColor(backgroundColor);
Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha);
rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24));
canvas.save();
canvas.clipRect(rect.left, rect.top, rect.right, rect.top + rect.height() / 2);
canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
if ((rad != 1.0f && actionBarType != 2) || currentAttachLayout.hasCustomActionBarBackground()) {
Theme.dialogs_onlineCirclePaint.setColor(currentAttachLayout.hasCustomActionBarBackground() ? currentAttachLayout.getCustomActionBarBackground() : backgroundColor);
Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha);
rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24));
canvas.save();
canvas.clipRect(rect.left, rect.top, rect.right, rect.top + rect.height() / 2);
canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
if (currentAttachLayout.hasCustomActionBarBackground()) {
Theme.dialogs_onlineCirclePaint.setColor(currentAttachLayout.getCustomActionBarBackground());
Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha);
int top2 = getScrollOffsetY(0);
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
top2 += AndroidUtilities.statusBarHeight;
}
rect.set(backgroundPaddingLeft, (backgroundPaddingTop + top + AndroidUtilities.dp(12)) * (rad), getMeasuredWidth() - backgroundPaddingLeft, top2 + AndroidUtilities.dp(12));
canvas.save();
canvas.drawRect(rect, Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
if ((headerView == null || headerView.getAlpha() != 1.0f) && rad != 0) {
int w = AndroidUtilities.dp(36);
rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4));
int color;
float alphaProgress;
if (actionBarType == 2) {
color = 0x20000000;
alphaProgress = rad;
} else if (currentAttachLayout.hasCustomActionBarBackground()) {
int actionBarColor = currentAttachLayout.getCustomActionBarBackground();
int blendColor = ColorUtils.calculateLuminance(actionBarColor) < 0.5f ? Color.WHITE : Color.BLACK;
color = ColorUtils.blendARGB(actionBarColor, blendColor, 0.5f);
alphaProgress = headerView == null ? 1.0f : 1.0f - headerView.getAlpha();
} else {
color = getThemedColor(Theme.key_sheet_scrollUp);
alphaProgress = headerView == null ? 1.0f : 1.0f - headerView.getAlpha();
}
int alpha = Color.alpha(color);
Theme.dialogs_onlineCirclePaint.setColor(color);
Theme.dialogs_onlineCirclePaint.setAlpha((int) (alpha * alphaProgress * rad * child.getAlpha()));
canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
}
canvas.restore();
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (child instanceof AttachAlertLayout && child.getAlpha() > 0.0f) {
canvas.save();
canvas.translate(0, currentPanTranslationY);
int viewAlpha = (int) (255 * child.getAlpha());
AttachAlertLayout layout = (AttachAlertLayout) child;
int actionBarType = layout.needsActionBar();
int offset = AndroidUtilities.dp(13) + (headerView != null ? AndroidUtilities.dp(headerView.getAlpha() * 26) : 0);
int top = getScrollOffsetY(layout == currentAttachLayout ? 0 : 1) - backgroundPaddingTop - offset;
if (currentSheetAnimationType == 1 || viewChangeAnimator != null) {
top += child.getTranslationY();
}
int y = top + AndroidUtilities.dp(20);
int height = getMeasuredHeight() + AndroidUtilities.dp(45) + backgroundPaddingTop;
float rad = 1.0f;
int h = (actionBarType != 0 ? ActionBar.getCurrentActionBarHeight() : backgroundPaddingTop);
if (actionBarType == 2) {
if (top < h) {
rad = Math.max(0, 1.0f - (h - top) / (float) backgroundPaddingTop);
}
} else if (top + backgroundPaddingTop < h) {
float toMove = offset;
if (layout == locationLayout) {
toMove += AndroidUtilities.dp(11);
} else if (layout == pollLayout) {
toMove -= AndroidUtilities.dp(3);
} else {
toMove += AndroidUtilities.dp(4);
}
float moveProgress = Math.min(1.0f, (h - top - backgroundPaddingTop) / toMove);
float availableToMove = h - toMove;
int diff = (int) (availableToMove * moveProgress);
top -= diff;
y -= diff;
height += diff;
rad = 1.0f - moveProgress;
}
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
top += AndroidUtilities.statusBarHeight;
y += AndroidUtilities.statusBarHeight;
height -= AndroidUtilities.statusBarHeight;
}
int backgroundColor = currentAttachLayout.hasCustomBackground() ? currentAttachLayout.getCustomBackground() : getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground);
boolean drawBackground = !(currentAttachLayout == photoPreviewLayout || nextAttachLayout == photoPreviewLayout || (currentAttachLayout == photoLayout && nextAttachLayout == null));
if (drawBackground) {
shadowDrawable.setAlpha(viewAlpha);
shadowDrawable.setBounds(0, top, getMeasuredWidth(), height);
shadowDrawable.draw(canvas);
if (actionBarType == 2) {
Theme.dialogs_onlineCirclePaint.setColor(backgroundColor);
Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha);
rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24));
canvas.save();
canvas.clipRect(rect.left, rect.top, rect.right, rect.top + rect.height() / 2);
canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
}
boolean result;
if (child != contactsLayout && child != quickRepliesLayout && child != audioLayout) {
canvas.save();
canvas.clipRect(backgroundPaddingLeft, actionBar.getY() + actionBar.getMeasuredHeight() - currentPanTranslationY, getMeasuredWidth() - backgroundPaddingLeft, getMeasuredHeight());
result = super.drawChild(canvas, child, drawingTime);
canvas.restore();
} else {
result = super.drawChild(canvas, child, drawingTime);
}
if (drawBackground) {
if (rad != 1.0f && actionBarType != 2) {
Theme.dialogs_onlineCirclePaint.setColor(backgroundColor);
Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha);
rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24));
canvas.save();
canvas.clipRect(rect.left, rect.top, rect.right, rect.top + rect.height() / 2);
canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
if ((headerView == null || headerView.getAlpha() != 1.0f) && rad != 0) {
int w = AndroidUtilities.dp(36);
rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4));
int color;
float alphaProgress;
if (actionBarType == 2) {
color = 0x20000000;
alphaProgress = rad;
} else {
color = getThemedColor(Theme.key_sheet_scrollUp);
alphaProgress = headerView == null ? 1.0f : 1.0f - headerView.getAlpha();
}
int alpha = Color.alpha(color);
Theme.dialogs_onlineCirclePaint.setColor(color);
Theme.dialogs_onlineCirclePaint.setAlpha((int) (alpha * alphaProgress * rad * child.getAlpha()));
canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
}
}
canvas.restore();
return result;
} else if (child == actionBar) {
final float alpha = actionBar.getAlpha();
if (alpha <= 0) {
return false;
}
if (alpha >= 1) {
return super.drawChild(canvas, child, drawingTime);
}
canvas.save();
canvas.clipRect(actionBar.getX(), getY(currentAttachLayout), actionBar.getX() + actionBar.getWidth(), actionBar.getY() + actionBar.getHeight());
boolean result = super.drawChild(canvas, child, drawingTime);
canvas.restore();
return result;
}
return super.drawChild(canvas, child, drawingTime);
}
@Override
protected void onDraw(Canvas canvas) {
if (inBubbleMode) {
return;
}
}
private int getCurrentTop() {
int y = scrollOffsetY[0] - backgroundPaddingTop * 2 - (AndroidUtilities.dp(13) + (headerView != null ? AndroidUtilities.dp(headerView.getAlpha() * 26) : 0)) + AndroidUtilities.dp(20);
if (Build.VERSION.SDK_INT >= 21 && !inBubbleMode) {
y += AndroidUtilities.statusBarHeight;
}
return y;
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
// canvas.clipRect(0, getPaddingTop() + currentPanTranslationY, getMeasuredWidth(), getMeasuredHeight() + currentPanTranslationY - getPaddingBottom());
if (currentAttachLayout == photoPreviewLayout || nextAttachLayout == photoPreviewLayout || (currentAttachLayout == photoLayout && nextAttachLayout == null)) {
drawChildBackground(canvas, currentAttachLayout);
}
super.dispatchDraw(canvas);
canvas.restore();
}
@Override
public void setTranslationY(float translationY) {
translationY += currentPanTranslationY;
if (currentSheetAnimationType == 0) {
initialTranslationY = translationY;
}
if (currentSheetAnimationType == 1) {
if (translationY < 0) {
currentAttachLayout.setTranslationY(translationY);
if (avatarPicker != 0) {
headerView.setTranslationY(baseSelectedTextViewTranslationY + translationY - currentPanTranslationY);
}
translationY = 0;
buttonsRecyclerView.setTranslationY(0);
} else {
currentAttachLayout.setTranslationY(0);
buttonsRecyclerView.setTranslationY(-translationY + buttonsRecyclerView.getMeasuredHeight() * (translationY / initialTranslationY));
}
containerView.invalidate();
}
super.setTranslationY(translationY - currentPanTranslationY);
if (currentSheetAnimationType != 1) {
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
adjustPanLayoutHelper.setResizableView(this);
adjustPanLayoutHelper.onAttach();
commentTextView.setAdjustPanLayoutHelper(adjustPanLayoutHelper);
// Bulletin.addDelegate(this, bulletinDelegate);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
adjustPanLayoutHelper.onDetach();
// Bulletin.removeDelegate(this);
}
};
sizeNotifierFrameLayout.setDelegate(new SizeNotifierFrameLayout.SizeNotifierFrameLayoutDelegate() {
@Override
public void onSizeChanged(int keyboardHeight, boolean isWidthGreater) {
if (currentAttachLayout == photoPreviewLayout) {
currentAttachLayout.invalidate();
}
}
});
containerView = sizeNotifierFrameLayout;
containerView.setWillNotDraw(false);
containerView.setClipChildren(false);
containerView.setClipToPadding(false);
containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);
actionBar = new ActionBar(context, resourcesProvider) {
@Override
public void setAlpha(float alpha) {
float oldAlpha = getAlpha();
super.setAlpha(alpha);
if (oldAlpha != alpha) {
containerView.invalidate();
if (frameLayout2 != null && buttonsRecyclerView != null) {
if (frameLayout2.getTag() == null) {
if (currentAttachLayout == null || currentAttachLayout.shouldHideBottomButtons()) {
buttonsRecyclerView.setAlpha(1.0f - alpha);
shadow.setAlpha(1.0f - alpha);
buttonsRecyclerView.setTranslationY(AndroidUtilities.dp(44) * alpha);
}
frameLayout2.setTranslationY(AndroidUtilities.dp(48) * alpha);
shadow.setTranslationY(AndroidUtilities.dp(84) * alpha + botMainButtonOffsetY);
} else if (currentAttachLayout == null) {
float value = alpha == 0.0f ? 1.0f : 0.0f;
if (buttonsRecyclerView.getAlpha() != value) {
buttonsRecyclerView.setAlpha(value);
}
}
}
}
}
};
actionBar.setBackgroundColor(getThemedColor(Theme.key_dialogBackground));
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setItemsColor(getThemedColor(Theme.key_dialogTextBlack), false);
actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_dialogButtonSelector), false);
actionBar.setTitleColor(getThemedColor(Theme.key_dialogTextBlack));
actionBar.setOccupyStatusBar(false);
actionBar.setAlpha(0.0f);
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
if (currentAttachLayout.onBackPressed()) {
return;
}
dismiss();
} else {
currentAttachLayout.onMenuItemClick(id);
}
}
});
selectedMenuItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider);
selectedMenuItem.setLongClickEnabled(false);
selectedMenuItem.setIcon(R.drawable.ic_ab_other);
selectedMenuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
selectedMenuItem.setVisibility(View.INVISIBLE);
selectedMenuItem.setAlpha(0.0f);
selectedMenuItem.setSubMenuOpenSide(2);
selectedMenuItem.setDelegate(id -> actionBar.getActionBarMenuOnItemClick().onItemClick(id));
selectedMenuItem.setAdditionalYOffset(AndroidUtilities.dp(72));
selectedMenuItem.setTranslationX(AndroidUtilities.dp(6));
selectedMenuItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 6));
selectedMenuItem.setOnClickListener(v -> selectedMenuItem.toggleSubMenu());
doneItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader), true, resourcesProvider);
doneItem.setLongClickEnabled(false);
doneItem.setText(LocaleController.getString("Create", R.string.Create).toUpperCase());
doneItem.setVisibility(View.INVISIBLE);
doneItem.setAlpha(0.0f);
doneItem.setTranslationX(-AndroidUtilities.dp(12));
doneItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 3));
doneItem.setOnClickListener(v -> currentAttachLayout.onMenuItemClick(40));
if (baseFragment != null) {
searchItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider);
searchItem.setLongClickEnabled(false);
searchItem.setIcon(R.drawable.ic_ab_search);
searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
searchItem.setVisibility(View.INVISIBLE);
searchItem.setAlpha(0.0f);
searchItem.setTranslationX(-AndroidUtilities.dp(42));
searchItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 6));
searchItem.setOnClickListener(v -> {
if (avatarPicker != 0) {
delegate.openAvatarsSearch();
dismiss();
return;
}
final HashMap<Object, Object> photos = new HashMap<>();
final ArrayList<Object> order = new ArrayList<>();
PhotoPickerSearchActivity fragment = new PhotoPickerSearchActivity(photos, order, 0, true, (ChatActivity) baseFragment);
fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() {
private boolean sendPressed;
@Override
public void selectedPhotosChanged() {
}
@Override
public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) {
if (canceled) {
return;
}
if (photos.isEmpty() || sendPressed) {
return;
}
sendPressed = true;
ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>();
for (int a = 0; a < order.size(); a++) {
Object object = photos.get(order.get(a));
SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
media.add(info);
MediaController.SearchImage searchImage = (MediaController.SearchImage) object;
if (searchImage.imagePath != null) {
info.path = searchImage.imagePath;
} else {
info.searchImage = searchImage;
}
info.thumbPath = searchImage.thumbPath;
info.videoEditedInfo = searchImage.editedInfo;
info.caption = searchImage.caption != null ? searchImage.caption.toString() : null;
info.entities = searchImage.entities;
info.masks = searchImage.stickers;
info.ttl = searchImage.ttl;
if (searchImage.inlineResult != null && searchImage.type == 1) {
info.inlineResult = searchImage.inlineResult;
info.params = searchImage.params;
}
searchImage.date = (int) (System.currentTimeMillis() / 1000);
}
((ChatActivity) baseFragment).didSelectSearchPhotos(media, notify, scheduleDate);
}
@Override
public void onCaptionChanged(CharSequence text) {
}
});
fragment.setMaxSelectedPhotos(maxSelectedPhotos, allowOrder);
if (showingFromDialog) {
baseFragment.showAsSheet(fragment);
} else {
baseFragment.presentFragment(fragment);
}
dismiss();
});
}
optionsItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider);
optionsItem.setLongClickEnabled(false);
optionsItem.setIcon(R.drawable.ic_ab_other);
optionsItem.setContentDescription(LocaleController.getString(R.string.AccDescrMoreOptions));
optionsItem.setVisibility(View.GONE);
optionsItem.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), Theme.RIPPLE_MASK_CIRCLE_TO_BOUND_EDGE));
optionsItem.addSubItem(1, R.drawable.msg_addbot, LocaleController.getString(R.string.StickerCreateEmpty)).setOnClickListener(v -> {
optionsItem.toggleSubMenu();
PhotoViewer.getInstance().setParentActivity(baseFragment, resourcesProvider);
PhotoViewer.getInstance().setParentAlert(this);
PhotoViewer.getInstance().setMaxSelectedPhotos(maxSelectedPhotos, allowOrder);
if (!delegate.needEnterComment()) {
AndroidUtilities.hideKeyboard(baseFragment.getFragmentView().findFocus());
AndroidUtilities.hideKeyboard(getContainer().findFocus());
}
File file = StoryEntry.makeCacheFile(currentAccount, "webp");
int w = AndroidUtilities.displaySize.x, h = AndroidUtilities.displaySize.y;
if (w > 1080 || h > 1080) {
float scale = Math.min(w, h) / 1080f;
w = (int) (w * scale);
h = (int) (h * scale);
}
Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
try {
b.compress(Bitmap.CompressFormat.WEBP, 100, new FileOutputStream(file));
} catch (Throwable e) {
FileLog.e(e);
}
b.recycle();
ArrayList<Object> arrayList = new ArrayList<>();
final MediaController.PhotoEntry entry = new MediaController.PhotoEntry(0, 0, 0, file.getAbsolutePath(), 0, false, 0, 0, 0);
arrayList.add(entry);
PhotoViewer.getInstance().openPhotoForSelect(arrayList, 0, PhotoViewer.SELECT_TYPE_STICKER, false, new PhotoViewer.EmptyPhotoViewerProvider() {
@Override
public boolean allowCaption() {
return false;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo, boolean notify, int scheduleDate, boolean forceDocument) {
sent = true;
if (delegate == null) {
return;
}
entry.editedInfo = videoEditedInfo;
ChatAttachAlertPhotoLayout.selectedPhotosOrder.clear();
ChatAttachAlertPhotoLayout.selectedPhotos.clear();
ChatAttachAlertPhotoLayout.selectedPhotosOrder.add(0);
ChatAttachAlertPhotoLayout.selectedPhotos.put(0, entry);
delegate.didPressedButton(7, true, notify, scheduleDate, forceDocument);
}
}, baseFragment instanceof ChatActivity ? (ChatActivity) baseFragment : null);
if (isStickerMode) {
PhotoViewer.getInstance().enableStickerMode(null, true, customStickerHandler);
}
});
optionsItem.setMenuYOffset(AndroidUtilities.dp(-12));
optionsItem.setAdditionalXOffset(AndroidUtilities.dp(12));
optionsItem.setOnClickListener(v -> {
optionsItem.toggleSubMenu();
});
headerView = new FrameLayout(context) {
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
updateSelectedPosition(0);
containerView.invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (headerView.getVisibility() != View.VISIBLE) {
return false;
}
return super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (headerView.getVisibility() != View.VISIBLE) {
return false;
}
return super.onInterceptTouchEvent(event);
}
};
headerView.setOnClickListener(e -> {
this.updatePhotoPreview(currentAttachLayout != photoPreviewLayout);
});
headerView.setAlpha(0.0f);
headerView.setVisibility(View.INVISIBLE);
selectedView = new LinearLayout(context);
selectedView.setOrientation(LinearLayout.HORIZONTAL);
selectedView.setGravity(Gravity.CENTER_VERTICAL);
selectedTextView = new TextView(context);
selectedTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
selectedTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
selectedTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
selectedTextView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
selectedTextView.setMaxLines(1);
selectedTextView.setEllipsize(TextUtils.TruncateAt.END);
selectedView.addView(selectedTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL));
selectedArrowImageView = new ImageView(context);
Drawable arrowRight = getContext().getResources().getDrawable(R.drawable.attach_arrow_right).mutate();
arrowRight.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY));
selectedArrowImageView.setImageDrawable(arrowRight);
selectedArrowImageView.setVisibility(View.GONE);
selectedView.addView(selectedArrowImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 4, 1, 0, 0));
selectedView.setAlpha(1);
headerView.addView(selectedView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
mediaPreviewView = new LinearLayout(context);
mediaPreviewView.setOrientation(LinearLayout.HORIZONTAL);
mediaPreviewView.setGravity(Gravity.CENTER_VERTICAL);
ImageView arrowView = new ImageView(context);
Drawable arrowLeft = getContext().getResources().getDrawable(R.drawable.attach_arrow_left).mutate();
arrowLeft.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY));
arrowView.setImageDrawable(arrowLeft);
mediaPreviewView.addView(arrowView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 4, 0));
mediaPreviewTextView = new TextView(context);
mediaPreviewTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
mediaPreviewTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
mediaPreviewTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
mediaPreviewTextView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
mediaPreviewTextView.setText(LocaleController.getString("AttachMediaPreview", R.string.AttachMediaPreview));
mediaPreviewView.setAlpha(0);
mediaPreviewView.addView(mediaPreviewTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL));
headerView.addView(mediaPreviewView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
layouts[0] = photoLayout = new ChatAttachAlertPhotoLayout(this, context, forceDarkTheme, needCamera, resourcesProvider);
photoLayout.setTranslationX(0);
currentAttachLayout = photoLayout;
selectedId = 1;
containerView.addView(photoLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
containerView.addView(headerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 23, 0, 12, 0));
containerView.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
containerView.addView(selectedMenuItem, LayoutHelper.createFrame(48, 48, Gravity.TOP | Gravity.RIGHT));
if (searchItem != null) {
containerView.addView(searchItem, LayoutHelper.createFrame(48, 48, Gravity.TOP | Gravity.RIGHT));
}
if (optionsItem != null) {
headerView.addView(optionsItem, LayoutHelper.createFrame(32, 32, Gravity.CENTER_VERTICAL | Gravity.RIGHT, 0, 0, 0, 8));
}
containerView.addView(doneItem, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.TOP | Gravity.RIGHT));
actionBarShadow = new View(context);
actionBarShadow.setAlpha(0.0f);
actionBarShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine));
containerView.addView(actionBarShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1));
shadow = new View(context);
shadow.setBackgroundResource(R.drawable.attach_shadow);
shadow.getBackground().setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
containerView.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 84));
buttonsRecyclerView = new RecyclerListView(context) {
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
currentAttachLayout.onButtonsTranslationYUpdated();
}
};
buttonsRecyclerView.setAdapter(buttonsAdapter = new ButtonsAdapter(context));
buttonsRecyclerView.setLayoutManager(buttonsLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
buttonsRecyclerView.setVerticalScrollBarEnabled(false);
buttonsRecyclerView.setHorizontalScrollBarEnabled(false);
buttonsRecyclerView.setItemAnimator(null);
buttonsRecyclerView.setLayoutAnimation(null);
buttonsRecyclerView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow));
buttonsRecyclerView.setBackgroundColor(getThemedColor(Theme.key_dialogBackground));
buttonsRecyclerView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
containerView.addView(buttonsRecyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 84, Gravity.BOTTOM | Gravity.LEFT));
buttonsRecyclerView.setOnItemClickListener((view, position) -> {
BaseFragment lastFragment = baseFragment;
if (lastFragment == null) {
lastFragment = LaunchActivity.getLastFragment();
}
if (lastFragment == null || lastFragment.getParentActivity() == null) {
return;
}
if (view instanceof AttachButton) {
final Activity activity = lastFragment.getParentActivity();
int num = (Integer) view.getTag();
if (num == 1) {
if (!photosEnabled && !videosEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (!photosEnabled && !videosEnabled) {
showLayout(restrictedLayout = new ChatAttachRestrictedLayout(1, this, getContext(), resourcesProvider));
}
showLayout(photoLayout);
} else if (num == 3) {
if (!musicEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (Build.VERSION.SDK_INT >= 33) {
if (activity.checkSelfPermission(Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_AUDIO}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
} else if (Build.VERSION.SDK_INT >= 23 && activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
AndroidUtilities.findActivity(getContext()).requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
openAudioLayout(true);
} else if (num == 4) {
if (!documentsEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (Build.VERSION.SDK_INT >= 33) {
if (activity.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED ||
activity.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
} else if (Build.VERSION.SDK_INT >= 23 && activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
AndroidUtilities.findActivity(getContext()).requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
openDocumentsLayout(true);
} else if (num == 5) {
if (!plainTextEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (Build.VERSION.SDK_INT >= 23 && plainTextEnabled) {
if (getContext().checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
AndroidUtilities.findActivity(getContext()).requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, BasePermissionsActivity.REQUEST_CODE_ATTACH_CONTACT);
return;
}
}
openContactsLayout();
} else if (num == 6) {
if (!plainTextEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (!AndroidUtilities.isMapsInstalled(baseFragment)) {
return;
}
if (!plainTextEnabled) {
restrictedLayout = new ChatAttachRestrictedLayout(6, this, getContext(), resourcesProvider);
showLayout(restrictedLayout);
} else {
if (locationLayout == null) {
layouts[5] = locationLayout = new ChatAttachAlertLocationLayout(this, getContext(), resourcesProvider);
locationLayout.setDelegate((location, live, notify, scheduleDate) -> ((ChatActivity) baseFragment).didSelectLocation(location, live, notify, scheduleDate));
}
showLayout(locationLayout);
}
} else if (num == 9) {
if (!pollsEnabled && checkCanRemoveRestrictionsByBoosts()) {
return;
}
if (!pollsEnabled) {
restrictedLayout = new ChatAttachRestrictedLayout(9, this, getContext(), resourcesProvider);
showLayout(restrictedLayout);
} else {
if (pollLayout == null) {
layouts[1] = pollLayout = new ChatAttachAlertPollLayout(this, getContext(), resourcesProvider);
pollLayout.setDelegate((poll, params, notify, scheduleDate) -> ((ChatActivity) baseFragment).sendPoll(poll, params, notify, scheduleDate));
}
showLayout(pollLayout);
}
} else if (num == 11) {
openQuickRepliesLayout();
} else {
delegate.didPressedButton((Integer) view.getTag(), true, true, 0, false);
}
int left = view.getLeft();
int right = view.getRight();
int extra = AndroidUtilities.dp(10);
if (left - extra < 0) {
buttonsRecyclerView.smoothScrollBy(left - extra, 0);
} else if (right + extra > buttonsRecyclerView.getMeasuredWidth()) {
buttonsRecyclerView.smoothScrollBy(right + extra - buttonsRecyclerView.getMeasuredWidth(), 0);
}
} else if (view instanceof AttachBotButton) {
AttachBotButton button = (AttachBotButton) view;
if (button.attachMenuBot != null) {
if (button.attachMenuBot.inactive) {
WebAppDisclaimerAlert.show(getContext(), (allowSendMessage) -> {
TLRPC.TL_messages_toggleBotInAttachMenu botRequest = new TLRPC.TL_messages_toggleBotInAttachMenu();
botRequest.bot = MessagesController.getInstance(currentAccount).getInputUser(button.attachMenuBot.bot_id);
botRequest.enabled = true;
botRequest.write_allowed = true;
ConnectionsManager.getInstance(currentAccount).sendRequest(botRequest, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
button.attachMenuBot.inactive = button.attachMenuBot.side_menu_disclaimer_needed = false;
showBotLayout(button.attachMenuBot.bot_id, true);
MediaDataController.getInstance(currentAccount).updateAttachMenuBotsInCache();
}), ConnectionsManager.RequestFlagInvokeAfter | ConnectionsManager.RequestFlagFailOnServerErrors);
}, null);
} else {
showBotLayout(button.attachMenuBot.bot_id, true);
}
} else {
delegate.didSelectBot(button.currentUser);
dismiss();
}
}
if (view.getX() + view.getWidth() >= buttonsRecyclerView.getMeasuredWidth() - AndroidUtilities.dp(32)) {
buttonsRecyclerView.smoothScrollBy((int) (view.getWidth() * 1.5f), 0);
}
});
buttonsRecyclerView.setOnItemLongClickListener((view, position) -> {
if (view instanceof AttachBotButton) {
AttachBotButton button = (AttachBotButton) view;
if (destroyed || button.currentUser == null) {
return false;
}
onLongClickBotButton(button.attachMenuBot, button.currentUser);
return true;
}
return false;
});
botMainButtonTextView = new TextView(context);
botMainButtonTextView.setVisibility(View.GONE);
botMainButtonTextView.setAlpha(0f);
botMainButtonTextView.setSingleLine();
botMainButtonTextView.setGravity(Gravity.CENTER);
botMainButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
int padding = AndroidUtilities.dp(16);
botMainButtonTextView.setPadding(padding, 0, padding, 0);
botMainButtonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
botMainButtonTextView.setOnClickListener(v -> {
if (selectedId < 0) {
ChatAttachAlertBotWebViewLayout webViewLayout = botAttachLayouts.get(-selectedId);
if (webViewLayout != null) {
webViewLayout.getWebViewContainer().onMainButtonPressed();
}
}
});
containerView.addView(botMainButtonTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
botProgressView = new RadialProgressView(context);
botProgressView.setSize(AndroidUtilities.dp(18));
botProgressView.setAlpha(0f);
botProgressView.setScaleX(0.1f);
botProgressView.setScaleY(0.1f);
botProgressView.setVisibility(View.GONE);
containerView.addView(botProgressView, LayoutHelper.createFrame(28, 28, Gravity.BOTTOM | Gravity.RIGHT, 0, 0, 10, 10));
frameLayout2 = new FrameLayout(context) {
private final Paint p = new Paint();
private int color;
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (chatActivityEnterViewAnimateFromTop != 0 && chatActivityEnterViewAnimateFromTop != frameLayout2.getTop() + chatActivityEnterViewAnimateFromTop) {
if (topBackgroundAnimator != null) {
topBackgroundAnimator.cancel();
}
captionEditTextTopOffset = chatActivityEnterViewAnimateFromTop - (frameLayout2.getTop() + captionEditTextTopOffset);
topBackgroundAnimator = ValueAnimator.ofFloat(captionEditTextTopOffset, 0);
topBackgroundAnimator.addUpdateListener(valueAnimator -> {
captionEditTextTopOffset = (float) valueAnimator.getAnimatedValue();
frameLayout2.invalidate();
invalidate();
});
topBackgroundAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
topBackgroundAnimator.setDuration(200);
topBackgroundAnimator.start();
chatActivityEnterViewAnimateFromTop = 0;
}
float alphaOffset = (frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(84)) * (1f - getAlpha());
shadow.setTranslationY(-(frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(84)) + captionEditTextTopOffset + currentPanTranslationY + bottomPannelTranslation + alphaOffset + botMainButtonOffsetY);
int newColor = currentAttachLayout.hasCustomBackground() ? currentAttachLayout.getCustomBackground() : getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground);
if (color != newColor) {
color = newColor;
p.setColor(color);
}
canvas.drawRect(0, captionEditTextTopOffset, getMeasuredWidth(), getMeasuredHeight(), p);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.clipRect(0, captionEditTextTopOffset, getMeasuredWidth(), getMeasuredHeight());
super.dispatchDraw(canvas);
canvas.restore();
}
};
frameLayout2.setWillNotDraw(false);
frameLayout2.setVisibility(View.INVISIBLE);
frameLayout2.setAlpha(0.0f);
containerView.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
frameLayout2.setOnTouchListener((v, event) -> true);
captionLimitView = new NumberTextView(context);
captionLimitView.setVisibility(View.GONE);
captionLimitView.setTextSize(15);
captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
captionLimitView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
captionLimitView.setCenterAlign(true);
frameLayout2.addView(captionLimitView, LayoutHelper.createFrame(56, 20, Gravity.BOTTOM | Gravity.RIGHT, 3, 0, 14, 78));
currentLimit = MessagesController.getInstance(UserConfig.selectedAccount).getCaptionMaxLengthLimit();
commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG, true, resourcesProvider) {
private boolean shouldAnimateEditTextWithBounds;
private int messageEditTextPredrawHeigth;
private int messageEditTextPredrawScrollY;
private ValueAnimator messageEditTextAnimator;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!enterCommentEventSent) {
if (ev.getX() > commentTextView.getEditText().getLeft() && ev.getX() < commentTextView.getEditText().getRight()
&& ev.getY() > commentTextView.getEditText().getTop() && ev.getY() < commentTextView.getEditText().getBottom()) {
makeFocusable(commentTextView.getEditText(), true);
} else {
makeFocusable(commentTextView.getEditText(), false);
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (shouldAnimateEditTextWithBounds) {
EditTextCaption editText = commentTextView.getEditText();
float dy = (messageEditTextPredrawHeigth - editText.getMeasuredHeight()) + (messageEditTextPredrawScrollY - editText.getScrollY());
editText.setOffsetY(editText.getOffsetY() - dy);
ValueAnimator a = ValueAnimator.ofFloat(editText.getOffsetY(), 0);
a.addUpdateListener(animation -> {
editText.setOffsetY((float) animation.getAnimatedValue());
updateCommentTextViewPosition();
if (currentAttachLayout == photoLayout) {
photoLayout.onContainerTranslationUpdated(currentPanTranslationY);
}
});
if (messageEditTextAnimator != null) {
messageEditTextAnimator.cancel();
}
messageEditTextAnimator = a;
a.setDuration(200);
a.setInterpolator(CubicBezierInterpolator.DEFAULT);
a.start();
shouldAnimateEditTextWithBounds = false;
}
super.dispatchDraw(canvas);
}
@Override
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
if (!TextUtils.isEmpty(getEditText().getText())) {
shouldAnimateEditTextWithBounds = true;
messageEditTextPredrawHeigth = getEditText().getMeasuredHeight();
messageEditTextPredrawScrollY = getEditText().getScrollY();
invalidate();
} else {
getEditText().animate().cancel();
getEditText().setOffsetY(0);
shouldAnimateEditTextWithBounds = false;
}
chatActivityEnterViewAnimateFromTop = frameLayout2.getTop() + captionEditTextTopOffset;
frameLayout2.invalidate();
updateCommentTextViewPosition();
}
@Override
protected void bottomPanelTranslationY(float translation) {
bottomPannelTranslation = translation;
// buttonsRecyclerView.setTranslationY(translation);
frameLayout2.setTranslationY(translation);
writeButtonContainer.setTranslationY(translation);
selectedCountView.setTranslationY(translation);
frameLayout2.invalidate();
updateLayout(currentAttachLayout, true, 0);
}
@Override
protected void closeParent() {
ChatAttachAlert.super.dismiss();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
updateCommentTextViewPosition();
}
};
commentTextView.setHint(LocaleController.getString("AddCaption", R.string.AddCaption));
commentTextView.onResume();
commentTextView.getEditText().addTextChangedListener(new TextWatcher() {
private boolean processChange;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if ((count - before) >= 1) {
processChange = true;
}
if (mentionContainer == null) {
createMentionsContainer();
}
if (mentionContainer.getAdapter() != null) {
mentionContainer.getAdapter().searchUsernameOrHashtag(charSequence, commentTextView.getEditText().getSelectionStart(), null, false, false);
}
}
@Override
public void afterTextChanged(Editable editable) {
if (processChange) {
ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class);
for (int i = 0; i < spans.length; i++) {
editable.removeSpan(spans[i]);
}
Emoji.replaceEmoji(editable, commentTextView.getEditText().getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false);
processChange = false;
}
int beforeLimit;
codepointCount = Character.codePointCount(editable, 0, editable.length());
boolean sendButtonEnabledLocal = true;
if (currentLimit > 0 && (beforeLimit = currentLimit - codepointCount) <= 100) {
if (beforeLimit < -9999) {
beforeLimit = -9999;
}
captionLimitView.setNumber(beforeLimit, captionLimitView.getVisibility() == View.VISIBLE);
if (captionLimitView.getVisibility() != View.VISIBLE) {
captionLimitView.setVisibility(View.VISIBLE);
captionLimitView.setAlpha(0);
captionLimitView.setScaleX(0.5f);
captionLimitView.setScaleY(0.5f);
}
captionLimitView.animate().setListener(null).cancel();
captionLimitView.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(100).start();
if (beforeLimit < 0) {
sendButtonEnabledLocal = false;
captionLimitView.setTextColor(getThemedColor(Theme.key_text_RedRegular));
} else {
captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
}
} else {
captionLimitView.animate().alpha(0).scaleX(0.5f).scaleY(0.5f).setDuration(100).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
captionLimitView.setVisibility(View.GONE);
}
});
}
if (sendButtonEnabled != sendButtonEnabledLocal) {
sendButtonEnabled = sendButtonEnabledLocal;
if (sendButtonColorAnimator != null) {
sendButtonColorAnimator.cancel();
}
sendButtonColorAnimator = ValueAnimator.ofFloat(sendButtonEnabled ? 0 : 1f, sendButtonEnabled ? 1f : 0);
sendButtonColorAnimator.addUpdateListener(valueAnimator -> {
sendButtonEnabledProgress = (float) valueAnimator.getAnimatedValue();
int color = getThemedColor(Theme.key_dialogFloatingIcon);
int defaultAlpha = Color.alpha(color);
writeButton.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (defaultAlpha * (0.58f + 0.42f * sendButtonEnabledProgress))), PorterDuff.Mode.MULTIPLY));
selectedCountView.invalidate();
});
sendButtonColorAnimator.setDuration(150).start();
}
// if (!captionLimitBulletinShown && !MessagesController.getInstance(currentAccount).premiumFeaturesBlocked() && !UserConfig.getInstance(currentAccount).isPremium() && codepointCount > MessagesController.getInstance(currentAccount).captionLengthLimitDefault && codepointCount < MessagesController.getInstance(currentAccount).captionLengthLimitPremium) {
// captionLimitBulletinShown = true;
// showCaptionLimitBulletin(parentFragment);
// }
}
});
frameLayout2.addView(commentTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 84, 0));
frameLayout2.setClipChildren(false);
commentTextView.setClipChildren(false);
writeButtonContainer = new FrameLayout(context) {
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (currentAttachLayout == photoLayout) {
info.setText(LocaleController.formatPluralString("AccDescrSendPhotos", photoLayout.getSelectedItemsCount()));
} else if (currentAttachLayout == documentLayout) {
info.setText(LocaleController.formatPluralString("AccDescrSendFiles", documentLayout.getSelectedItemsCount()));
} else if (currentAttachLayout == audioLayout) {
info.setText(LocaleController.formatPluralString("AccDescrSendAudio", audioLayout.getSelectedItemsCount()));
}
info.setClassName(Button.class.getName());
info.setLongClickable(true);
info.setClickable(true);
}
};
writeButtonContainer.setFocusable(true);
writeButtonContainer.setFocusableInTouchMode(true);
writeButtonContainer.setVisibility(View.INVISIBLE);
writeButtonContainer.setScaleX(0.2f);
writeButtonContainer.setScaleY(0.2f);
writeButtonContainer.setAlpha(0.0f);
containerView.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 6, 10));
writeButton = new ImageView(context);
writeButtonDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, writeButtonDrawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
writeButtonDrawable = combinedDrawable;
}
writeButton.setBackgroundDrawable(writeButtonDrawable);
writeButton.setImageResource(R.drawable.attach_send);
writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
writeButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
writeButton.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
writeButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
}
});
}
writeButtonContainer.addView(writeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, Gravity.LEFT | Gravity.TOP, Build.VERSION.SDK_INT >= 21 ? 2 : 0, 0, 0, 0));
writeButton.setOnClickListener(v -> {
if (currentLimit - codepointCount < 0) {
AndroidUtilities.shakeView(captionLimitView);
try {
captionLimitView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
} catch (Exception ignored) {
}
if (!MessagesController.getInstance(currentAccount).premiumFeaturesBlocked() && MessagesController.getInstance(currentAccount).captionLengthLimitPremium > codepointCount) {
showCaptionLimitBulletin(parentFragment);
}
return;
}
if (editingMessageObject == null && baseFragment instanceof ChatActivity && ((ChatActivity) baseFragment).isInScheduleMode()) {
AlertsCreator.createScheduleDatePickerDialog(getContext(), ((ChatActivity) baseFragment).getDialogId(), (notify, scheduleDate) -> {
if (currentAttachLayout == photoLayout || currentAttachLayout == photoPreviewLayout) {
sendPressed(notify, scheduleDate);
} else {
currentAttachLayout.sendSelectedItems(notify, scheduleDate);
allowPassConfirmationAlert = true;
dismiss();
}
}, resourcesProvider);
} else {
if (currentAttachLayout == photoLayout || currentAttachLayout == photoPreviewLayout) {
sendPressed(true, 0);
} else {
currentAttachLayout.sendSelectedItems(true, 0);
allowPassConfirmationAlert = true;
dismiss();
}
}
});
writeButton.setOnLongClickListener(view -> {
if ((dialogId == 0 && !(baseFragment instanceof ChatActivity)) || editingMessageObject != null || currentLimit - codepointCount < 0) {
return false;
}
ChatActivity chatActivity = null;
TLRPC.User user = null;
long dialogId = this.dialogId;
if (baseFragment instanceof ChatActivity) {
chatActivity = (ChatActivity) baseFragment;
TLRPC.Chat chat = chatActivity.getCurrentChat();
user = chatActivity.getCurrentUser();
if (chatActivity.isInScheduleMode() || chatActivity.getChatMode() == ChatActivity.MODE_QUICK_REPLIES) {
return false;
}
dialogId = chatActivity.getDialogId();
} else {
user = MessagesController.getInstance(currentAccount).getUser(dialogId);
}
sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext(), resourcesProvider);
sendPopupLayout.setAnimationEnabled(false);
sendPopupLayout.setOnTouchListener(new View.OnTouchListener() {
private Rect popupRect = new Rect();
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
v.getHitRect(popupRect);
if (!popupRect.contains((int) event.getX(), (int) event.getY())) {
sendPopupWindow.dismiss();
}
}
}
return false;
}
});
sendPopupLayout.setDispatchKeyEventListener(keyEvent -> {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
});
sendPopupLayout.setShownFromBottom(false);
itemCells = new ActionBarMenuSubItem[2];
int i = 0;
for (int a = 0; a < 2; a++) {
if (a == 0) {
if ((chatActivity != null && !chatActivity.canScheduleMessage()) || !currentAttachLayout.canScheduleMessages()) {
continue;
}
} else if (a == 1 && UserObject.isUserSelf(user)) {
continue;
}
int num = a;
itemCells[a] = new ActionBarMenuSubItem(getContext(), a == 0, a == 1, resourcesProvider);
if (num == 0) {
if (UserObject.isUserSelf(user)) {
itemCells[a].setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_calendar2);
} else {
itemCells[a].setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_calendar2);
}
} else if (num == 1) {
itemCells[a].setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off);
}
itemCells[a].setMinimumWidth(AndroidUtilities.dp(196));
sendPopupLayout.addView(itemCells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
long finalDialogId = dialogId;
itemCells[a].setOnClickListener(v -> {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
if (num == 0) {
AlertsCreator.createScheduleDatePickerDialog(getContext(), finalDialogId, (notify, scheduleDate) -> {
if (currentAttachLayout == photoLayout || currentAttachLayout == photoPreviewLayout) {
sendPressed(notify, scheduleDate);
} else {
currentAttachLayout.sendSelectedItems(notify, scheduleDate);
dismiss();
}
}, resourcesProvider);
} else if (num == 1) {
if (currentAttachLayout == photoLayout || currentAttachLayout == photoPreviewLayout) {
sendPressed(false, 0);
} else {
currentAttachLayout.sendSelectedItems(false, 0);
dismiss();
}
}
});
i++;
}
sendPopupLayout.setupRadialSelectors(getThemedColor(Theme.key_dialogButtonSelector));
sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
sendPopupWindow.setAnimationEnabled(false);
sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2);
sendPopupWindow.setOutsideTouchable(true);
sendPopupWindow.setClippingEnabled(true);
sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
sendPopupWindow.getContentView().setFocusableInTouchMode(true);
sendPopupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
sendPopupWindow.setFocusable(true);
int[] location = new int[2];
view.getLocationInWindow(location);
sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - sendPopupLayout.getMeasuredWidth() + AndroidUtilities.dp(8), location[1] - sendPopupLayout.getMeasuredHeight() - AndroidUtilities.dp(2));
sendPopupWindow.dimBehind();
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return false;
});
textPaint.setTextSize(AndroidUtilities.dp(12));
textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
selectedCountView = new View(context) {
@Override
protected void onDraw(Canvas canvas) {
String text = String.format("%d", Math.max(1, currentAttachLayout.getSelectedItemsCount()));
int textSize = (int) Math.ceil(textPaint.measureText(text));
int size = Math.max(AndroidUtilities.dp(16) + textSize, AndroidUtilities.dp(24));
int cx = getMeasuredWidth() / 2;
int color = getThemedColor(Theme.key_dialogRoundCheckBoxCheck);
textPaint.setColor(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * (0.58 + 0.42 * sendButtonEnabledProgress))));
paint.setColor(getThemedColor(Theme.key_dialogBackground));
rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight());
canvas.drawRoundRect(rect, AndroidUtilities.dp(12), AndroidUtilities.dp(12), paint);
paint.setColor(getThemedColor(Theme.key_chat_attachCheckBoxBackground));
rect.set(cx - size / 2 + AndroidUtilities.dp(2), AndroidUtilities.dp(2), cx + size / 2 - AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(2));
canvas.drawRoundRect(rect, AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint);
canvas.drawText(text, cx - textSize / 2, AndroidUtilities.dp(16.2f), textPaint);
}
};
selectedCountView.setAlpha(0.0f);
selectedCountView.setScaleX(0.2f);
selectedCountView.setScaleY(0.2f);
containerView.addView(selectedCountView, LayoutHelper.createFrame(42, 24, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -8, 9));
if (forceDarkTheme) {
checkColors();
navBarColorKey = -1;
}
passcodeView = new PasscodeView(context);
containerView.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
}
@Override
protected void onStart() {
super.onStart();
Context context = getContext();
if (context instanceof ContextWrapper && !(context instanceof LaunchActivity)) {
context = ((ContextWrapper) context).getBaseContext();
}
if (context instanceof LaunchActivity) {
((LaunchActivity) context).addOverlayPasscodeView(passcodeView);
}
}
@Override
protected void onStop() {
super.onStop();
Context context = getContext();
if (context instanceof ContextWrapper && !(context instanceof LaunchActivity)) {
context = ((ContextWrapper) context).getBaseContext();
}
if (context instanceof LaunchActivity) {
((LaunchActivity) context).removeOverlayPasscodeView(passcodeView);
}
}
public void updateCommentTextViewPosition() {
commentTextView.getLocationOnScreen(commentTextViewLocation);
if (mentionContainer != null) {
float y = -commentTextView.getHeight();
if (mentionContainer.getY() != y) {
mentionContainer.setTranslationY(y);
mentionContainer.invalidate();
}
}
}
public int getCommentTextViewTop() {
return commentTextViewLocation[1];
}
private void showCaptionLimitBulletin(BaseFragment parentFragment) {
if (!(parentFragment instanceof ChatActivity) || !ChatObject.isChannelAndNotMegaGroup(((ChatActivity) parentFragment).getCurrentChat())) {
return;
}
BulletinFactory.of(sizeNotifierFrameLayout, resourcesProvider).createCaptionLimitBulletin(MessagesController.getInstance(currentAccount).captionLengthLimitPremium, () -> {
dismiss(true);
if (parentFragment != null) {
parentFragment.presentFragment(new PremiumPreviewFragment("caption_limit"));
}
}).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (baseFragment != null) {
AndroidUtilities.setLightStatusBar(getWindow(), baseFragment.isLightStatusBar());
}
}
private boolean isLightStatusBar() {
int color = getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground);
return ColorUtils.calculateLuminance(color) > 0.7f;
}
public void onLongClickBotButton(TLRPC.TL_attachMenuBot attachMenuBot, TLRPC.User currentUser) {
String botName = attachMenuBot != null ? attachMenuBot.short_name : UserObject.getUserName(currentUser);
String description;
TLRPC.TL_attachMenuBot currentBot = null;
for (TLRPC.TL_attachMenuBot bot : MediaDataController.getInstance(currentAccount).getAttachMenuBots().bots) {
if (bot.bot_id == currentUser.id) {
currentBot = bot;
break;
}
}
description = LocaleController.formatString("BotRemoveFromMenu", R.string.BotRemoveFromMenu, botName);
new AlertDialog.Builder(getContext())
.setTitle(LocaleController.getString(R.string.BotRemoveFromMenuTitle))
.setMessage(AndroidUtilities.replaceTags(attachMenuBot != null ? description : LocaleController.formatString("BotRemoveInlineFromMenu", R.string.BotRemoveInlineFromMenu, botName)))
.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
if (attachMenuBot != null) {
TLRPC.TL_messages_toggleBotInAttachMenu req = new TLRPC.TL_messages_toggleBotInAttachMenu();
req.bot = MessagesController.getInstance(currentAccount).getInputUser(currentUser);
req.enabled = false;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
MediaDataController.getInstance(currentAccount).loadAttachMenuBots(false, true);
if (currentAttachLayout == botAttachLayouts.get(attachMenuBot.bot_id)) {
showLayout(photoLayout);
}
}), ConnectionsManager.RequestFlagInvokeAfter | ConnectionsManager.RequestFlagFailOnServerErrors);
} else {
MediaDataController.getInstance(currentAccount).removeInline(currentUser.id);
}
})
.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null)
.show();
}
@Override
protected boolean shouldOverlayCameraViewOverNavBar() {
return currentAttachLayout == photoLayout && photoLayout.cameraExpanded;
}
@Override
public void show() {
super.show();
buttonPressed = false;
if (baseFragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
calcMandatoryInsets = chatActivity.isKeyboardVisible();
}
openTransitionFinished = false;
if (Build.VERSION.SDK_INT >= 30) {
navBarColorKey = -1;
navBarColor = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_windowBackgroundGray), 0);
AndroidUtilities.setNavigationBarColor(getWindow(), navBarColor, false);
AndroidUtilities.setLightNavigationBar(getWindow(), AndroidUtilities.computePerceivedBrightness(navBarColor) > 0.721);
}
}
public void setEditingMessageObject(MessageObject messageObject) {
if (editingMessageObject == messageObject) {
return;
}
editingMessageObject = messageObject;
if (editingMessageObject != null) {
maxSelectedPhotos = 1;
allowOrder = false;
} else {
maxSelectedPhotos = -1;
allowOrder = true;
}
buttonsAdapter.notifyDataSetChanged();
}
public MessageObject getEditingMessageObject() {
return editingMessageObject;
}
protected void applyCaption() {
if (commentTextView.length() <= 0) {
return;
}
currentAttachLayout.applyCaption(commentTextView.getText());
}
private void sendPressed(boolean notify, int scheduleDate) {
if (buttonPressed) {
return;
}
if (baseFragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
TLRPC.Chat chat = chatActivity.getCurrentChat();
TLRPC.User user = chatActivity.getCurrentUser();
if (user != null || ChatObject.isChannel(chat) && chat.megagroup || !ChatObject.isChannel(chat)) {
MessagesController.getNotificationsSettings(currentAccount).edit().putBoolean("silent_" + chatActivity.getDialogId(), !notify).commit();
}
}
if (checkCaption(commentTextView.getText())) {
return;
}
applyCaption();
buttonPressed = true;
delegate.didPressedButton(7, true, notify, scheduleDate, false);
}
public void showLayout(AttachAlertLayout layout) {
long newId = selectedId;
if (layout == restrictedLayout) {
newId = restrictedLayout.id;
} else if (layout == photoLayout) {
newId = 1;
} else if (layout == audioLayout) {
newId = 3;
} else if (layout == documentLayout) {
newId = 4;
} else if (layout == contactsLayout) {
newId = 5;
} else if (layout == locationLayout) {
newId = 6;
} else if (layout == pollLayout) {
newId = 9;
} else if (layout == colorsLayout) {
newId = 10;
} else if (layout == quickRepliesLayout) {
newId = 11;
}
showLayout(layout, newId);
}
private void showLayout(AttachAlertLayout layout, long newId) {
showLayout(layout, newId, true);
}
private void showLayout(AttachAlertLayout layout, long newId, boolean animated) {
if (viewChangeAnimator != null || commentsAnimator != null) {
return;
}
if (currentAttachLayout == layout) {
currentAttachLayout.scrollToTop();
return;
}
botButtonWasVisible = false;
botButtonProgressWasVisible = false;
botMainButtonOffsetY = 0;
botMainButtonTextView.setVisibility(View.GONE);
botProgressView.setAlpha(0f);
botProgressView.setScaleX(0.1f);
botProgressView.setScaleY(0.1f);
botProgressView.setVisibility(View.GONE);
buttonsRecyclerView.setAlpha(1f);
buttonsRecyclerView.setTranslationY(botMainButtonOffsetY);
for (int i = 0; i < botAttachLayouts.size(); i++) {
botAttachLayouts.valueAt(i).setMeasureOffsetY(0);
}
selectedId = newId;
int count = buttonsRecyclerView.getChildCount();
for (int a = 0; a < count; a++) {
View child = buttonsRecyclerView.getChildAt(a);
if (child instanceof AttachButton) {
AttachButton attachButton = (AttachButton) child;
attachButton.updateCheckedState(true);
} else if (child instanceof AttachBotButton) {
AttachBotButton attachButton = (AttachBotButton) child;
attachButton.updateCheckedState(true);
}
}
int t = currentAttachLayout.getFirstOffset() - AndroidUtilities.dp(11) - scrollOffsetY[0];
nextAttachLayout = layout;
if (Build.VERSION.SDK_INT >= 20) {
container.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
actionBar.setVisibility(nextAttachLayout.needsActionBar() != 0 ? View.VISIBLE : View.INVISIBLE);
actionBarShadow.setVisibility(actionBar.getVisibility());
if (actionBar.isSearchFieldVisible()) {
actionBar.closeSearchField();
}
currentAttachLayout.onHide();
if (nextAttachLayout == photoLayout) {
photoLayout.setCheckCameraWhenShown(true);
}
nextAttachLayout.onShow(currentAttachLayout);
nextAttachLayout.setVisibility(View.VISIBLE);
if (layout.getParent() != null) {
containerView.removeView(nextAttachLayout);
}
int index = containerView.indexOfChild(currentAttachLayout);
if (nextAttachLayout.getParent() != containerView) {
containerView.addView(nextAttachLayout, nextAttachLayout == locationLayout ? index : index + 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
}
Runnable onEnd = () -> {
if (Build.VERSION.SDK_INT >= 20) {
container.setLayerType(View.LAYER_TYPE_NONE, null);
}
viewChangeAnimator = null;
if ((currentAttachLayout != photoLayout && nextAttachLayout != photoPreviewLayout) && (currentAttachLayout != nextAttachLayout && currentAttachLayout != photoPreviewLayout)) {
containerView.removeView(currentAttachLayout);
}
currentAttachLayout.setVisibility(View.GONE);
currentAttachLayout.onHidden();
nextAttachLayout.onShown();
currentAttachLayout = nextAttachLayout;
nextAttachLayout = null;
scrollOffsetY[0] = scrollOffsetY[1];
};
if (!(currentAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview || nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview)) {
if (animated) {
AnimatorSet animator = new AnimatorSet();
nextAttachLayout.setAlpha(0.0f);
nextAttachLayout.setTranslationY(AndroidUtilities.dp(78));
animator.playTogether(
ObjectAnimator.ofFloat(currentAttachLayout, View.TRANSLATION_Y, AndroidUtilities.dp(78) + t),
ObjectAnimator.ofFloat(currentAttachLayout, ATTACH_ALERT_LAYOUT_TRANSLATION, 0.0f, 1.0f),
ObjectAnimator.ofFloat(actionBar, View.ALPHA, actionBar.getAlpha(), 0f)
);
animator.setDuration(180);
animator.setStartDelay(20);
animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
currentAttachLayout.setAlpha(0.0f);
SpringAnimation springAnimation = new SpringAnimation(nextAttachLayout, DynamicAnimation.TRANSLATION_Y, 0);
springAnimation.getSpring().setDampingRatio(0.75f);
springAnimation.getSpring().setStiffness(500.0f);
springAnimation.addUpdateListener((animation12, value, velocity) -> {
if (nextAttachLayout == pollLayout || (isPhotoPicker && viewChangeAnimator != null)) {
updateSelectedPosition(1);
}
nextAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
containerView.invalidate();
});
springAnimation.addEndListener((animation1, canceled, value, velocity) -> {
onEnd.run();
updateSelectedPosition(0);
});
viewChangeAnimator = springAnimation;
springAnimation.start();
}
});
viewChangeAnimator = animator;
animator.start();
} else {
currentAttachLayout.setAlpha(0.0f);
onEnd.run();
updateSelectedPosition(0);
containerView.invalidate();
}
} else {
int width = Math.max(nextAttachLayout.getWidth(), currentAttachLayout.getWidth());
if (nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview) {
nextAttachLayout.setTranslationX(width);
if (currentAttachLayout instanceof ChatAttachAlertPhotoLayout) {
ChatAttachAlertPhotoLayout photoLayout = (ChatAttachAlertPhotoLayout) currentAttachLayout;
if (photoLayout.cameraView != null) {
photoLayout.cameraView.setVisibility(View.INVISIBLE);
photoLayout.cameraIcon.setVisibility(View.INVISIBLE);
photoLayout.cameraCell.setVisibility(View.VISIBLE);
}
}
} else {
currentAttachLayout.setTranslationX(-width);
if (nextAttachLayout == photoLayout) {
ChatAttachAlertPhotoLayout photoLayout = (ChatAttachAlertPhotoLayout) nextAttachLayout;
if (photoLayout.cameraView != null) {
photoLayout.cameraView.setVisibility(View.VISIBLE);
photoLayout.cameraIcon.setVisibility(View.VISIBLE);
}
}
}
nextAttachLayout.setAlpha(1);
currentAttachLayout.setAlpha(1);
boolean showActionBar = nextAttachLayout.getCurrentItemTop() <= layout.getButtonsHideOffset();
if (animated) {
ATTACH_ALERT_LAYOUT_TRANSLATION.set(currentAttachLayout, 0.0f);
AndroidUtilities.runOnUIThread(() -> {
float fromActionBarAlpha = actionBar.getAlpha();
float toActionBarAlpha = showActionBar ? 1f : 0f;
SpringAnimation springAnimation = new SpringAnimation(new FloatValueHolder(0));
springAnimation.addUpdateListener((animation, value, velocity) -> {
float f = value / 500f;
ATTACH_ALERT_LAYOUT_TRANSLATION.set(currentAttachLayout, f);
actionBar.setAlpha(AndroidUtilities.lerp(fromActionBarAlpha, toActionBarAlpha, f));
updateLayout(currentAttachLayout, false, 0);
updateLayout(nextAttachLayout, false, 0);
float mediaPreviewAlpha = nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview && !showActionBar ? f : 1f - f;
mediaPreviewView.setAlpha(mediaPreviewAlpha);
selectedView.setAlpha(1f - mediaPreviewAlpha);
selectedView.setTranslationX(mediaPreviewAlpha * -AndroidUtilities.dp(16));
mediaPreviewView.setTranslationX((1f - mediaPreviewAlpha) * AndroidUtilities.dp(16));
});
springAnimation.addEndListener((animation, canceled, value, velocity) -> {
currentAttachLayout.onHideShowProgress(1f);
nextAttachLayout.onHideShowProgress(1f);
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
nextAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
containerView.invalidate();
actionBar.setTag(showActionBar ? 1 : null);
onEnd.run();
});
springAnimation.setSpring(new SpringForce(500f));
springAnimation.getSpring().setDampingRatio(1f);
springAnimation.getSpring().setStiffness(1000.0f);
springAnimation.start();
viewChangeAnimator = springAnimation;
});
} else {
currentAttachLayout.onHideShowProgress(1f);
nextAttachLayout.onHideShowProgress(1f);
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
nextAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
containerView.invalidate();
ATTACH_ALERT_LAYOUT_TRANSLATION.set(currentAttachLayout, 1.0f);
actionBar.setTag(showActionBar ? 1 : null);
onEnd.run();
}
}
}
public AttachAlertLayout getCurrentAttachLayout() {
return currentAttachLayout;
}
public ChatAttachAlertPhotoLayoutPreview getPhotoPreviewLayout() {
return photoPreviewLayout;
}
public void updatePhotoPreview(boolean show) {
if (show) {
if (!canOpenPreview) {
return;
}
if (photoPreviewLayout == null) {
photoPreviewLayout = new ChatAttachAlertPhotoLayoutPreview(this, getContext(), (parentThemeDelegate != null ? parentThemeDelegate : resourcesProvider));
photoPreviewLayout.bringToFront();
}
showLayout(currentAttachLayout == photoPreviewLayout ? photoLayout : photoPreviewLayout);
} else {
showLayout(photoLayout);
}
}
public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == BasePermissionsActivity.REQUEST_CODE_ATTACH_CONTACT && grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openContactsLayout();
} else if (requestCode == 30 && locationLayout != null && currentAttachLayout == locationLayout && isShowing()) {
locationLayout.openShareLiveLocation();
}
}
private void openContactsLayout() {
if (!plainTextEnabled) {
restrictedLayout = new ChatAttachRestrictedLayout(5, this, getContext(), resourcesProvider);
showLayout(restrictedLayout);
}
if (contactsLayout == null) {
layouts[2] = contactsLayout = new ChatAttachAlertContactsLayout(this, getContext(), resourcesProvider);
contactsLayout.setDelegate(new ChatAttachAlertContactsLayout.PhonebookShareAlertDelegate() {
@Override
public void didSelectContact(TLRPC.User user, boolean notify, int scheduleDate) {
((ChatActivity) baseFragment).sendContact(user, notify, scheduleDate);
}
@Override
public void didSelectContacts(ArrayList<TLRPC.User> users, String caption, boolean notify, int scheduleDate) {
((ChatActivity) baseFragment).sendContacts(users, caption, notify, scheduleDate);
}
});
}
if (baseFragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
TLRPC.Chat currentChat = chatActivity.getCurrentChat();
contactsLayout.setMultipleSelectionAllowed(!(currentChat != null && !ChatObject.hasAdminRights(currentChat) && currentChat.slowmode_enabled));
}
showLayout(contactsLayout);
}
private void openQuickRepliesLayout() {
if (quickRepliesLayout == null) {
layouts[7] = quickRepliesLayout = new ChatAttachAlertQuickRepliesLayout(this, getContext(), resourcesProvider);
}
showLayout(quickRepliesLayout);
}
public boolean checkCanRemoveRestrictionsByBoosts() {
return (baseFragment instanceof ChatActivity) && ((ChatActivity) baseFragment).checkCanRemoveRestrictionsByBoosts();
}
private void openAudioLayout(boolean show) {
if (!musicEnabled) {
if (show) {
restrictedLayout = new ChatAttachRestrictedLayout(3, this, getContext(), resourcesProvider);
showLayout(restrictedLayout);
}
}
if (audioLayout == null) {
layouts[3] = audioLayout = new ChatAttachAlertAudioLayout(this, getContext(), resourcesProvider);
audioLayout.setDelegate((audios, caption, notify, scheduleDate) -> {
if (baseFragment != null && baseFragment instanceof ChatActivity) {
((ChatActivity) baseFragment).sendAudio(audios, caption, notify, scheduleDate);
} else if (delegate != null) {
delegate.sendAudio(audios, caption, notify, scheduleDate);
}
});
}
if (baseFragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
TLRPC.Chat currentChat = chatActivity.getCurrentChat();
audioLayout.setMaxSelectedFiles(currentChat != null && !ChatObject.hasAdminRights(currentChat) && currentChat.slowmode_enabled || editingMessageObject != null ? 1 : -1);
}
if (show) {
showLayout(audioLayout);
}
}
public void openColorsLayout() {
if (colorsLayout == null) {
colorsLayout = new ChatAttachAlertColorsLayout(this, getContext(), resourcesProvider);
colorsLayout.setDelegate((wallpaper -> {
if (delegate != null) {
delegate.onWallpaperSelected(wallpaper);
}
}));
}
showLayout(colorsLayout);
}
private void openDocumentsLayout(boolean show) {
if (!documentsEnabled) {
if (show) {
restrictedLayout = new ChatAttachRestrictedLayout(4, this, getContext(), resourcesProvider);
showLayout(restrictedLayout);
}
}
if (documentLayout == null) {
int type = isSoundPicker ? ChatAttachAlertDocumentLayout.TYPE_RINGTONE : ChatAttachAlertDocumentLayout.TYPE_DEFAULT;
layouts[4] = documentLayout = new ChatAttachAlertDocumentLayout(this, getContext(), type, resourcesProvider);
documentLayout.setDelegate(new ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate() {
@Override
public void didSelectFiles(ArrayList<String> files, String caption, ArrayList<MessageObject> fmessages, boolean notify, int scheduleDate) {
if (documentsDelegate != null) {
documentsDelegate.didSelectFiles(files, caption, fmessages, notify, scheduleDate);
} else if (baseFragment instanceof ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate) {
((ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate) baseFragment).didSelectFiles(files, caption, fmessages, notify, scheduleDate);
} else if (baseFragment instanceof PassportActivity) {
((PassportActivity) baseFragment).didSelectFiles(files, caption, notify, scheduleDate);
}
}
@Override
public void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos, boolean notify, int scheduleDate) {
if (documentsDelegate != null) {
documentsDelegate.didSelectPhotos(photos, notify, scheduleDate);
} else if (baseFragment instanceof ChatActivity) {
((ChatActivity) baseFragment).didSelectPhotos(photos, notify, scheduleDate);
} else if (baseFragment instanceof PassportActivity) {
((PassportActivity) baseFragment).didSelectPhotos(photos, notify, scheduleDate);
}
}
@Override
public void startDocumentSelectActivity() {
if (documentsDelegate != null) {
documentsDelegate.startDocumentSelectActivity();
} else if (baseFragment instanceof ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate) {
((ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate) baseFragment).startDocumentSelectActivity();
} else if (baseFragment instanceof PassportActivity) {
((PassportActivity) baseFragment).startDocumentSelectActivity();
}
}
@Override
public void startMusicSelectActivity() {
openAudioLayout(true);
}
});
}
if (baseFragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
TLRPC.Chat currentChat = chatActivity.getCurrentChat();
documentLayout.setMaxSelectedFiles(currentChat != null && !ChatObject.hasAdminRights(currentChat) && currentChat.slowmode_enabled || editingMessageObject != null ? 1 : -1);
} else {
documentLayout.setMaxSelectedFiles(maxSelectedPhotos);
documentLayout.setCanSelectOnlyImageFiles(!isSoundPicker && !allowEnterCaption);
}
documentLayout.isSoundPicker = isSoundPicker;
if (show) {
showLayout(documentLayout);
}
}
private boolean showCommentTextView(boolean show, boolean animated) {
if (show == (frameLayout2.getTag() != null)) {
return false;
}
if (commentsAnimator != null) {
commentsAnimator.cancel();
}
frameLayout2.setTag(show ? 1 : null);
if (commentTextView.getEditText().isFocused()) {
AndroidUtilities.hideKeyboard(commentTextView.getEditText());
}
commentTextView.hidePopup(true);
if (show) {
if (!isSoundPicker) {
frameLayout2.setVisibility(View.VISIBLE);
}
writeButtonContainer.setVisibility(View.VISIBLE);
if (!typeButtonsAvailable && !isSoundPicker) {
shadow.setVisibility(View.VISIBLE);
}
} else if (typeButtonsAvailable) {
buttonsRecyclerView.setVisibility(View.VISIBLE);
}
if (animated) {
commentsAnimator = new AnimatorSet();
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(frameLayout2, View.ALPHA, show ? 1.0f : 0.0f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.SCALE_X, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.SCALE_Y, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(writeButtonContainer, View.ALPHA, show ? 1.0f : 0.0f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.SCALE_X, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.SCALE_Y, show ? 1.0f : 0.2f));
animators.add(ObjectAnimator.ofFloat(selectedCountView, View.ALPHA, show ? 1.0f : 0.0f));
if (actionBar.getTag() != null) {
animators.add(ObjectAnimator.ofFloat(frameLayout2, View.TRANSLATION_Y, show ? 0.0f : AndroidUtilities.dp(48)));
animators.add(ObjectAnimator.ofFloat(shadow, View.TRANSLATION_Y, show ? AndroidUtilities.dp(36) : AndroidUtilities.dp(48 + 36)));
animators.add(ObjectAnimator.ofFloat(shadow, View.ALPHA, show ? 1.0f : 0.0f));
} else if (typeButtonsAvailable) {
animators.add(ObjectAnimator.ofFloat(buttonsRecyclerView, View.TRANSLATION_Y, show ? AndroidUtilities.dp(36) : 0));
animators.add(ObjectAnimator.ofFloat(shadow, View.TRANSLATION_Y, show ? AndroidUtilities.dp(36) : 0));
} else if (!isSoundPicker) {
shadow.setTranslationY(AndroidUtilities.dp(36) + botMainButtonOffsetY);
animators.add(ObjectAnimator.ofFloat(shadow, View.ALPHA, show ? 1.0f : 0.0f));
}
commentsAnimator.playTogether(animators);
commentsAnimator.setInterpolator(new DecelerateInterpolator());
commentsAnimator.setDuration(180);
commentsAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (animation.equals(commentsAnimator)) {
if (!show) {
if (!isSoundPicker) {
frameLayout2.setVisibility(View.INVISIBLE);
}
writeButtonContainer.setVisibility(View.INVISIBLE);
if (!typeButtonsAvailable && !isSoundPicker) {
shadow.setVisibility(View.INVISIBLE);
}
} else if (typeButtonsAvailable) {
if (currentAttachLayout == null || currentAttachLayout.shouldHideBottomButtons()) {
buttonsRecyclerView.setVisibility(View.INVISIBLE);
}
}
commentsAnimator = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (animation.equals(commentsAnimator)) {
commentsAnimator = null;
}
}
});
commentsAnimator.start();
} else {
frameLayout2.setAlpha(show ? 1.0f : 0.0f);
writeButtonContainer.setScaleX(show ? 1.0f : 0.2f);
writeButtonContainer.setScaleY(show ? 1.0f : 0.2f);
writeButtonContainer.setAlpha(show ? 1.0f : 0.0f);
selectedCountView.setScaleX(show ? 1.0f : 0.2f);
selectedCountView.setScaleY(show ? 1.0f : 0.2f);
selectedCountView.setAlpha(show ? 1.0f : 0.0f);
if (actionBar.getTag() != null) {
frameLayout2.setTranslationY(show ? 0.0f : AndroidUtilities.dp(48));
shadow.setTranslationY((show ? AndroidUtilities.dp(36) : AndroidUtilities.dp(48 + 36)) + botMainButtonOffsetY);
shadow.setAlpha(show ? 1.0f : 0.0f);
} else if (typeButtonsAvailable) {
if (currentAttachLayout == null || currentAttachLayout.shouldHideBottomButtons()) {
buttonsRecyclerView.setTranslationY(show ? AndroidUtilities.dp(36) : 0);
}
shadow.setTranslationY((show ? AndroidUtilities.dp(36) : 0) + botMainButtonOffsetY);
} else {
shadow.setTranslationY(AndroidUtilities.dp(36) + botMainButtonOffsetY);
shadow.setAlpha(show ? 1.0f : 0.0f);
}
if (!show) {
frameLayout2.setVisibility(View.INVISIBLE);
writeButtonContainer.setVisibility(View.INVISIBLE);
if (!typeButtonsAvailable) {
shadow.setVisibility(View.INVISIBLE);
}
}
}
return true;
}
private final Property<ChatAttachAlert, Float> ATTACH_ALERT_PROGRESS = new AnimationProperties.FloatProperty<ChatAttachAlert>("openProgress") {
private float openProgress;
@Override
public void setValue(ChatAttachAlert object, float value) {
for (int a = 0, N = buttonsRecyclerView.getChildCount(); a < N; a++) {
float startTime = 32.0f * (3 - a);
View child = buttonsRecyclerView.getChildAt(a);
float scale;
if (value > startTime) {
float elapsedTime = value - startTime;
if (elapsedTime <= 200.0f) {
scale = 1.1f * CubicBezierInterpolator.EASE_OUT.getInterpolation(elapsedTime / 200.0f);
child.setAlpha(CubicBezierInterpolator.EASE_BOTH.getInterpolation(elapsedTime / 200.0f));
} else {
child.setAlpha(1.0f);
elapsedTime -= 200.0f;
if (elapsedTime <= 100.0f) {
scale = 1.1f - 0.1f * CubicBezierInterpolator.EASE_IN.getInterpolation(elapsedTime / 100.0f);
} else {
scale = 1.0f;
}
}
} else {
scale = 0;
}
if (child instanceof AttachButton) {
AttachButton attachButton = (AttachButton) child;
attachButton.textView.setScaleX(scale);
attachButton.textView.setScaleY(scale);
attachButton.imageView.setScaleX(scale);
attachButton.imageView.setScaleY(scale);
} else if (child instanceof AttachBotButton) {
AttachBotButton attachButton = (AttachBotButton) child;
attachButton.nameTextView.setScaleX(scale);
attachButton.nameTextView.setScaleY(scale);
attachButton.imageView.setScaleX(scale);
attachButton.imageView.setScaleY(scale);
}
}
}
@Override
public Float get(ChatAttachAlert object) {
return openProgress;
}
};
@Override
protected void cancelSheetAnimation() {
if (currentSheetAnimation != null) {
currentSheetAnimation.cancel();
if (appearSpringAnimation != null) {
appearSpringAnimation.cancel();
}
if (buttonsAnimation != null) {
buttonsAnimation.cancel();
}
currentSheetAnimation = null;
currentSheetAnimationType = 0;
}
}
private SpringAnimation appearSpringAnimation;
private AnimatorSet buttonsAnimation;
@Override
protected boolean onCustomOpenAnimation() {
photoLayout.setTranslationX(0);
mediaPreviewView.setAlpha(0);
selectedView.setAlpha(1);
int fromTranslationY = super.containerView.getMeasuredHeight();
super.containerView.setTranslationY(fromTranslationY);
buttonsAnimation = new AnimatorSet();
buttonsAnimation.playTogether(ObjectAnimator.ofFloat(this, ATTACH_ALERT_PROGRESS, 0.0f, 400.0f));
buttonsAnimation.setDuration(400);
buttonsAnimation.setStartDelay(20);
ATTACH_ALERT_PROGRESS.set(this, 0.0f);
buttonsAnimation.start();
if (navigationBarAnimation != null) {
navigationBarAnimation.cancel();
}
navigationBarAnimation = ValueAnimator.ofFloat(navigationBarAlpha, 1f);
navigationBarAnimation.addUpdateListener(a -> {
navigationBarAlpha = (float) a.getAnimatedValue();
if (container != null) {
container.invalidate();
}
});
if (appearSpringAnimation != null) {
appearSpringAnimation.cancel();
}
appearSpringAnimation = new SpringAnimation(super.containerView, DynamicAnimation.TRANSLATION_Y, 0);
appearSpringAnimation.getSpring().setDampingRatio(0.75f);
appearSpringAnimation.getSpring().setStiffness(350.0f);
appearSpringAnimation.start();
if (Build.VERSION.SDK_INT >= 20 && useHardwareLayer) {
container.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
currentSheetAnimationType = 1;
currentSheetAnimation = new AnimatorSet();
currentSheetAnimation.playTogether(
ObjectAnimator.ofInt(backDrawable, AnimationProperties.COLOR_DRAWABLE_ALPHA, dimBehind ? dimBehindAlpha : 0)
);
currentSheetAnimation.setDuration(400);
currentSheetAnimation.setStartDelay(20);
currentSheetAnimation.setInterpolator(openInterpolator);
AnimationNotificationsLocker locker = new AnimationNotificationsLocker();
BottomSheetDelegateInterface delegate = super.delegate;
final Runnable onAnimationEnd = () -> {
currentSheetAnimation = null;
appearSpringAnimation = null;
locker.unlock();
currentSheetAnimationType = 0;
if (delegate != null) {
delegate.onOpenAnimationEnd();
}
if (useHardwareLayer) {
container.setLayerType(View.LAYER_TYPE_NONE, null);
}
if (isFullscreen) {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(params);
}
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 512);
};
appearSpringAnimation.addEndListener((animation, cancelled, value, velocity) -> {
if (currentSheetAnimation != null && !currentSheetAnimation.isRunning()) {
onAnimationEnd.run();
}
});
currentSheetAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
if (appearSpringAnimation != null && !appearSpringAnimation.isRunning()) {
onAnimationEnd.run();
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
currentSheetAnimation = null;
currentSheetAnimationType = 0;
}
}
});
locker.lock();
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopAllHeavyOperations, 512);
currentSheetAnimation.start();
// AndroidUtilities.runOnUIThread(() -> {
// if (currentSheetAnimation != null) {
// // closes keyboard so navigation bar buttons can be accessible
// ChatAttachAlert.this.delegate.needEnterComment();
// }
// }, 75);
ValueAnimator navigationBarAnimator = ValueAnimator.ofFloat(0, 1);
setNavBarAlpha(0);
navigationBarAnimator.addUpdateListener(a -> {
setNavBarAlpha((float) a.getAnimatedValue());
});
navigationBarAnimator.setStartDelay(25);
navigationBarAnimator.setDuration(200);
navigationBarAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
navigationBarAnimator.start();
return true;
}
private void setNavBarAlpha(float alpha) {
navBarColor = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_windowBackgroundGray), Math.min(255, Math.max(0, (int) (255 * alpha))));
AndroidUtilities.setNavigationBarColor(getWindow(), navBarColor, false);
AndroidUtilities.setLightNavigationBar(getWindow(), AndroidUtilities.computePerceivedBrightness(navBarColor) > 0.721);
getContainer().invalidate();
}
@Override
protected boolean onContainerTouchEvent(MotionEvent event) {
return currentAttachLayout.onContainerViewTouchEvent(event);
}
public void makeFocusable(EditTextBoldCursor editText, boolean showKeyboard) {
if (delegate == null) {
return;
}
if (!enterCommentEventSent) {
boolean keyboardVisible = delegate.needEnterComment();
enterCommentEventSent = true;
AndroidUtilities.runOnUIThread(() -> {
setFocusable(true);
editText.requestFocus();
if (showKeyboard) {
AndroidUtilities.runOnUIThread(() -> AndroidUtilities.showKeyboard(editText));
}
}, keyboardVisible ? 200 : 0);
}
}
private void applyAttachButtonColors(View view) {
if (view instanceof AttachButton) {
AttachButton button = (AttachButton) view;
button.textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(button.textKey), button.checkedState));
} else if (view instanceof AttachBotButton) {
AttachBotButton button = (AttachBotButton) view;
button.nameTextView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), button.textColor, button.checkedState));
}
}
@Override
public ArrayList<ThemeDescription> getThemeDescriptions() {
ArrayList<ThemeDescription> descriptions = new ArrayList<>();
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null) {
ArrayList<ThemeDescription> arrayList = layouts[a].getThemeDescriptions();
if (arrayList != null) {
descriptions.addAll(arrayList);
}
}
}
descriptions.add(new ThemeDescription(container, 0, null, null, null, null, Theme.key_dialogBackgroundGray));
return descriptions;
}
public void checkColors() {
if (buttonsRecyclerView == null) {
return;
}
int count = buttonsRecyclerView.getChildCount();
for (int a = 0; a < count; a++) {
applyAttachButtonColors(buttonsRecyclerView.getChildAt(a));
}
selectedTextView.setTextColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack));
mediaPreviewTextView.setTextColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack));
doneItem.getTextView().setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader));
selectedMenuItem.setIconColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack));
Theme.setDrawableColor(selectedMenuItem.getBackground(), forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector));
selectedMenuItem.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false);
selectedMenuItem.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), true);
selectedMenuItem.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground));
if (searchItem != null) {
searchItem.setIconColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack));
Theme.setDrawableColor(searchItem.getBackground(), forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector));
}
commentTextView.updateColors();
if (sendPopupLayout != null) {
for (int a = 0; a < itemCells.length; a++) {
if (itemCells[a] != null) {
itemCells[a].setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon));
itemCells[a].setSelectorColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector));
}
}
sendPopupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground));
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupLayout.invalidate();
}
}
Theme.setSelectorDrawableColor(writeButtonDrawable, getThemedColor(Theme.key_dialogFloatingButton), false);
Theme.setSelectorDrawableColor(writeButtonDrawable, getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton), true);
writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
actionBarShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine));
buttonsRecyclerView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow));
buttonsRecyclerView.setBackgroundColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground));
frameLayout2.setBackgroundColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground));
selectedCountView.invalidate();
actionBar.setBackgroundColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBar) : getThemedColor(Theme.key_dialogBackground));
actionBar.setItemsColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack), false);
actionBar.setItemsBackgroundColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector), false);
actionBar.setTitleColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack));
Theme.setDrawableColor(shadowDrawable, getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground));
containerView.invalidate();
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null) {
layouts[a].checkColors();
}
}
if (Build.VERSION.SDK_INT >= 30) {
navBarColorKey = -1;
navBarColor = getThemedColor(Theme.key_dialogBackgroundGray);
AndroidUtilities.setNavigationBarColor(getWindow(), getThemedColor(Theme.key_dialogBackground), false);
AndroidUtilities.setLightNavigationBar(getWindow(), AndroidUtilities.computePerceivedBrightness(navBarColor) > 0.721);
} else {
fixNavigationBar(getThemedColor(Theme.key_dialogBackground));
}
}
@Override
protected boolean onCustomMeasure(View view, int width, int height) {
if (photoLayout.onCustomMeasure(view, width, height)) {
return true;
}
return false;
}
@Override
protected boolean onCustomLayout(View view, int left, int top, int right, int bottom) {
if (photoLayout.onCustomLayout(view, left, top, right, bottom)) {
return true;
}
return false;
}
public void onPause() {
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null) {
layouts[a].onPause();
}
}
paused = true;
}
public void onResume() {
paused = false;
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null) {
layouts[a].onResume();
}
}
if (isShowing()) {
delegate.needEnterComment();
}
}
public void onActivityResultFragment(int requestCode, Intent data, String currentPicturePath) {
photoLayout.onActivityResultFragment(requestCode, data, currentPicturePath);
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.reloadInlineHints || id == NotificationCenter.attachMenuBotsDidLoad || id == NotificationCenter.quickRepliesUpdated) {
if (buttonsAdapter != null) {
buttonsAdapter.notifyDataSetChanged();
}
} else if (id == NotificationCenter.currentUserPremiumStatusChanged) {
currentLimit = MessagesController.getInstance(UserConfig.selectedAccount).getCaptionMaxLengthLimit();
}
}
private int getScrollOffsetY(int idx) {
if (nextAttachLayout != null && (currentAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview || nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview)) {
return AndroidUtilities.lerp(scrollOffsetY[0], scrollOffsetY[1], translationProgress);
} else {
return scrollOffsetY[idx];
}
}
private void updateSelectedPosition(int idx) {
float moveProgress;
AttachAlertLayout layout = idx == 0 ? currentAttachLayout : nextAttachLayout;
if (layout == null || layout.getVisibility() != View.VISIBLE) {
return;
}
int scrollOffset = getScrollOffsetY(idx);
int t = scrollOffset - backgroundPaddingTop;
float toMove;
if (layout == pollLayout) {
t -= AndroidUtilities.dp(13);
toMove = AndroidUtilities.dp(11);
} else {
t -= AndroidUtilities.dp(39);
toMove = AndroidUtilities.dp(43);
}
if (t + backgroundPaddingTop < ActionBar.getCurrentActionBarHeight()) {
moveProgress = Math.min(1.0f, (ActionBar.getCurrentActionBarHeight() - t - backgroundPaddingTop) / toMove);
cornerRadius = 1.0f - moveProgress;
} else {
moveProgress = 0.0f;
cornerRadius = 1.0f;
}
int finalMove;
if (AndroidUtilities.isTablet()) {
finalMove = 16;
} else if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) {
finalMove = 6;
} else {
finalMove = 12;
}
float offset = actionBar.getAlpha() != 0 ? 0.0f : AndroidUtilities.dp(26 * (1.0f - headerView.getAlpha()));
if (menuShowed && avatarPicker == 0) {
selectedMenuItem.setTranslationY(scrollOffset - AndroidUtilities.dp(37 + finalMove * moveProgress) + offset + currentPanTranslationY);
} else {
selectedMenuItem.setTranslationY(ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(4) - AndroidUtilities.dp(37 + finalMove) + currentPanTranslationY);
}
float swapOffset = 0;
if (isPhotoPicker && openTransitionFinished) {
if (nextAttachLayout != null && currentAttachLayout != null) {
swapOffset = Math.min(nextAttachLayout.getTranslationY(), currentAttachLayout.getTranslationY());
} else if (nextAttachLayout != null) {
swapOffset = nextAttachLayout.getTranslationY();
}
}
if (searchItem != null) {
searchItem.setTranslationY(ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(4) - AndroidUtilities.dp(37 + finalMove) + currentPanTranslationY);
}
headerView.setTranslationY(baseSelectedTextViewTranslationY = scrollOffset - AndroidUtilities.dp(25 + finalMove * moveProgress) + offset + currentPanTranslationY + swapOffset);
if (pollLayout != null && layout == pollLayout) {
if (AndroidUtilities.isTablet()) {
finalMove = 63;
} else if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) {
finalMove = 53;
} else {
finalMove = 59;
}
doneItem.setTranslationY(Math.max(0, pollLayout.getTranslationY() + scrollOffset - AndroidUtilities.dp(7 + finalMove * moveProgress)) + currentPanTranslationY);
}
}
private void updateActionBarVisibility(boolean show, boolean animated) {
if (show && actionBar.getTag() == null || !show && actionBar.getTag() != null) {
actionBar.setTag(show ? 1 : null);
if (actionBarAnimation != null) {
actionBarAnimation.cancel();
actionBarAnimation = null;
}
boolean needsSearchItem = searchItem != null && (avatarSearch || false && currentAttachLayout == photoLayout && !menuShowed && baseFragment instanceof ChatActivity && ((ChatActivity) baseFragment).allowSendGifs() && ((ChatActivity) baseFragment).allowSendPhotos());
boolean needMoreItem = !isPhotoPicker && (avatarPicker != 0 || !menuShowed) && currentAttachLayout == photoLayout && (photosEnabled || videosEnabled);
if (currentAttachLayout == restrictedLayout) {
needsSearchItem = false;
needMoreItem = false;
}
if (show) {
if (needsSearchItem) {
searchItem.setVisibility(View.VISIBLE);
}
if (needMoreItem) {
selectedMenuItem.setVisibility(View.VISIBLE);
}
} else if (typeButtonsAvailable && frameLayout2.getTag() == null) {
buttonsRecyclerView.setVisibility(View.VISIBLE);
}
if (getWindow() != null && baseFragment != null) {
if (show) {
AndroidUtilities.setLightStatusBar(getWindow(), isLightStatusBar());
} else {
AndroidUtilities.setLightStatusBar(getWindow(), baseFragment.isLightStatusBar());
}
}
if (animated) {
actionBarAnimation = new AnimatorSet();
actionBarAnimation.setDuration((long) (180 * Math.abs((show ? 1.0f : 0.0f) - actionBar.getAlpha())));
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(actionBar, View.ALPHA, show ? 1.0f : 0.0f));
animators.add(ObjectAnimator.ofFloat(actionBarShadow, View.ALPHA, show ? 1.0f : 0.0f));
if (needsSearchItem) {
animators.add(ObjectAnimator.ofFloat(searchItem, View.ALPHA, show ? 1.0f : 0.0f));
}
if (needMoreItem) {
animators.add(ObjectAnimator.ofFloat(selectedMenuItem, View.ALPHA, show ? 1.0f : 0.0f));
}
actionBarAnimation.playTogether(animators);
actionBarAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (actionBarAnimation != null) {
if (show) {
if (typeButtonsAvailable && (currentAttachLayout == null || currentAttachLayout.shouldHideBottomButtons())) {
buttonsRecyclerView.setVisibility(View.INVISIBLE);
}
} else {
if (searchItem != null) {
searchItem.setVisibility(View.INVISIBLE);
}
if (avatarPicker != 0 || !menuShowed) {
selectedMenuItem.setVisibility(View.INVISIBLE);
}
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
actionBarAnimation = null;
}
});
actionBarAnimation.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
actionBarAnimation.setDuration(380);
actionBarAnimation.start();
} else {
if (show) {
if (typeButtonsAvailable && (currentAttachLayout == null || currentAttachLayout.shouldHideBottomButtons())) {
buttonsRecyclerView.setVisibility(View.INVISIBLE);
}
}
actionBar.setAlpha(show ? 1.0f : 0.0f);
actionBarShadow.setAlpha(show ? 1.0f : 0.0f);
if (needsSearchItem) {
searchItem.setAlpha(show ? 1.0f : 0.0f);
}
if (needMoreItem) {
selectedMenuItem.setAlpha(show ? 1.0f : 0.0f);
}
if (!show) {
if (searchItem != null) {
searchItem.setVisibility(View.INVISIBLE);
}
if (avatarPicker != 0 || !menuShowed) {
selectedMenuItem.setVisibility(View.INVISIBLE);
}
}
}
}
}
@SuppressLint("NewApi")
public void updateLayout(AttachAlertLayout layout, boolean animated, int dy) {
if (layout == null) {
return;
}
int newOffset = layout.getCurrentItemTop();
if (newOffset == Integer.MAX_VALUE) {
return;
}
boolean show = layout == currentAttachLayout && newOffset <= layout.getButtonsHideOffset();
pinnedToTop = show;
if (currentAttachLayout != photoPreviewLayout && keyboardVisible && animated && !(currentAttachLayout instanceof ChatAttachAlertBotWebViewLayout)) {
animated = false;
}
if (layout == currentAttachLayout) {
updateActionBarVisibility(show, true);
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) layout.getLayoutParams();
newOffset += (layoutParams == null ? 0 : layoutParams.topMargin) - AndroidUtilities.dp(11);
int idx = currentAttachLayout == layout ? 0 : 1;
boolean previewAnimationIsRunning = (currentAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview || nextAttachLayout instanceof ChatAttachAlertPhotoLayoutPreview) && (viewChangeAnimator instanceof SpringAnimation && ((SpringAnimation) viewChangeAnimator).isRunning());
if (scrollOffsetY[idx] != newOffset || previewAnimationIsRunning) {
previousScrollOffsetY = scrollOffsetY[idx];
scrollOffsetY[idx] = newOffset;
updateSelectedPosition(idx);
containerView.invalidate();
} else if (dy != 0) {
previousScrollOffsetY = scrollOffsetY[idx];
}
}
@Override
protected boolean canDismissWithSwipe() {
return false;
}
public void updateCountButton(int animated) {
if (viewChangeAnimator != null) {
return;
}
int count = currentAttachLayout.getSelectedItemsCount();
if (count == 0) {
selectedCountView.setPivotX(0);
selectedCountView.setPivotY(0);
showCommentTextView(false, animated != 0);
} else {
selectedCountView.invalidate();
if (!showCommentTextView(true, animated != 0) && animated != 0) {
selectedCountView.setPivotX(AndroidUtilities.dp(21));
selectedCountView.setPivotY(AndroidUtilities.dp(12));
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(selectedCountView, View.SCALE_X, animated == 1 ? 1.1f : 0.9f, 1.0f),
ObjectAnimator.ofFloat(selectedCountView, View.SCALE_Y, animated == 1 ? 1.1f : 0.9f, 1.0f));
animatorSet.setInterpolator(new OvershootInterpolator());
animatorSet.setDuration(180);
animatorSet.start();
} else {
selectedCountView.setPivotX(0);
selectedCountView.setPivotY(0);
}
}
currentAttachLayout.onSelectedItemsCountChanged(count);
if (currentAttachLayout == photoLayout && ((baseFragment instanceof ChatActivity) || avatarPicker != 0) && (count == 0 && menuShowed || (count != 0 || avatarPicker != 0) && !menuShowed)) {
menuShowed = count != 0 || avatarPicker != 0;
if (menuAnimator != null) {
menuAnimator.cancel();
menuAnimator = null;
}
boolean needsSearchItem = avatarPicker != 0 && searchItem != null && actionBar.getTag() != null && baseFragment instanceof ChatActivity && ((ChatActivity) baseFragment).allowSendGifs();
if (menuShowed) {
if (avatarPicker == 0) {
selectedMenuItem.setVisibility(View.VISIBLE);
}
headerView.setVisibility(View.VISIBLE);
} else {
if (actionBar.getTag() != null && searchItem != null) {
searchItem.setVisibility(View.VISIBLE);
}
}
if (animated == 0) {
if (actionBar.getTag() == null && avatarPicker == 0) {
selectedMenuItem.setAlpha(menuShowed ? 1.0f : 0.0f);
}
headerView.setAlpha(menuShowed ? 1.0f : 0.0f);
if (needsSearchItem) {
searchItem.setAlpha(menuShowed ? 0.0f : 1.0f);
}
if (menuShowed && searchItem != null) {
searchItem.setVisibility(View.INVISIBLE);
}
} else {
menuAnimator = new AnimatorSet();
ArrayList<Animator> animators = new ArrayList<>();
if (actionBar.getTag() == null && avatarPicker == 0) {
animators.add(ObjectAnimator.ofFloat(selectedMenuItem, View.ALPHA, menuShowed ? 1.0f : 0.0f));
}
animators.add(ObjectAnimator.ofFloat(headerView, View.ALPHA, menuShowed ? 1.0f : 0.0f));
if (needsSearchItem) {
animators.add(ObjectAnimator.ofFloat(searchItem, View.ALPHA, menuShowed ? 0.0f : 1.0f));
}
menuAnimator.playTogether(animators);
menuAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
menuAnimator = null;
if (!menuShowed) {
if (actionBar.getTag() == null && avatarPicker == 0) {
selectedMenuItem.setVisibility(View.INVISIBLE);
}
headerView.setVisibility(View.INVISIBLE);
} else if (searchItem != null) {
searchItem.setVisibility(View.INVISIBLE);
}
}
});
menuAnimator.setDuration(180);
menuAnimator.start();
}
}
}
public void setDelegate(ChatAttachViewDelegate chatAttachViewDelegate) {
delegate = chatAttachViewDelegate;
}
public void init() {
botButtonWasVisible = false;
botButtonProgressWasVisible = false;
botMainButtonOffsetY = 0;
botMainButtonTextView.setVisibility(View.GONE);
botProgressView.setAlpha(0f);
botProgressView.setScaleX(0.1f);
botProgressView.setScaleY(0.1f);
botProgressView.setVisibility(View.GONE);
buttonsRecyclerView.setAlpha(1f);
buttonsRecyclerView.setTranslationY(0);
for (int i = 0; i < botAttachLayouts.size(); i++) {
botAttachLayouts.valueAt(i).setMeasureOffsetY(0);
}
shadow.setAlpha(1f);
shadow.setTranslationY(0);
TLRPC.Chat chat = null;
TLRPC.User user = null;
if (avatarPicker != 2) {
if (baseFragment instanceof ChatActivity) {
chat = ((ChatActivity) baseFragment).getCurrentChat();
user = ((ChatActivity) baseFragment).getCurrentUser();
} else if (dialogId >= 0) {
user = MessagesController.getInstance(currentAccount).getUser(dialogId);
} else if (dialogId < 0) {
chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
}
}
if (baseFragment instanceof ChatActivity && avatarPicker != 2 || (chat != null || user != null)) {
if (chat != null) {
// mediaEnabled = ChatObject.canSendMedia(chat);
photosEnabled = ChatObject.canSendPhoto(chat);
videosEnabled = ChatObject.canSendVideo(chat);
musicEnabled = ChatObject.canSendMusic(chat);
pollsEnabled = ChatObject.canSendPolls(chat);
plainTextEnabled = ChatObject.canSendPlain(chat);
documentsEnabled = ChatObject.canSendDocument(chat);
} else {
pollsEnabled = user != null && user.bot;
}
}
if (!(baseFragment instanceof ChatActivity && avatarPicker != 2)) {
commentTextView.setVisibility(allowEnterCaption ? View.VISIBLE : View.INVISIBLE);
}
photoLayout.onInit(videosEnabled, photosEnabled, documentsEnabled);
commentTextView.hidePopup(true);
enterCommentEventSent = false;
setFocusable(false);
ChatAttachAlert.AttachAlertLayout layoutToSet;
if (isStoryLocationPicker || isBizLocationPicker) {
if (locationLayout == null) {
layouts[5] = locationLayout = new ChatAttachAlertLocationLayout(this, getContext(), resourcesProvider);
locationLayout.setDelegate((location, live, notify, scheduleDate) -> ((ChatActivity) baseFragment).didSelectLocation(location, live, notify, scheduleDate));
}
selectedId = 5;
layoutToSet = locationLayout;
} else if (isStoryAudioPicker) {
openAudioLayout(false);
layoutToSet = audioLayout;
selectedId = 3;
} else if (isSoundPicker) {
openDocumentsLayout(false);
layoutToSet = documentLayout;
selectedId = 4;
} else if (editingMessageObject != null && (editingMessageObject.isMusic() || (editingMessageObject.isDocument() && !editingMessageObject.isGif()))) {
if (editingMessageObject.isMusic()) {
openAudioLayout(false);
layoutToSet = audioLayout;
selectedId = 3;
} else {
openDocumentsLayout(false);
layoutToSet = documentLayout;
selectedId = 4;
}
typeButtonsAvailable = !editingMessageObject.hasValidGroupId();
} else {
layoutToSet = photoLayout;
typeButtonsAvailable = avatarPicker == 0;
selectedId = 1;
}
buttonsRecyclerView.setVisibility(typeButtonsAvailable ? View.VISIBLE : View.GONE);
shadow.setVisibility(typeButtonsAvailable ? View.VISIBLE : View.INVISIBLE);
if (currentAttachLayout != layoutToSet) {
if (actionBar.isSearchFieldVisible()) {
actionBar.closeSearchField();
}
containerView.removeView(currentAttachLayout);
currentAttachLayout.onHide();
currentAttachLayout.setVisibility(View.GONE);
currentAttachLayout.onHidden();
AttachAlertLayout previousLayout = currentAttachLayout;
currentAttachLayout = layoutToSet;
setAllowNestedScroll(true);
if (currentAttachLayout.getParent() == null) {
containerView.addView(currentAttachLayout, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
}
layoutToSet.setAlpha(1.0f);
layoutToSet.setVisibility(View.VISIBLE);
layoutToSet.onShow(null);
layoutToSet.onShown();
actionBar.setVisibility(layoutToSet.needsActionBar() != 0 ? View.VISIBLE : View.INVISIBLE);
actionBarShadow.setVisibility(actionBar.getVisibility());
}
if (currentAttachLayout != photoLayout) {
photoLayout.setCheckCameraWhenShown(true);
}
updateCountButton(0);
buttonsAdapter.notifyDataSetChanged();
commentTextView.setText("");
buttonsLayoutManager.scrollToPositionWithOffset(0, 1000000);
}
public void onDestroy() {
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null) {
layouts[a].onDestroy();
}
}
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.reloadInlineHints);
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.attachMenuBotsDidLoad);
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.currentUserPremiumStatusChanged);
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.quickRepliesUpdated);
destroyed = true;
if (commentTextView != null) {
commentTextView.onDestroy();
}
}
@Override
public void onOpenAnimationEnd() {
MediaController.AlbumEntry albumEntry;
if (baseFragment instanceof ChatActivity) {
albumEntry = MediaController.allMediaAlbumEntry;
} else {
albumEntry = MediaController.allPhotosAlbumEntry;
}
if (Build.VERSION.SDK_INT <= 19 && albumEntry == null) {
MediaController.loadGalleryPhotosAlbums(0);
}
currentAttachLayout.onOpenAnimationEnd();
AndroidUtilities.makeAccessibilityAnnouncement(LocaleController.getString("AccDescrAttachButton", R.string.AccDescrAttachButton));
openTransitionFinished = true;
if (!videosEnabled && !photosEnabled) {
checkCanRemoveRestrictionsByBoosts();
}
}
@Override
public void onOpenAnimationStart() {
sent = false;
}
@Override
public boolean canDismiss() {
return true;
}
private boolean allowDrawContent = true;
public boolean sent = false;
@Override
public void setAllowDrawContent(boolean value) {
super.setAllowDrawContent(value);
currentAttachLayout.onContainerTranslationUpdated(currentPanTranslationY);
if (allowDrawContent != value) {
allowDrawContent = value;
if (currentAttachLayout == photoLayout && photoLayout != null && !photoLayout.cameraExpanded) {
photoLayout.pauseCamera(!allowDrawContent || sent);
}
}
}
public void setStories(boolean value) {
stories = value;
}
public void setAvatarPicker(int type, boolean search) {
avatarPicker = type;
avatarSearch = search;
if (avatarPicker != 0) {
typeButtonsAvailable = false;
if (currentAttachLayout == null || currentAttachLayout == photoLayout) {
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
}
if (avatarPicker == 2) {
selectedTextView.setText(LocaleController.getString("ChoosePhotoOrVideo", R.string.ChoosePhotoOrVideo));
} else {
selectedTextView.setText(LocaleController.getString("ChoosePhoto", R.string.ChoosePhoto));
}
} else {
typeButtonsAvailable = true;
}
if (photoLayout != null) {
photoLayout.updateAvatarPicker();
}
}
public void enableStickerMode(Utilities.Callback2<String, TLRPC.InputDocument> customStickerHandler) {
selectedTextView.setText(LocaleController.getString("ChoosePhoto", R.string.ChoosePhoto));
typeButtonsAvailable = false;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
avatarPicker = 1;
isPhotoPicker = true;
isStickerMode = true;
this.customStickerHandler = customStickerHandler;
if (optionsItem != null) {
selectedTextView.setTranslationY(-AndroidUtilities.dp(8));
optionsItem.setVisibility(View.VISIBLE);
}
}
public void enableDefaultMode() {
typeButtonsAvailable = true;
buttonsRecyclerView.setVisibility(View.VISIBLE);
shadow.setVisibility(View.VISIBLE);
avatarPicker = 0;
isPhotoPicker = false;
isStickerMode = false;
customStickerHandler = null;
if (optionsItem != null) {
selectedTextView.setTranslationY(0);
optionsItem.setVisibility(View.GONE);
}
}
public TextView getSelectedTextView() {
return selectedTextView;
}
public void setSoundPicker() {
isSoundPicker = true;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
selectedTextView.setText(LocaleController.getString("ChoosePhotoOrVideo", R.string.ChoosePhotoOrVideo));
}
public boolean storyLocationPickerFileIsVideo;
public File storyLocationPickerPhotoFile;
public double[] storyLocationPickerLatLong;
public void setBusinessLocationPicker() {
isBizLocationPicker = true;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
}
public void setStoryLocationPicker() {
isStoryLocationPicker = true;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
}
public void setStoryLocationPicker(boolean isVideo, File photo) {
storyLocationPickerFileIsVideo = isVideo;
storyLocationPickerPhotoFile = photo;
isStoryLocationPicker = true;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
}
public void setStoryLocationPicker(double lat, double lon) {
storyLocationPickerLatLong = new double[]{lat, lon};
isStoryLocationPicker = true;
buttonsRecyclerView.setVisibility(View.GONE);
shadow.setVisibility(View.GONE);
}
public void setStoryAudioPicker() {
isStoryAudioPicker = true;
}
public void setMaxSelectedPhotos(int value, boolean order) {
if (editingMessageObject != null) {
return;
}
maxSelectedPhotos = value;
allowOrder = order;
}
public void setOpenWithFrontFaceCamera(boolean value) {
openWithFrontFaceCamera = value;
}
public ChatAttachAlertPhotoLayout getPhotoLayout() {
return photoLayout;
}
public ChatAttachAlertLocationLayout getLocationLayout() {
return locationLayout;
}
private class ButtonsAdapter extends RecyclerListView.SelectionAdapter {
private final static int VIEW_TYPE_BUTTON = 0, VIEW_TYPE_BOT_BUTTON = 1;
private Context mContext;
private int galleryButton;
private int attachBotsStartRow;
private int attachBotsEndRow;
private List<TLRPC.TL_attachMenuBot> attachMenuBots = new ArrayList<>();
private int documentButton;
private int musicButton;
private int pollButton;
private int contactButton;
private int quickRepliesButton;
private int locationButton;
private int buttonsCount;
public ButtonsAdapter(Context context) {
mContext = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case VIEW_TYPE_BUTTON:
view = new AttachButton(mContext);
break;
case VIEW_TYPE_BOT_BUTTON:
default:
view = new AttachBotButton(mContext);
break;
}
view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
view.setFocusable(true);
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case VIEW_TYPE_BUTTON:
AttachButton attachButton = (AttachButton) holder.itemView;
if (position == galleryButton) {
attachButton.setTextAndIcon(1, LocaleController.getString("ChatGallery", R.string.ChatGallery), Theme.chat_attachButtonDrawables[0], Theme.key_chat_attachGalleryBackground, Theme.key_chat_attachGalleryText);
attachButton.setTag(1);
} else if (position == documentButton) {
attachButton.setTextAndIcon(4, LocaleController.getString("ChatDocument", R.string.ChatDocument), Theme.chat_attachButtonDrawables[2], Theme.key_chat_attachFileBackground, Theme.key_chat_attachFileText);
attachButton.setTag(4);
} else if (position == locationButton) {
attachButton.setTextAndIcon(6, LocaleController.getString("ChatLocation", R.string.ChatLocation), Theme.chat_attachButtonDrawables[4], Theme.key_chat_attachLocationBackground, Theme.key_chat_attachLocationText);
attachButton.setTag(6);
} else if (position == musicButton) {
attachButton.setTextAndIcon(3, LocaleController.getString("AttachMusic", R.string.AttachMusic), Theme.chat_attachButtonDrawables[1], Theme.key_chat_attachAudioBackground, Theme.key_chat_attachAudioText);
attachButton.setTag(3);
} else if (position == pollButton) {
attachButton.setTextAndIcon(9, LocaleController.getString("Poll", R.string.Poll), Theme.chat_attachButtonDrawables[5], Theme.key_chat_attachPollBackground, Theme.key_chat_attachPollText);
attachButton.setTag(9);
} else if (position == contactButton) {
attachButton.setTextAndIcon(5, LocaleController.getString("AttachContact", R.string.AttachContact), Theme.chat_attachButtonDrawables[3], Theme.key_chat_attachContactBackground, Theme.key_chat_attachContactText);
attachButton.setTag(5);
} else if (position == quickRepliesButton) {
attachButton.setTextAndIcon(11, LocaleController.getString(R.string.AttachQuickReplies), getContext().getResources().getDrawable(R.drawable.ic_ab_reply).mutate(), Theme.key_chat_attachContactBackground, Theme.key_chat_attachContactText);
attachButton.setTag(11);
}
break;
case VIEW_TYPE_BOT_BUTTON:
AttachBotButton child = (AttachBotButton) holder.itemView;
if (position >= attachBotsStartRow && position < attachBotsEndRow) {
position -= attachBotsStartRow;
child.setTag(position);
TLRPC.TL_attachMenuBot bot = attachMenuBots.get(position);
child.setAttachBot(MessagesController.getInstance(currentAccount).getUser(bot.bot_id), bot);
break;
}
position -= buttonsCount;
child.setTag(position);
child.setUser(MessagesController.getInstance(currentAccount).getUser(MediaDataController.getInstance(currentAccount).inlineBots.get(position).peer.user_id));
break;
}
}
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
applyAttachButtonColors(holder.itemView);
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return false;
}
@Override
public int getItemCount() {
int count = buttonsCount;
if (editingMessageObject == null && baseFragment instanceof ChatActivity) {
count += MediaDataController.getInstance(currentAccount).inlineBots.size();
}
return count;
}
@Override
public void notifyDataSetChanged() {
buttonsCount = 0;
galleryButton = -1;
documentButton = -1;
musicButton = -1;
pollButton = -1;
contactButton = -1;
quickRepliesButton = -1;
locationButton = -1;
attachBotsStartRow = -1;
attachBotsEndRow = -1;
if (!(baseFragment instanceof ChatActivity)) {
galleryButton = buttonsCount++;
documentButton = buttonsCount++;
if (allowEnterCaption) {
musicButton = buttonsCount++;
}
} else if (editingMessageObject != null) {
if ((editingMessageObject.isMusic() || editingMessageObject.isDocument()) && editingMessageObject.hasValidGroupId()) {
if (editingMessageObject.isMusic()) {
musicButton = buttonsCount++;
} else {
documentButton = buttonsCount++;
}
} else {
galleryButton = buttonsCount++;
documentButton = buttonsCount++;
musicButton = buttonsCount++;
}
} else {
galleryButton = buttonsCount++;
if (photosEnabled || videosEnabled) {
if (baseFragment instanceof ChatActivity && !((ChatActivity) baseFragment).isInScheduleMode() && !((ChatActivity) baseFragment).isSecretChat() && ((ChatActivity) baseFragment).getChatMode() != ChatActivity.MODE_QUICK_REPLIES) {
ChatActivity chatActivity = (ChatActivity) baseFragment;
attachBotsStartRow = buttonsCount;
attachMenuBots.clear();
for (TLRPC.TL_attachMenuBot bot : MediaDataController.getInstance(currentAccount).getAttachMenuBots().bots) {
if (bot.show_in_attach_menu && MediaDataController.canShowAttachMenuBot(bot, chatActivity.getCurrentChat() != null ? chatActivity.getCurrentChat() : chatActivity.getCurrentUser())) {
attachMenuBots.add(bot);
}
}
buttonsCount += attachMenuBots.size();
attachBotsEndRow = buttonsCount;
}
}
documentButton = buttonsCount++;
if (plainTextEnabled) {
locationButton = buttonsCount++;
}
if (pollsEnabled) {
pollButton = buttonsCount++;
} else if (plainTextEnabled) {
contactButton = buttonsCount++;
}
TLRPC.User user = baseFragment instanceof ChatActivity ? ((ChatActivity) baseFragment).getCurrentUser() : null;
if (baseFragment instanceof ChatActivity && ((ChatActivity) baseFragment).getChatMode() == 0 && user != null && !user.bot && QuickRepliesController.getInstance(currentAccount).hasReplies()) {
quickRepliesButton = buttonsCount++;
}
musicButton = buttonsCount++;
if (user != null && user.bot) {
contactButton = buttonsCount++;
}
}
super.notifyDataSetChanged();
}
public int getButtonsCount() {
return buttonsCount;
}
@Override
public int getItemViewType(int position) {
if (position < buttonsCount) {
if (position >= attachBotsStartRow && position < attachBotsEndRow) {
return VIEW_TYPE_BOT_BUTTON;
}
return VIEW_TYPE_BUTTON;
}
return VIEW_TYPE_BOT_BUTTON;
}
}
@Override
public void dismissInternal() {
if (delegate != null) {
delegate.doOnIdle(this::removeFromRoot);
} else {
removeFromRoot();
}
}
private void removeFromRoot() {
if (containerView != null) {
containerView.setVisibility(View.INVISIBLE);
}
if (actionBar.isSearchFieldVisible()) {
actionBar.closeSearchField();
}
contactsLayout = null;
quickRepliesLayout = null;
audioLayout = null;
pollLayout = null;
locationLayout = null;
documentLayout = null;
for (int a = 1; a < layouts.length; a++) {
if (layouts[a] == null) {
continue;
}
layouts[a].onDestroy();
containerView.removeView(layouts[a]);
layouts[a] = null;
}
updateActionBarVisibility(false, false);
super.dismissInternal();
}
@Override
public void onBackPressed() {
if (passcodeView.getVisibility() == View.VISIBLE) {
if (getOwnerActivity() != null) {
getOwnerActivity().finish();
}
return;
}
if (actionBar.isSearchFieldVisible()) {
actionBar.closeSearchField();
return;
}
if (currentAttachLayout.onBackPressed()) {
return;
}
if (commentTextView != null && commentTextView.isPopupShowing()) {
commentTextView.hidePopup(true);
return;
}
super.onBackPressed();
}
@Override
public void dismissWithButtonClick(int item) {
super.dismissWithButtonClick(item);
currentAttachLayout.onDismissWithButtonClick(item);
}
@Override
protected boolean canDismissWithTouchOutside() {
return currentAttachLayout.canDismissWithTouchOutside();
}
@Override
protected void onDismissWithTouchOutside() {
if (currentAttachLayout.onDismissWithTouchOutside()) {
dismiss();
}
}
private boolean confirmationAlertShown = false;
protected boolean allowPassConfirmationAlert = false;
public void dismiss(boolean passConfirmationAlert) {
if (passConfirmationAlert) {
this.allowPassConfirmationAlert = passConfirmationAlert;
}
this.dismiss();
}
@Override
public void dismiss() {
if (currentAttachLayout.onDismiss() || isDismissed()) {
return;
}
if (commentTextView != null) {
AndroidUtilities.hideKeyboard(commentTextView.getEditText());
}
botAttachLayouts.clear();
BaseFragment baseFragment = this.baseFragment;
if (baseFragment == null) {
baseFragment = LaunchActivity.getLastFragment();
}
if (!allowPassConfirmationAlert && baseFragment != null && currentAttachLayout.getSelectedItemsCount() > 0 && !isPhotoPicker) {
if (confirmationAlertShown) {
return;
}
confirmationAlertShown = true;
AlertDialog dialog =
new AlertDialog.Builder(baseFragment.getParentActivity(), resourcesProvider)
.setTitle(LocaleController.getString("DiscardSelectionAlertTitle", R.string.DiscardSelectionAlertTitle))
.setMessage(LocaleController.getString("DiscardSelectionAlertMessage", R.string.DiscardSelectionAlertMessage))
.setPositiveButton(LocaleController.getString("PassportDiscard", R.string.PassportDiscard), (dialogInterface, i) -> {
allowPassConfirmationAlert = true;
dismiss();
})
.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null)
.setOnCancelListener(di -> {
if (appearSpringAnimation != null) {
appearSpringAnimation.cancel();
}
appearSpringAnimation = new SpringAnimation(super.containerView, DynamicAnimation.TRANSLATION_Y, 0);
appearSpringAnimation.getSpring().setDampingRatio(1.5f);
appearSpringAnimation.getSpring().setStiffness(1500.0f);
appearSpringAnimation.start();
})
.setOnPreDismissListener(di -> {
confirmationAlertShown = false;
})
.create();
dialog.show();
TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (button != null) {
button.setTextColor(getThemedColor(Theme.key_text_RedBold));
}
return;
}
for (int a = 0; a < layouts.length; a++) {
if (layouts[a] != null && currentAttachLayout != layouts[a]) {
layouts[a].onDismiss();
}
}
AndroidUtilities.setNavigationBarColor(getWindow(), ColorUtils.setAlphaComponent(getThemedColor(Theme.key_windowBackgroundGray), 0), true, tcolor -> {
navBarColorKey = -1;
navBarColor = tcolor;
containerView.invalidate();
});
if (baseFragment != null) {
AndroidUtilities.setLightStatusBar(getWindow(), baseFragment.isLightStatusBar());
}
captionLimitBulletinShown = false;
super.dismiss();
allowPassConfirmationAlert = false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (currentAttachLayout.onSheetKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setAllowNestedScroll(boolean allowNestedScroll) {
this.allowNestedScroll = allowNestedScroll;
}
public BaseFragment getBaseFragment() {
return baseFragment;
}
public EditTextEmoji getCommentTextView() {
return commentTextView;
}
public ChatAttachAlertDocumentLayout getDocumentLayout() {
return documentLayout;
}
public void setAllowEnterCaption(boolean allowEnterCaption) {
this.allowEnterCaption = allowEnterCaption;
}
public void setDocumentsDelegate(ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate documentsDelegate) {
this.documentsDelegate = documentsDelegate;
}
private void replaceWithText(int start, int len, CharSequence text, boolean parseEmoji) {
if (commentTextView == null) {
return;
}
try {
SpannableStringBuilder builder = new SpannableStringBuilder(commentTextView.getText());
builder.replace(start, start + len, text);
if (parseEmoji) {
Emoji.replaceEmoji(builder, commentTextView.getEditText().getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false);
}
commentTextView.setText(builder);
commentTextView.setSelection(start + text.length());
} catch (Exception e) {
FileLog.e(e);
}
}
public MentionsContainerView mentionContainer;
private void createMentionsContainer() {
mentionContainer = new MentionsContainerView(getContext(), UserConfig.getInstance(currentAccount).getClientUserId(), 0, LaunchActivity.getLastFragment(), null, resourcesProvider) {
@Override
protected void onScrolled(boolean atTop, boolean atBottom) {
if (photoLayout != null) {
photoLayout.checkCameraViewPosition();
}
}
@Override
protected void onAnimationScroll() {
if (photoLayout != null) {
photoLayout.checkCameraViewPosition();
}
}
};
setupMentionContainer();
mentionContainer.withDelegate(new MentionsContainerView.Delegate() {
@Override
public void replaceText(int start, int len, CharSequence replacingString, boolean allowShort) {
replaceWithText(start, len, replacingString, allowShort);
}
@Override
public Paint.FontMetricsInt getFontMetrics() {
return commentTextView.getEditText().getPaint().getFontMetricsInt();
}
});
containerView.addView(mentionContainer, containerView.indexOfChild(frameLayout2), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.BOTTOM));
mentionContainer.setTranslationY(-commentTextView.getHeight());
setupMentionContainer();
}
protected void setupMentionContainer() {
mentionContainer.getAdapter().setAllowStickers(false);
mentionContainer.getAdapter().setAllowBots(false);
mentionContainer.getAdapter().setAllowChats(false);
mentionContainer.getAdapter().setSearchInDailogs(true);
if (baseFragment instanceof ChatActivity) {
mentionContainer.getAdapter().setChatInfo(((ChatActivity) baseFragment).getCurrentChatInfo());
mentionContainer.getAdapter().setNeedUsernames(((ChatActivity) baseFragment).getCurrentChat() != null);
} else {
mentionContainer.getAdapter().setChatInfo(null);
mentionContainer.getAdapter().setNeedUsernames(false);
}
mentionContainer.getAdapter().setNeedBotContext(false);
}
}
| DrKLO/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java |
45,281 | package com.github.binarywang.wxpay.bean.request;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.*;
import me.chanjar.weixin.common.annotation.Required;
import java.util.Map;
/**
* @author chenliang
* created on 2021-08-02 5:26 下午
*
* <pre>
* 发起微信委托代扣参数
* </pre>
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Builder(builderMethodName = "newBuilder")
@NoArgsConstructor
@AllArgsConstructor
@XStreamAlias("xml")
public class WxWithholdRequest extends BaseWxPayRequest {
/**
* <pre>
* 商品描述
* body
* 是
* String(128)
* ipad mini 16G 白色
* 商品支付单简要描述
* </pre>
*/
@Required
@XStreamAlias("body")
private String body;
/**
* <pre>
* 商品详情
* detail
* 否
* String(8192)
* ipad mini 16G 白色
* 商品名称明细列表
* </pre>
*/
@XStreamAlias("detail")
private String detail;
/**
* <pre>
* 附加数据
* attach
* 否
* String(127)
* online/dev/dev1
* 商家数据包
* </pre>
*/
@XStreamAlias("attach")
private String attach;
/**
* <pre>
* 商户订单号
* out_trade_no
* 是
* String(32)
* 123456
* 商户系统内部的订单号,32字符内,可包含字母
* </pre>
*/
@Required
@XStreamAlias("out_trade_no")
private String outTradeNo;
/**
* <pre>
* 总金额
* total_fee
* 是
* int
* 888
* 订单总金额,单位分
* </pre>
*/
@Required
@XStreamAlias("total_fee")
private Integer totalFee;
/**
* <pre>
* 货币类型
* fee_type
* 否
* String(16)
* CNY
* 默认人民币:CNY
* </pre>
*/
@XStreamAlias("fee_type")
private String feeType;
/**
* <pre>
* 终端ip
* spbill_create_ip
* 否
* String(16)
* 127.0.0.1
* 用户的客户端IP
* </pre>
*/
@XStreamAlias("spbill_create_ip")
private String spbillCreateIp;
/**
* <pre>
* 商品标记
* goods_tag
* 否
* String(32)
* wxg
* 商品标记,代金券或立减优惠功能参数
* </pre>
*/
@XStreamAlias("goods_tag")
private String goodsTag;
/**
* <pre>
* 回调通知url
* notify_url
* 是
* String(256)
* https://weixin.qq.com
* 回调通知地址
* </pre>
*/
@Required
@XStreamAlias("notify_url")
private String notifyUrl;
/**
* <pre>
* 交易类型
* trade_type
* 是
* String(16)
* JSAPI
* JSAPI,MWEB
* </pre>
*/
@Required
@XStreamAlias("trade_type")
private String tradeType;
/**
* <pre>
* 委托代扣协议ID
* contract_id
* 是
* String(32)
* Wx234324808503234483920
* 签约成功后微信返回的委托代扣协议ID
* </pre>
*/
@Required
@XStreamAlias("contract_id")
private String contractId;
@Override
protected void checkConstraints() throws WxPayException {
}
@Override
protected void storeMap(Map<String, String> map) {
map.put("body", body);
map.put("detail", detail);
map.put("attach", attach);
map.put("out_trade_no", outTradeNo);
map.put("total_fee", totalFee.toString());
map.put("fee_type", feeType);
map.put("spbill_create_ip", spbillCreateIp);
map.put("goods_tag", goodsTag);
map.put("notify_url", notifyUrl);
map.put("trade_type", tradeType);
map.put("contract_id", contractId);
}
}
| Wechat-Group/WxJava | weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxWithholdRequest.java |
45,282 | package com.mxgraph.online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GitlabAuthServlet extends GitlabAuth implements ServletComm
{
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
super.doGetAbst(request, response);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/GitlabAuthServlet.java |
45,283 | /**
* Copyright (c) 2006-2019, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GoogleAuthServlet extends GoogleAuth implements ServletComm
{
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
super.doGetAbst(request, response);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/GoogleAuthServlet.java |
45,284 | package com.mxgraph.online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GitHubAuthServlet extends GitHubAuth implements ServletComm
{
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
super.doGetAbst(request, response);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/GitHubAuthServlet.java |
45,285 | /**
* Copyright (c) 2006-2019, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class MSGraphAuthServlet extends MSGraphAuth implements ServletComm
{
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
super.doGetAbst(request, response);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/MSGraphAuthServlet.java |
45,286 | package com.mxgraph.online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DropboxAuthServlet extends DropboxAuth implements ServletComm
{
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
super.doGetAbst(request, response);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/DropboxAuthServlet.java |
45,287 | package me.chanjar.weixin.mp.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.WxMpHostConfig;
import static me.chanjar.weixin.mp.config.WxMpHostConfig.API_DEFAULT_HOST_URL;
import static me.chanjar.weixin.mp.config.WxMpHostConfig.MP_DEFAULT_HOST_URL;
import static me.chanjar.weixin.mp.config.WxMpHostConfig.OPEN_DEFAULT_HOST_URL;
import static me.chanjar.weixin.mp.config.WxMpHostConfig.buildUrl;
/**
* <pre>
* 公众号接口api地址
* Created by BinaryWang on 2019-06-03.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public interface WxMpApiUrl {
/**
* 得到api完整地址.
*
* @param config 微信公众号配置
* @return api地址
*/
default String getUrl(WxMpConfigStorage config) {
WxMpHostConfig hostConfig = null;
if (config != null) {
hostConfig = config.getHostConfig();
}
return buildUrl(hostConfig, this.getPrefix(), this.getPath());
}
/**
* the path
*
* @return path
*/
String getPath();
/**
* the prefix
*
* @return prefix
*/
String getPrefix();
@AllArgsConstructor
@Getter
enum Device implements WxMpApiUrl {
/**
* get_bind_device.
*/
DEVICE_GET_BIND_DEVICE(API_DEFAULT_HOST_URL, "/device/get_bind_device"),
/**
* get_openid.
*/
DEVICE_GET_OPENID(API_DEFAULT_HOST_URL, "/device/get_openid"),
/**
* compel_unbind.
*/
DEVICE_COMPEL_UNBIND(API_DEFAULT_HOST_URL, "/device/compel_unbind?"),
/**
* unbind.
*/
DEVICE_UNBIND(API_DEFAULT_HOST_URL, "/device/unbind?"),
/**
* compel_bind.
*/
DEVICE_COMPEL_BIND(API_DEFAULT_HOST_URL, "/device/compel_bind"),
/**
* bind.
*/
DEVICE_BIND(API_DEFAULT_HOST_URL, "/device/bind"),
/**
* authorize_device.
*/
DEVICE_AUTHORIZE_DEVICE(API_DEFAULT_HOST_URL, "/device/authorize_device"),
/**
* getqrcode.
*/
DEVICE_GETQRCODE(API_DEFAULT_HOST_URL, "/device/getqrcode"),
/**
* transmsg.
*/
DEVICE_TRANSMSG(API_DEFAULT_HOST_URL, "/device/transmsg");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum OAuth2 implements WxMpApiUrl {
/**
* 用code换取oauth2的access token.
*/
OAUTH2_ACCESS_TOKEN_URL(API_DEFAULT_HOST_URL, "/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"),
/**
* 刷新oauth2的access token.
*/
OAUTH2_REFRESH_TOKEN_URL(API_DEFAULT_HOST_URL, "/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"),
/**
* 用oauth2获取用户信息.
*/
OAUTH2_USERINFO_URL(API_DEFAULT_HOST_URL, "/sns/userinfo?access_token=%s&openid=%s&lang=%s"),
/**
* 验证oauth2的access token是否有效.
*/
OAUTH2_VALIDATE_TOKEN_URL(API_DEFAULT_HOST_URL, "/sns/auth?access_token=%s&openid=%s"),
/**
* oauth2授权的url连接.
*/
CONNECT_OAUTH2_AUTHORIZE_URL(OPEN_DEFAULT_HOST_URL, "/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s&connect_redirect=1#wechat_redirect");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Other implements WxMpApiUrl {
/**
* 获取access_token.
*/
GET_ACCESS_TOKEN_URL(API_DEFAULT_HOST_URL, "/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"),
/**
* 获取稳定版 access_token.
*/
GET_STABLE_ACCESS_TOKEN_URL(API_DEFAULT_HOST_URL, "/cgi-bin/stable_token"),
/**
* 获得各种类型的ticket.
*/
GET_TICKET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/ticket/getticket?type="),
/**
* 长链接转短链接接口.
*/
SHORTURL_API_URL(API_DEFAULT_HOST_URL, "/cgi-bin/shorturl"),
/**
* 语义查询接口.
*/
SEMANTIC_SEMPROXY_SEARCH_URL(API_DEFAULT_HOST_URL, "/semantic/semproxy/search"),
/**
* 获取微信服务器IP地址.
*/
GET_CALLBACK_IP_URL(API_DEFAULT_HOST_URL, "/cgi-bin/getcallbackip"),
/**
* 网络检测.
*/
NETCHECK_URL(API_DEFAULT_HOST_URL, "/cgi-bin/callback/check"),
/**
* 第三方使用网站应用授权登录的url.
*/
QRCONNECT_URL(OPEN_DEFAULT_HOST_URL, "/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"),
/**
* 获取公众号的自动回复规则.
*/
GET_CURRENT_AUTOREPLY_INFO_URL(API_DEFAULT_HOST_URL, "/cgi-bin/get_current_autoreply_info"),
/**
* 公众号调用或第三方平台帮公众号调用对公众号的所有api调用(包括第三方帮其调用)次数进行清零.
*/
CLEAR_QUOTA_URL(API_DEFAULT_HOST_URL, "/cgi-bin/clear_quota"),
/**
* 短key托管(生成短key的url)
*/
GEN_SHORTEN_URL(API_DEFAULT_HOST_URL, "/cgi-bin/shorten/gen"),
/**
* 短key解析(解析短key的url)
*/
FETCH_SHORTEN_URL(API_DEFAULT_HOST_URL, "/cgi-bin/shorten/fetch");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Marketing implements WxMpApiUrl {
/**
* sets add.
*/
USER_ACTION_SETS_ADD(API_DEFAULT_HOST_URL, "/marketing/user_action_sets/add?version=v1.0"),
/**
* get.
*/
USER_ACTION_SETS_GET(API_DEFAULT_HOST_URL, "/marketing/user_action_sets/get"),
/**
* add.
*/
USER_ACTIONS_ADD(API_DEFAULT_HOST_URL, "/marketing/user_actions/add?version=v1.0"),
/**
* get.
*/
WECHAT_AD_LEADS_GET(API_DEFAULT_HOST_URL, "/marketing/wechat_ad_leads/get");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Menu implements WxMpApiUrl {
/**
* get_current_selfmenu_info.
*/
GET_CURRENT_SELFMENU_INFO(API_DEFAULT_HOST_URL, "/cgi-bin/get_current_selfmenu_info"),
/**
* trymatch.
*/
MENU_TRYMATCH(API_DEFAULT_HOST_URL, "/cgi-bin/menu/trymatch"),
/**
* get.
*/
MENU_GET(API_DEFAULT_HOST_URL, "/cgi-bin/menu/get"),
/**
* delconditional.
*/
MENU_DELCONDITIONAL(API_DEFAULT_HOST_URL, "/cgi-bin/menu/delconditional"),
/**
* delete.
*/
MENU_DELETE(API_DEFAULT_HOST_URL, "/cgi-bin/menu/delete"),
/**
* create.
*/
MENU_CREATE(API_DEFAULT_HOST_URL, "/cgi-bin/menu/create"),
/**
* addconditional.
*/
MENU_ADDCONDITIONAL(API_DEFAULT_HOST_URL, "/cgi-bin/menu/addconditional");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Qrcode implements WxMpApiUrl {
/**
* create.
*/
QRCODE_CREATE(API_DEFAULT_HOST_URL, "/cgi-bin/qrcode/create"),
/**
* showqrcode.
*/
SHOW_QRCODE(MP_DEFAULT_HOST_URL, "/cgi-bin/showqrcode"),
/**
* showqrcode.
*/
SHOW_QRCODE_WITH_TICKET(MP_DEFAULT_HOST_URL, "/cgi-bin/showqrcode?ticket=%s");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum ShakeAround implements WxMpApiUrl {
/**
* getshakeinfo.
*/
SHAKEAROUND_USER_GETSHAKEINFO(API_DEFAULT_HOST_URL, "/shakearound/user/getshakeinfo"),
/**
* add.
*/
SHAKEAROUND_PAGE_ADD(API_DEFAULT_HOST_URL, "/shakearound/page/add"),
/**
* bindpage.
*/
SHAKEAROUND_DEVICE_BINDPAGE(API_DEFAULT_HOST_URL, "/shakearound/device/bindpage"),
/**
* search.
*/
SHAKEAROUND_RELATION_SEARCH(API_DEFAULT_HOST_URL, "/shakearound/relation/search");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum SubscribeMsg implements WxMpApiUrl {
/**
* subscribemsg.
*/
SUBSCRIBE_MESSAGE_AUTHORIZE_URL(MP_DEFAULT_HOST_URL, "/mp/subscribemsg?action=get_confirm&appid=%s&scene=%d&template_id=%s&redirect_url=%s&reserved=%s#wechat_redirect"),
/**
* subscribe once.
*/
SEND_MESSAGE_ONCE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/template/subscribe"),
/**
* 订阅通知消息发送.
*/
SEND_SUBSCRIBE_MESSAGE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/subscribe/bizsend"),
/**
* 获取模板标题下的关键词列表.
*/
GET_PUB_TEMPLATE_TITLE_LIST_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/getpubtemplatetitles"),
/**
* 获取模板标题下的关键词列表.
*/
GET_PUB_TEMPLATE_KEY_WORDS_BY_ID_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/getpubtemplatekeywords"),
/**
* 组合模板并添加至帐号下的个人模板库.
*/
TEMPLATE_ADD_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/addtemplate"),
/**
* 获取当前帐号下的个人模板列表.
*/
TEMPLATE_LIST_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/gettemplate"),
/**
* 删除帐号下的某个模板.
*/
TEMPLATE_DEL_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/deltemplate"),
/**
* 获取小程序账号的类目
*/
GET_CATEGORY_URL(API_DEFAULT_HOST_URL, "/wxaapi/newtmpl/getcategory"),
UNIFORM_MSG_SEND_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/wxopen/template/uniform_send"),
ACTIVITY_ID_CREATE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/wxopen/activityid/create"),
UPDATABLE_MSG_SEND_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/wxopen/updatablemsg/send");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum TemplateMsg implements WxMpApiUrl {
/**
* send.
*/
MESSAGE_TEMPLATE_SEND(API_DEFAULT_HOST_URL, "/cgi-bin/message/template/send"),
/**
* api_set_industry.
*/
TEMPLATE_API_SET_INDUSTRY(API_DEFAULT_HOST_URL, "/cgi-bin/template/api_set_industry"),
/**
* get_industry.
*/
TEMPLATE_GET_INDUSTRY(API_DEFAULT_HOST_URL, "/cgi-bin/template/get_industry"),
/**
* api_add_template.
*/
TEMPLATE_API_ADD_TEMPLATE(API_DEFAULT_HOST_URL, "/cgi-bin/template/api_add_template"),
/**
* get_all_private_template.
*/
TEMPLATE_GET_ALL_PRIVATE_TEMPLATE(API_DEFAULT_HOST_URL, "/cgi-bin/template/get_all_private_template"),
/**
* del_private_template.
*/
TEMPLATE_DEL_PRIVATE_TEMPLATE(API_DEFAULT_HOST_URL, "/cgi-bin/template/del_private_template");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum UserBlacklist implements WxMpApiUrl {
/**
* getblacklist.
*/
GETBLACKLIST(API_DEFAULT_HOST_URL, "/cgi-bin/tags/members/getblacklist"),
/**
* batchblacklist.
*/
BATCHBLACKLIST(API_DEFAULT_HOST_URL, "/cgi-bin/tags/members/batchblacklist"),
/**
* batchunblacklist.
*/
BATCHUNBLACKLIST(API_DEFAULT_HOST_URL, "/cgi-bin/tags/members/batchunblacklist");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum UserTag implements WxMpApiUrl {
/**
* create.
*/
TAGS_CREATE(API_DEFAULT_HOST_URL, "/cgi-bin/tags/create"),
/**
* get.
*/
TAGS_GET(API_DEFAULT_HOST_URL, "/cgi-bin/tags/get"),
/**
* update.
*/
TAGS_UPDATE(API_DEFAULT_HOST_URL, "/cgi-bin/tags/update"),
/**
* delete.
*/
TAGS_DELETE(API_DEFAULT_HOST_URL, "/cgi-bin/tags/delete"),
/**
* get.
*/
TAG_GET(API_DEFAULT_HOST_URL, "/cgi-bin/user/tag/get"),
/**
* batchtagging.
*/
TAGS_MEMBERS_BATCHTAGGING(API_DEFAULT_HOST_URL, "/cgi-bin/tags/members/batchtagging"),
/**
* batchuntagging.
*/
TAGS_MEMBERS_BATCHUNTAGGING(API_DEFAULT_HOST_URL, "/cgi-bin/tags/members/batchuntagging"),
/**
* getidlist.
*/
TAGS_GETIDLIST(API_DEFAULT_HOST_URL, "/cgi-bin/tags/getidlist");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Wifi implements WxMpApiUrl {
/**
* list.
*/
BIZWIFI_SHOP_LIST(API_DEFAULT_HOST_URL, "/bizwifi/shop/list"),
/**
* get.
*/
BIZWIFI_SHOP_GET(API_DEFAULT_HOST_URL, "/bizwifi/shop/get"),
/**
* upadte.
*/
BIZWIFI_SHOP_UPDATE(API_DEFAULT_HOST_URL, "/bizwifi/shop/update");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum AiOpen implements WxMpApiUrl {
/**
* translatecontent.
*/
TRANSLATE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/voice/translatecontent?lfrom=%s<o=%s"),
/**
* addvoicetorecofortext.
*/
VOICE_UPLOAD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/voice/addvoicetorecofortext?format=%s&voice_id=%s&lang=%s"),
/**
* queryrecoresultfortext.
*/
VOICE_QUERY_RESULT_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/voice/queryrecoresultfortext");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Ocr implements WxMpApiUrl {
/**
* 身份证识别.
*/
IDCARD(API_DEFAULT_HOST_URL, "/cv/ocr/idcard?img_url=%s"),
FILEIDCARD(API_DEFAULT_HOST_URL, "/cv/ocr/idcard"),
/**
* 银行卡OCR识别
*/
BANK_CARD(API_DEFAULT_HOST_URL, "/cv/ocr/bankcard?img_url=%s"),
/**
* 银行卡OCR识别(文件)
*/
FILE_BANK_CARD(API_DEFAULT_HOST_URL, "/cv/ocr/bankcard"),
/**
* 行驶证OCR识别
*/
DRIVING(API_DEFAULT_HOST_URL, "/cv/ocr/driving?img_url=%s"),
/**
* 行驶证OCR识别(文件)
*/
FILE_DRIVING(API_DEFAULT_HOST_URL, "/cv/ocr/driving"),
/**
* 驾驶证OCR识别
*/
DRIVING_LICENSE(API_DEFAULT_HOST_URL, "/cv/ocr/drivinglicense?img_url=%s"),
/**
* 驾驶证OCR识别(文件)
*/
FILE_DRIVING_LICENSE(API_DEFAULT_HOST_URL, "/cv/ocr/drivinglicense"),
/**
* 营业执照OCR识别
*/
BIZ_LICENSE(API_DEFAULT_HOST_URL, "/cv/ocr/bizlicense?img_url=%s"),
/**
* 营业执照OCR识别(文件)
*/
FILE_BIZ_LICENSE(API_DEFAULT_HOST_URL, "/cv/ocr/bizlicense"),
/**
* 通用印刷体OCR识别
*/
COMM(API_DEFAULT_HOST_URL, "/cv/ocr/comm?img_url=%s"),
/**
* 通用印刷体OCR识别(文件)
*/
FILE_COMM(API_DEFAULT_HOST_URL, "/cv/ocr/comm");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Card implements WxMpApiUrl {
/**
* create.
*/
CARD_CREATE(API_DEFAULT_HOST_URL, "/card/create"),
/**
* get.
*/
CARD_GET(API_DEFAULT_HOST_URL, "/card/get"),
/**
* wx_card.
*/
CARD_GET_TICKET(API_DEFAULT_HOST_URL, "/cgi-bin/ticket/getticket?type=wx_card"),
/**
* decrypt.
*/
CARD_CODE_DECRYPT(API_DEFAULT_HOST_URL, "/card/code/decrypt"),
/**
* get.
*/
CARD_CODE_GET(API_DEFAULT_HOST_URL, "/card/code/get"),
/**
* consume.
*/
CARD_CODE_CONSUME(API_DEFAULT_HOST_URL, "/card/code/consume"),
/**
* mark.
*/
CARD_CODE_MARK(API_DEFAULT_HOST_URL, "/card/code/mark"),
/**
* set.
*/
CARD_TEST_WHITELIST(API_DEFAULT_HOST_URL, "/card/testwhitelist/set"),
/**
* create.
*/
CARD_QRCODE_CREATE(API_DEFAULT_HOST_URL, "/card/qrcode/create"),
/**
* create.
*/
CARD_LANDING_PAGE_CREATE(API_DEFAULT_HOST_URL, "/card/landingpage/create"),
/**
* 将用户的卡券设置为失效状态.
*/
CARD_CODE_UNAVAILABLE(API_DEFAULT_HOST_URL, "/card/code/unavailable"),
/**
* 卡券删除.
*/
CARD_DELETE(API_DEFAULT_HOST_URL, "/card/delete"),
/**
* 导入code接口.
*/
CARD_CODE_DEPOSIT(API_DEFAULT_HOST_URL, "/card/code/deposit"),
/**
* 查询导入code数目接口
*/
CARD_CODE_DEPOSIT_COUNT(API_DEFAULT_HOST_URL, "/card/code/getdepositcount"),
/**
* 核查code接口
*/
CARD_CODE_CHECKCODE(API_DEFAULT_HOST_URL, "/card/code/checkcode"),
/**
* 图文消息群发卡券
*/
CARD_MPNEWS_GETHTML(API_DEFAULT_HOST_URL, "/card/mpnews/gethtml"),
/**
* 修改库存接口
*/
CARD_MODIFY_STOCK(API_DEFAULT_HOST_URL, "/card/modifystock"),
/**
* 更改Code接口
*/
CARD_CODE_UPDATE(API_DEFAULT_HOST_URL, "/card/code/update"),
/**
* 设置买单接口
*/
CARD_PAYCELL_SET(API_DEFAULT_HOST_URL, "/card/paycell/set"),
/**
* 设置自助核销接口
*/
CARD_SELF_CONSUME_CELL_SET(API_DEFAULT_HOST_URL, "/card/selfconsumecell/set"),
/**
* 获取用户已领取卡券接口
*/
CARD_USER_CARD_LIST(API_DEFAULT_HOST_URL, "/card/user/getcardlist"),
;
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum DataCube implements WxMpApiUrl {
/**
* getusersummary.
*/
GET_USER_SUMMARY(API_DEFAULT_HOST_URL, "/datacube/getusersummary"),
/**
* getusercumulate.
*/
GET_USER_CUMULATE(API_DEFAULT_HOST_URL, "/datacube/getusercumulate"),
/**
* getarticlesummary.
*/
GET_ARTICLE_SUMMARY(API_DEFAULT_HOST_URL, "/datacube/getarticlesummary"),
/**
* getarticletotal.
*/
GET_ARTICLE_TOTAL(API_DEFAULT_HOST_URL, "/datacube/getarticletotal"),
/**
* getuserread.
*/
GET_USER_READ(API_DEFAULT_HOST_URL, "/datacube/getuserread"),
/**
* getuserreadhour.
*/
GET_USER_READ_HOUR(API_DEFAULT_HOST_URL, "/datacube/getuserreadhour"),
/**
* getusershare.
*/
GET_USER_SHARE(API_DEFAULT_HOST_URL, "/datacube/getusershare"),
/**
* getusersharehour.
*/
GET_USER_SHARE_HOUR(API_DEFAULT_HOST_URL, "/datacube/getusersharehour"),
/**
* getupstreammsg.
*/
GET_UPSTREAM_MSG(API_DEFAULT_HOST_URL, "/datacube/getupstreammsg"),
/**
* getupstreammsghour.
*/
GET_UPSTREAM_MSG_HOUR(API_DEFAULT_HOST_URL, "/datacube/getupstreammsghour"),
/**
* getupstreammsgweek.
*/
GET_UPSTREAM_MSG_WEEK(API_DEFAULT_HOST_URL, "/datacube/getupstreammsgweek"),
/**
* getupstreammsgmonth.
*/
GET_UPSTREAM_MSG_MONTH(API_DEFAULT_HOST_URL, "/datacube/getupstreammsgmonth"),
/**
* getupstreammsgdist.
*/
GET_UPSTREAM_MSG_DIST(API_DEFAULT_HOST_URL, "/datacube/getupstreammsgdist"),
/**
* getupstreammsgdistweek.
*/
GET_UPSTREAM_MSG_DIST_WEEK(API_DEFAULT_HOST_URL, "/datacube/getupstreammsgdistweek"),
/**
* getupstreammsgdistmonth.
*/
GET_UPSTREAM_MSG_DIST_MONTH(API_DEFAULT_HOST_URL, "/datacube/getupstreammsgdistmonth"),
/**
* getinterfacesummary.
*/
GET_INTERFACE_SUMMARY(API_DEFAULT_HOST_URL, "/datacube/getinterfacesummary"),
/**
* getinterfacesummaryhour.
*/
GET_INTERFACE_SUMMARY_HOUR(API_DEFAULT_HOST_URL, "/datacube/getinterfacesummaryhour");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Kefu implements WxMpApiUrl {
/**
* send.
*/
MESSAGE_CUSTOM_SEND(API_DEFAULT_HOST_URL, "/cgi-bin/message/custom/send"),
/**
* getkflist.
*/
GET_KF_LIST(API_DEFAULT_HOST_URL, "/cgi-bin/customservice/getkflist"),
/**
* getonlinekflist.
*/
GET_ONLINE_KF_LIST(API_DEFAULT_HOST_URL, "/cgi-bin/customservice/getonlinekflist"),
/**
* add.
*/
KFACCOUNT_ADD(API_DEFAULT_HOST_URL, "/customservice/kfaccount/add"),
/**
* update.
*/
KFACCOUNT_UPDATE(API_DEFAULT_HOST_URL, "/customservice/kfaccount/update"),
/**
* inviteworker.
*/
KFACCOUNT_INVITE_WORKER(API_DEFAULT_HOST_URL, "/customservice/kfaccount/inviteworker"),
/**
* uploadheadimg.
*/
KFACCOUNT_UPLOAD_HEAD_IMG(API_DEFAULT_HOST_URL, "/customservice/kfaccount/uploadheadimg?kf_account=%s"),
/**
* del kfaccount.
*/
KFACCOUNT_DEL(API_DEFAULT_HOST_URL, "/customservice/kfaccount/del?kf_account=%s"),
/**
* create.
*/
KFSESSION_CREATE(API_DEFAULT_HOST_URL, "/customservice/kfsession/create"),
/**
* close.
*/
KFSESSION_CLOSE(API_DEFAULT_HOST_URL, "/customservice/kfsession/close"),
/**
* getsession.
*/
KFSESSION_GET_SESSION(API_DEFAULT_HOST_URL, "/customservice/kfsession/getsession?openid=%s"),
/**
* getsessionlist.
*/
KFSESSION_GET_SESSION_LIST(API_DEFAULT_HOST_URL, "/customservice/kfsession/getsessionlist?kf_account=%s"),
/**
* getwaitcase.
*/
KFSESSION_GET_WAIT_CASE(API_DEFAULT_HOST_URL, "/customservice/kfsession/getwaitcase"),
/**
* getmsglist.
*/
MSG_RECORD_LIST(API_DEFAULT_HOST_URL, "/customservice/msgrecord/getmsglist"),
/**
* typing.
*/
CUSTOM_TYPING(API_DEFAULT_HOST_URL, "/cgi-bin/message/custom/typing");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum MassMessage implements WxMpApiUrl {
/**
* 上传群发用的图文消息.
*/
MEDIA_UPLOAD_NEWS_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/uploadnews"),
/**
* 上传群发用的视频.
*/
MEDIA_UPLOAD_VIDEO_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/uploadvideo"),
/**
* 分组群发消息.
*/
MESSAGE_MASS_SENDALL_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/sendall"),
/**
* 按openId列表群发消息.
*/
MESSAGE_MASS_SEND_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/send"),
/**
* 群发消息预览接口.
*/
MESSAGE_MASS_PREVIEW_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/preview"),
/**
* 删除群发接口.
*/
MESSAGE_MASS_DELETE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/delete"),
/**
* 获取群发速度.
*/
MESSAGE_MASS_SPEED_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/speed/get"),
/**
* 设置群发速度.
*/
MESSAGE_MASS_SPEED_SET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/speed/set"),
/**
* 查询群发消息发送状态【订阅号与服务号认证后均可用】
*/
MESSAGE_MASS_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/message/mass/get");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Material implements WxMpApiUrl {
/**
* get.
*/
MEDIA_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/get"),
/**
* jssdk media get.
*/
JSSDK_MEDIA_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/get/jssdk"),
/**
* upload.
*/
MEDIA_UPLOAD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/upload?type=%s"),
/**
* uploadimg.
*/
IMG_UPLOAD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/media/uploadimg"),
/**
* add_material.
*/
MATERIAL_ADD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/add_material?type=%s"),
/**
* add_news.
*/
NEWS_ADD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/add_news"),
/**
* get_material.
*/
MATERIAL_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/get_material"),
/**
* update_news.
*/
NEWS_UPDATE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/update_news"),
/**
* del_material.
*/
MATERIAL_DEL_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/del_material"),
/**
* get_materialcount.
*/
MATERIAL_GET_COUNT_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/get_materialcount"),
/**
* batchget_material.
*/
MATERIAL_BATCHGET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/material/batchget_material");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum MemberCard implements WxMpApiUrl {
/**
* create.
*/
MEMBER_CARD_CREATE(API_DEFAULT_HOST_URL, "/card/create"),
/**
* activate.
*/
MEMBER_CARD_ACTIVATE(API_DEFAULT_HOST_URL, "/card/membercard/activate"),
/**
* get userinfo.
*/
MEMBER_CARD_USER_INFO_GET(API_DEFAULT_HOST_URL, "/card/membercard/userinfo/get"),
/**
* updateuser.
*/
MEMBER_CARD_UPDATE_USER(API_DEFAULT_HOST_URL, "/card/membercard/updateuser"),
/**
* 会员卡激活之微信开卡接口(wx_activate=true情况调用).
*/
MEMBER_CARD_ACTIVATE_USER_FORM(API_DEFAULT_HOST_URL, "/card/membercard/activateuserform/set"),
/**
* 获取会员卡开卡插件参数.
*/
MEMBER_CARD_ACTIVATE_URL(API_DEFAULT_HOST_URL, "/card/membercard/activate/geturl"),
/**
* 会员卡信息更新.
*/
MEMBER_CARD_UPDATE(API_DEFAULT_HOST_URL, "/card/update"),
/**
* 跳转型会员卡开卡字段.
* 获取用户提交资料(wx_activate=true情况调用),开发者根据activate_ticket获取到用户填写的信息
*/
MEMBER_CARD_ACTIVATE_TEMP_INFO(API_DEFAULT_HOST_URL, "/card/membercard/activatetempinfo/get");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Store implements WxMpApiUrl {
/**
* getwxcategory.
*/
POI_GET_WX_CATEGORY_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/getwxcategory"),
/**
* updatepoi.
*/
POI_UPDATE_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/updatepoi"),
/**
* getpoilist.
*/
POI_LIST_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/getpoilist"),
/**
* delpoi.
*/
POI_DEL_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/delpoi"),
/**
* getpoi.
*/
POI_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/getpoi"),
/**
* addpoi.
*/
POI_ADD_URL(API_DEFAULT_HOST_URL, "/cgi-bin/poi/addpoi");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum User implements WxMpApiUrl {
/**
* batchget.
*/
USER_INFO_BATCH_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/user/info/batchget"),
/**
* get.
*/
USER_GET_URL(API_DEFAULT_HOST_URL, "/cgi-bin/user/get"),
/**
* info.
*/
USER_INFO_URL(API_DEFAULT_HOST_URL, "/cgi-bin/user/info"),
/**
* updateremark.
*/
USER_INFO_UPDATE_REMARK_URL(API_DEFAULT_HOST_URL, "/cgi-bin/user/info/updateremark"),
/**
* changeopenid.
*/
USER_CHANGE_OPENID_URL(API_DEFAULT_HOST_URL, "/cgi-bin/changeopenid");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Comment implements WxMpApiUrl {
/**
* 打开已群发文章评论.
*/
OPEN(API_DEFAULT_HOST_URL, "/cgi-bin/comment/open"),
/**
* 关闭已群发文章评论.
*/
CLOSE(API_DEFAULT_HOST_URL, "/cgi-bin/comment/close"),
/**
* 查看指定文章的评论数据.
*/
LIST(API_DEFAULT_HOST_URL, "/cgi-bin/comment/list"),
/**
* 将评论标记精选.
*/
MARK_ELECT(API_DEFAULT_HOST_URL, "/cgi-bin/comment/markelect"),
/**
* 将评论取消精选.
*/
UNMARK_ELECT(API_DEFAULT_HOST_URL, "/cgi-bin/comment/unmarkelect"),
/**
* 删除评论.
*/
DELETE(API_DEFAULT_HOST_URL, "/cgi-bin/comment/delete"),
/**
* 回复评论.
*/
REPLY_ADD(API_DEFAULT_HOST_URL, "/cgi-bin/comment/reply/add"),
/**
* 删除回复.
*/
REPLY_DELETE(API_DEFAULT_HOST_URL, "/cgi-bin/comment/reply/delete");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum ImgProc implements WxMpApiUrl {
/**
* 二维码/条码识别
*/
QRCODE(API_DEFAULT_HOST_URL, "/cv/img/qrcode?img_url=%s"),
/**
* 二维码/条码识别(文件)
*/
FILE_QRCODE(API_DEFAULT_HOST_URL, "/cv/img/qrcode"),
/**
* 图片高清化
*/
SUPER_RESOLUTION(API_DEFAULT_HOST_URL, "/cv/img/superresolution?img_url=%s"),
/**
* 图片高清化(文件)
*/
FILE_SUPER_RESOLUTION(API_DEFAULT_HOST_URL, "/cv/img/superresolution"),
/**
* 图片智能裁剪
*/
AI_CROP(API_DEFAULT_HOST_URL, "/cv/img/aicrop?img_url=%s&ratios=%s"),
/**
* 图片智能裁剪(文件)
*/
FILE_AI_CROP(API_DEFAULT_HOST_URL, "/cv/img/aicrop?ratios=%s");
private final String prefix;
private final String path;
}
@AllArgsConstructor
@Getter
enum Invoice implements WxMpApiUrl {
/**
* 获取用户开票授权地址
*/
GET_AUTH_URL(API_DEFAULT_HOST_URL, "/card/invoice/getauthurl"),
/**
* 获取用户开票授权信息
*/
GET_AUTH_DATA(API_DEFAULT_HOST_URL, "/card/invoice/getauthdata"),
/**
* 拒绝为用户开票
*/
REJECT_INSERT(API_DEFAULT_HOST_URL, "/card/invoice/rejectinsert"),
/**
* 开票
*/
MAKE_OUT_INVOICE(API_DEFAULT_HOST_URL, "/card/invoice/makeoutinvoice"),
/**
* 发票冲红
*/
CLEAR_OUT_INVOICE(API_DEFAULT_HOST_URL, "/card/invoice/clearoutinvoice"),
/**
* 查询发票信息
*/
QUERY_INVOICE_INFO(API_DEFAULT_HOST_URL, "/card/invoice/queryinvoceinfo"),
/**
* 设置商户信息联系
*/
SET_CONTACT_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=set_contact"),
/**
* 获取商户联系信息
*/
GET_CONTACT_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=get_contact"),
/**
* 设置授权页面字段
*/
SET_AUTH_FIELD_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=set_auth_field"),
/**
* 获取授权页面字段
*/
GET_AUTH_FIELD_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=get_auth_field"),
/**
* 设置关联商户
*/
SET_PAY_MCH_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=set_pay_mch"),
/**
* 获取关联商户
*/
GET_PAY_MCH_SET_BIZ_ATTR(API_DEFAULT_HOST_URL, "/card/invoice/setbizattr?action=get_pay_mch"),
/**
* 报销方查询报销发票信息
*/
GET_INVOICE_INFO(API_DEFAULT_HOST_URL, "/card/invoice/reimburse/getinvoiceinfo"),
/**
* 报销方批量查询报销发票信息
*/
GET_INVOICE_BATCH(API_DEFAULT_HOST_URL, "/card/invoice/reimburse/getinvoicebatch"),
/**
* 报销方更新发票状态
*/
UPDATE_INVOICE_STATUS(API_DEFAULT_HOST_URL, "/card/invoice/reimburse/updateinvoicestatus"),
/**
* 报销方批量更新发票状态
*/
UPDATE_STATUS_BATCH(API_DEFAULT_HOST_URL, "/card/invoice/reimburse/updatestatusbatch"),
;
private final String prefix;
private final String path;
}
/**
* 对话能力
*/
@AllArgsConstructor
@Getter
enum Guide implements WxMpApiUrl {
/**
* 添加顾问
*/
ADD_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguideacct"),
/**
* 修改顾问
*/
UPDATE_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/updateguideacct"),
/**
* 获取顾问信息
*/
GET_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguideacct"),
/**
* 删除顾问
*/
DEL_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguideacct"),
/**
* 获取服务号顾问列表
*/
LIST_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguideacctlist"),
/**
* 生成顾问二维码
*/
CREATE_QR_CODE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/guidecreateqrcode"),
/**
* 获取顾问聊天记录
*/
GET_GUIDE_CHAT_RECORD(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyerchatrecord"),
/**
* 设置快捷回复与关注自动回复
*/
SET_GUIDE_CONFIG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/setguideconfig"),
/**
* 获取快捷回复与关注自动回复
*/
GET_GUIDE_CONFIG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguideconfig"),
/**
* 为服务号设置敏感词与离线自动回复
*/
SET_GUIDE_ACCT_CONFIG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/setguideacctconfig"),
/**
* 获取服务号敏感词与离线自动回复
*/
GET_GUIDE_ACCT_CONFIG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguideacctconfig"),
/**
* 允许微信用户复制小程序页面路径
*/
PUSH_SHOW_WX_PATH_MENU(API_DEFAULT_HOST_URL, "/cgi-bin/guide/pushshowwxapathmenu"),
/**
* 新建顾问分组
*/
NEW_GUIDE_GROUP(API_DEFAULT_HOST_URL, "/cgi-bin/guide/newguidegroup"),
/**
* 获取服务号下所有顾问分组的列表
*/
GET_GUIDE_GROUP_LIST(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidegrouplist"),
/**
* 获取指定顾问分组内顾问信息
*/
GET_GROUP_GUIDE_INFO(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getgroupinfo"),
/**
* 分组内添加顾问
*/
ADD_GROUP_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguide2guidegroup"),
/**
* 分组内删除顾问
*/
DEL_GROUP_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguide2guidegroup"),
/**
* 获取顾问所在分组
*/
GET_GROUP_ON_GUIDE(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getgroupbyguide"),
/**
* 删除指定顾问分组
*/
DEL_GROUP(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidegroup"),
/**
* 为顾问分配客户
*/
ADD_GUIDE_BUYER_RELATION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguidebuyerrelation"),
/**
* 为顾问移除客户
*/
DEL_GUIDE_BUYER_RELATION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidebuyerrelation"),
/**
* 获取顾问的客户列表
*/
GET_GUIDE_BUYER_RELATION_LIST(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyerrelationlist"),
/**
* 为客户更换顾问
*/
REBIND_GUIDE_ACCT_FOR_BUYER(API_DEFAULT_HOST_URL, "/cgi-bin/guide/rebindguideacctforbuyer"),
/**
* 修改客户昵称
*/
UPDATE_GUIDE_BUYER_RELATION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/updateguidebuyerrelation"),
/**
* 查询客户所属顾问
*/
GET_GUIDE_BUYER_RELATION_BY_BUYER(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyerrelationbybuyer"),
/**
* 查询指定顾问和客户的关系
*/
GET_GUIDE_BUYER_RELATION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyerrelation"),
/**
* 新建标签类型
*/
NEW_GUIDE_TAG_OPTION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/newguidetagoption"),
/**
* 删除标签类型
*/
DEL_GUIDE_TAG_OPTION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidetagoption"),
/**
* 为标签添加可选值
*/
ADD_GUIDE_TAG_OPTION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguidetagoption"),
/**
* 获取标签和可选值
*/
GET_GUIDE_TAG_OPTION(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidetagoption"),
/**
* 为客户设置标签
*/
ADD_GUIDE_BUYER_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguidebuyertag"),
/**
* 查询客户标签
*/
GET_GUIDE_BUYER_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyertag"),
/**
* 根据标签值筛选客户
*/
QUERY_GUIDE_BUYER_BY_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/queryguidebuyerbytag"),
/**
* 删除客户标签
*/
DEL_GUIDE_BUYER_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidebuyertag"),
/**
* 设置自定义客户信息
*/
ADD_GUIDE_BUYER_DISPLAY_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguidebuyerdisplaytag"),
/**
* 获取自定义客户信息
*/
GET_GUIDE_BUYER_DISPLAY_TAG(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidebuyerdisplaytag"),
/**
* 添加小程序卡片素材
*/
SET_GUIDE_CARD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/setguidecardmaterial"),
/**
* 查询小程序卡片素材
*/
GET_GUIDE_CARD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidecardmaterial"),
/**
* 删除小程序卡片素材
*/
DEL_GUIDE_CARD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidecardmaterial"),
/**
* 添加图片素材
*/
SET_GUIDE_IMAGE_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/setguideimagematerial"),
/**
* 查询图片素材
*/
GET_GUIDE_IMAGE_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguideimagematerial"),
/**
* 删除图片素材
*/
DEL_GUIDE_IMAGE_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguideimagematerial"),
/**
* 添加文字素材
*/
SET_GUIDE_WORD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/setguidewordmaterial"),
/**
* 查询文字素材
*/
GET_GUIDE_WORD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidewordmaterial"),
/**
* 删除文字素材
*/
DEL_GUIDE_WORD_MATERIAL(API_DEFAULT_HOST_URL, "/cgi-bin/guide/delguidewordmaterial"),
/**
* 添加群发任务
*/
ADD_GUIDE_MASSED_JOB(API_DEFAULT_HOST_URL, "/cgi-bin/guide/addguidemassendjob"),
/**
* 获取群发任务列表
*/
GET_GUIDE_MASSED_JOB_LIST(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidemassendjoblist"),
/**
* 获取指定群发任务信息
*/
GET_GUIDE_MASSED_JOB(API_DEFAULT_HOST_URL, "/cgi-bin/guide/getguidemassendjob"),
/**
* 修改群发任务
*/
UPDATE_GUIDE_MASSED_JOB(API_DEFAULT_HOST_URL, "/cgi-bin/guide/updateguidemassendjob"),
/**
* 取消群发任务
*/
CANCEL_GUIDE_MASSED_JOB(API_DEFAULT_HOST_URL, "/cgi-bin/guide/cancelguidemassendjob"),
;
private final String prefix;
private final String path;
}
/**
* 草稿箱 能力:
* 新建草稿
* 获取草稿
* 删除草稿
* 修改草稿
* 获取草稿总数
* 获取草稿列表
* MP端开关(仅内测期间使用)- 上线后废弃,没实现,可以自己去公众号后台开启草稿箱
*/
@AllArgsConstructor
@Getter
enum Draft implements WxMpApiUrl {
/**
* 新建草稿
*/
ADD_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/add"),
/**
* 修改草稿
*/
UPDATE_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/update"),
/**
* 获取草稿
*/
GET_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/get"),
/**
* 删除草稿
*/
DEL_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/delete"),
/**
* 获取草稿列表
*/
LIST_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/batchget"),
/**
* 获取草稿总数
*/
COUNT_DRAFT(API_DEFAULT_HOST_URL, "/cgi-bin/draft/count");
private final String prefix;
private final String path;
}
/**
* 发布能力:
* 发布接口
* 发布状态轮询接口
* 事件推送发布结果 -- 是回调,没实现
* 删除发布
* 通过 article_id 获取已发布文章
* 获取成功发布列表
*/
@AllArgsConstructor
@Getter
enum FreePublish implements WxMpApiUrl {
/**
* 发布接口
*/
SUBMIT(API_DEFAULT_HOST_URL, "/cgi-bin/freepublish/submit"),
/**
* 通过 article_id 获取已发布文章
*/
GET_ARTICLE(API_DEFAULT_HOST_URL, "/cgi-bin/freepublish/getarticle"),
/**
* 发布状态轮询接口
*/
GET_PUSH_STATUS(API_DEFAULT_HOST_URL, "/cgi-bin/freepublish/get"),
/**
* 删除发布
*/
DEL_PUSH(API_DEFAULT_HOST_URL, "/cgi-bin/freepublish/delete"),
/**
* 获取成功发布列表
*/
BATCH_GET(API_DEFAULT_HOST_URL, "/cgi-bin/freepublish/batchget")
;
private final String prefix;
private final String path;
}
}
| Wechat-Group/WxJava | weixin-java-mp/src/main/java/me/chanjar/weixin/mp/enums/WxMpApiUrl.java |
45,288 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Adapters;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.SystemClock;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.support.LongSparseIntArray;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_chatlists;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.ArchiveHintCell;
import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Cells.DialogMeUrlCell;
import org.telegram.ui.Cells.DialogsEmptyCell;
import org.telegram.ui.Cells.DialogsHintCell;
import org.telegram.ui.Cells.DialogsRequestedEmptyCell;
import org.telegram.ui.Cells.HeaderCell;
import org.telegram.ui.Cells.ProfileSearchCell;
import org.telegram.ui.Cells.RequestPeerRequirementsCell;
import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.UserCell;
import org.telegram.ui.Components.ArchiveHelp;
import org.telegram.ui.Components.BlurredRecyclerView;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.FlickerLoadingView;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.ListView.AdapterWithDiffUtils;
import org.telegram.ui.Components.PullForegroundDrawable;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.Stories.DialogStoriesCell;
import org.telegram.ui.Stories.StoriesController;
import org.telegram.ui.Stories.StoriesListPlaceProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
public class DialogsAdapter extends RecyclerListView.SelectionAdapter implements DialogCell.DialogCellDelegate {
public final static int VIEW_TYPE_DIALOG = 0,
VIEW_TYPE_FLICKER = 1,
VIEW_TYPE_RECENTLY_VIEWED = 2,
VIEW_TYPE_DIVIDER = 3,
VIEW_TYPE_ME_URL = 4,
VIEW_TYPE_EMPTY = 5,
VIEW_TYPE_USER = 6,
VIEW_TYPE_HEADER = 7,
VIEW_TYPE_SHADOW = 8,
// VIEW_TYPE_ARCHIVE = 9,
VIEW_TYPE_LAST_EMPTY = 10,
VIEW_TYPE_NEW_CHAT_HINT = 11,
VIEW_TYPE_TEXT = 12,
VIEW_TYPE_CONTACTS_FLICKER = 13,
VIEW_TYPE_HEADER_2 = 14,
VIEW_TYPE_REQUIREMENTS = 15,
VIEW_TYPE_REQUIRED_EMPTY = 16,
VIEW_TYPE_FOLDER_UPDATE_HINT = 17,
VIEW_TYPE_STORIES = 18,
VIEW_TYPE_ARCHIVE_FULLSCREEN = 19;
private Context mContext;
private ArchiveHintCell archiveHintCell;
private ArrayList<TLRPC.TL_contact> onlineContacts;
private boolean forceUpdatingContacts;
private int dialogsCount;
private int prevContactsCount;
private int prevDialogsCount;
private int dialogsType;
private int folderId;
private long openedDialogId;
private int currentCount;
private boolean isOnlySelect;
private ArrayList<Long> selectedDialogs;
private boolean hasHints;
private boolean hasChatlistHint;
private int currentAccount;
private boolean dialogsListFrozen;
private boolean isReordering;
private long lastSortTime;
private boolean collapsedView;
private boolean firstUpdate = true;
RecyclerListView recyclerListView;
private PullForegroundDrawable pullForegroundDrawable;
ArrayList<ItemInternal> itemInternals = new ArrayList<>();
ArrayList<ItemInternal> oldItems = new ArrayList<>();
private Drawable arrowDrawable;
private DialogsPreloader preloader;
private boolean forceShowEmptyCell;
private DialogsActivity parentFragment;
private boolean isTransitionSupport;
private TLRPC.RequestPeerType requestPeerType;
public boolean isEmpty;
public DialogsAdapter(DialogsActivity fragment, Context context, int type, int folder, boolean onlySelect, ArrayList<Long> selected, int account, TLRPC.RequestPeerType requestPeerType) {
mContext = context;
parentFragment = fragment;
dialogsType = type;
folderId = folder;
isOnlySelect = onlySelect;
hasHints = folder == 0 && type == 0 && !onlySelect;
selectedDialogs = selected;
currentAccount = account;
// setHasStableIds(true);
if (folder == 0) {
this.preloader = new DialogsPreloader();
}
this.requestPeerType = requestPeerType;
}
public void setRecyclerListView(RecyclerListView recyclerListView) {
this.recyclerListView = recyclerListView;
}
public void setOpenedDialogId(long id) {
openedDialogId = id;
}
public void onReorderStateChanged(boolean reordering) {
isReordering = reordering;
}
public int fixPosition(int position) {
if (hasChatlistHint) {
position--;
}
if (hasHints) {
position -= 2 + MessagesController.getInstance(currentAccount).hintDialogs.size();
}
if (dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_GROUPS || dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY) {
position -= 2;
} else if (dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_USERS) {
position -= 1;
}
return position;
}
public boolean isDataSetChanged() {
return true;
}
public void setDialogsType(int type) {
dialogsType = type;
notifyDataSetChanged();
}
public int getDialogsType() {
return dialogsType;
}
public int getDialogsCount() {
return dialogsCount;
}
@Override
public long getItemId(int position) {
return itemInternals.get(position).stableId;
}
@Override
public int getItemCount() {
currentCount = itemInternals.size();
return currentCount;
}
public int findDialogPosition(long dialogId) {
for (int i = 0; i < itemInternals.size(); i++) {
if (itemInternals.get(i).dialog != null && itemInternals.get(i).dialog.id == dialogId) {
return i;
}
}
return -1;
}
public int fixScrollGap(RecyclerListView animationSupportListView, int p, int offset, boolean hasHidenArchive, boolean hasStories, boolean hasTabs, boolean oppened) {
int itemsToEnd = getItemCount() - p;
int cellHeight = AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 78 : 72);
int bottom = offset + animationSupportListView.getPaddingTop() + itemsToEnd * cellHeight + itemsToEnd - 1;
//fix height changed
int top = offset + animationSupportListView.getPaddingTop() - p * cellHeight - p;
int additionalHeight = 0;
if (hasStories) {
additionalHeight += AndroidUtilities.dp(DialogStoriesCell.HEIGHT_IN_DP);
} else if (hasTabs) {
additionalHeight += AndroidUtilities.dp(44);
}
if (oppened) {
bottom -= additionalHeight;
} else {
bottom += additionalHeight;
}
if (hasHidenArchive) {
top += cellHeight;
}
int paddingTop = animationSupportListView.getPaddingTop();
if (top > paddingTop) {
return offset + paddingTop - top;
}
// if (bottom < animationSupportListView.getMeasuredHeight()) {
// return offset + (animationSupportListView.getMeasuredHeight() - bottom);
// }
return offset;
}
int stableIdPointer = 10;
LongSparseIntArray dialogsStableIds = new LongSparseIntArray();
private class ItemInternal extends AdapterWithDiffUtils.Item {
TLRPC.Dialog dialog;
TLRPC.RecentMeUrl recentMeUrl;
TLRPC.TL_contact contact;
boolean isForumCell;
private boolean pinned;
private boolean isFolder;
TL_chatlists.TL_chatlists_chatlistUpdates chatlistUpdates;
private int emptyType;
public ItemInternal(TL_chatlists.TL_chatlists_chatlistUpdates updates) {
super(VIEW_TYPE_FOLDER_UPDATE_HINT, true);
this.chatlistUpdates = updates;
stableId = stableIdPointer++;
}
private final int stableId;
public ItemInternal(int viewType, TLRPC.Dialog dialog) {
super(viewType, true);
this.dialog = dialog;
if (dialog != null) {
int currentId = dialogsStableIds.get(dialog.id, -1);
if (currentId >= 0) {
stableId = currentId;
} else {
stableId = stableIdPointer++;
dialogsStableIds.put(dialog.id, stableId);
}
} else {
if (viewType == VIEW_TYPE_ARCHIVE_FULLSCREEN) {
stableId = 5;
} else {
stableId = stableIdPointer++;
}
}
if (dialog != null) {
if (dialogsType == 7 || dialogsType == 8) {
MessagesController.DialogFilter filter = MessagesController.getInstance(currentAccount).selectedDialogFilter[dialogsType == 8 ? 1 : 0];
pinned = filter != null && filter.pinnedDialogs.indexOfKey(dialog.id) >= 0;
} else {
pinned = dialog.pinned;
}
isFolder = dialog.isFolder;
isForumCell = MessagesController.getInstance(currentAccount).isForum(dialog.id);
}
}
public ItemInternal(int viewTypeMeUrl, TLRPC.RecentMeUrl recentMeUrl) {
super(viewTypeMeUrl, true);
this.recentMeUrl = recentMeUrl;
stableId = stableIdPointer++;
}
public ItemInternal(int viewTypeEmpty) {
super(viewTypeEmpty, true);
this.emptyType = viewTypeEmpty;
if (viewTypeEmpty == VIEW_TYPE_LAST_EMPTY) {
stableId = 1;
} else {
if (viewType == VIEW_TYPE_ARCHIVE_FULLSCREEN) {
stableId = 5;
} else {
stableId = stableIdPointer++;
}
}
}
public ItemInternal(int viewTypeEmpty, int emptyType) {
super(viewTypeEmpty, true);
this.emptyType = emptyType;
stableId = stableIdPointer++;
}
public ItemInternal(int viewTypeUser, TLRPC.TL_contact tl_contact) {
super(viewTypeUser, true);
contact = tl_contact;
if (contact != null) {
int currentId = dialogsStableIds.get(contact.user_id, -1);
if (currentId > 0) {
stableId = currentId;
} else {
stableId = stableIdPointer++;
dialogsStableIds.put(contact.user_id, stableId);
}
} else {
stableId = stableIdPointer++;
}
}
boolean compare(ItemInternal itemInternal) {
if (viewType != itemInternal.viewType) {
return false;
}
if (viewType == VIEW_TYPE_DIALOG) {
return dialog != null && itemInternal.dialog != null && dialog.id == itemInternal.dialog.id
&& isFolder == itemInternal.isFolder &&
isForumCell == itemInternal.isForumCell &&
pinned == itemInternal.pinned;
}
if (viewType == VIEW_TYPE_HEADER_2) {
return dialog != null && itemInternal.dialog != null && dialog.id == itemInternal.dialog.id && dialog.isFolder == itemInternal.dialog.isFolder;
}
if (viewType == VIEW_TYPE_ME_URL) {
return recentMeUrl != null && itemInternal.recentMeUrl != null && recentMeUrl.url != null && recentMeUrl.url.equals(recentMeUrl.url);
}
if (viewType == VIEW_TYPE_USER) {
return contact != null && itemInternal.contact != null && contact.user_id == itemInternal.contact.user_id;
}
if (viewType == VIEW_TYPE_EMPTY) {
return emptyType == itemInternal.emptyType;
}
if (viewType == VIEW_TYPE_LAST_EMPTY) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(dialog, recentMeUrl, contact);
}
}
public TLObject getItem(int i) {
if (i < 0 || i >= itemInternals.size()) {
return null;
}
if (itemInternals.get(i).dialog != null) {
return itemInternals.get(i).dialog;
} else if (itemInternals.get(i).contact != null) {
return MessagesController.getInstance(currentAccount).getUser(itemInternals.get(i).contact.user_id);
} else if (itemInternals.get(i).recentMeUrl != null) {
return itemInternals.get(i).recentMeUrl;
}
return null;
}
public void sortOnlineContacts(boolean notify) {
if (onlineContacts == null || notify && (SystemClock.elapsedRealtime() - lastSortTime) < 2000) {
return;
}
lastSortTime = SystemClock.elapsedRealtime();
try {
int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
MessagesController messagesController = MessagesController.getInstance(currentAccount);
Collections.sort(onlineContacts, (o1, o2) -> {
TLRPC.User user1 = messagesController.getUser(o2.user_id);
TLRPC.User user2 = messagesController.getUser(o1.user_id);
int status1 = 0;
int status2 = 0;
if (user1 != null) {
if (user1.self) {
status1 = currentTime + 50000;
} else if (user1.status != null) {
status1 = user1.status.expires;
}
}
if (user2 != null) {
if (user2.self) {
status2 = currentTime + 50000;
} else if (user2.status != null) {
status2 = user2.status.expires;
}
}
if (status1 > 0 && status2 > 0) {
if (status1 > status2) {
return 1;
} else if (status1 < status2) {
return -1;
}
return 0;
} else if (status1 < 0 && status2 < 0) {
if (status1 > status2) {
return 1;
} else if (status1 < status2) {
return -1;
}
return 0;
} else if (status1 < 0 && status2 > 0 || status1 == 0 && status2 != 0) {
return -1;
} else if (status2 < 0 || status1 != 0) {
return 1;
}
return 0;
});
if (notify) {
notifyDataSetChanged();
}
} catch (Exception e) {
FileLog.e(e);
}
}
public void setDialogsListFrozen(boolean frozen) {
dialogsListFrozen = frozen;
}
public boolean getDialogsListIsFrozen() {
return dialogsListFrozen;
}
public ViewPager getArchiveHintCellPager() {
return archiveHintCell != null ? archiveHintCell.getViewPager() : null;
}
public void updateHasHints() {
hasHints = folderId == 0 && dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT && !isOnlySelect && !MessagesController.getInstance(currentAccount).hintDialogs.isEmpty();
}
boolean isCalculatingDiff;
boolean updateListPending;
private final static boolean ALLOW_UPDATE_IN_BACKGROUND = BuildVars.DEBUG_PRIVATE_VERSION;
public void updateList(Runnable saveScrollPosition) {
if (isCalculatingDiff) {
updateListPending = true;
return;
}
isCalculatingDiff = true;
oldItems = new ArrayList<>();
oldItems.addAll(itemInternals);
updateItemList();
ArrayList<ItemInternal> newItems = new ArrayList<>(itemInternals);
itemInternals = oldItems;
DiffUtil.Callback callback = new DiffUtil.Callback() {
@Override
public int getOldListSize() {
return oldItems.size();
}
@Override
public int getNewListSize() {
return newItems.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldItems.get(oldItemPosition).compare(newItems.get(newItemPosition));
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldItems.get(oldItemPosition).viewType == newItems.get(newItemPosition).viewType;
}
};
if (itemInternals.size() < 50 || !ALLOW_UPDATE_IN_BACKGROUND) {
DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
isCalculatingDiff = false;
if (saveScrollPosition != null) {
saveScrollPosition.run();
}
itemInternals = newItems;
result.dispatchUpdatesTo(this);
} else {
Utilities.searchQueue.postRunnable(() -> {
DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
AndroidUtilities.runOnUIThread(() -> {
if (!isCalculatingDiff) {
return;
}
isCalculatingDiff = false;
if (saveScrollPosition != null) {
saveScrollPosition.run();
}
itemInternals = newItems;
result.dispatchUpdatesTo(this);
if (updateListPending) {
updateListPending = false;
updateList(saveScrollPosition);
}
});
});
}
}
@Override
public void notifyDataSetChanged() {
if (isCalculatingDiff) {
itemInternals = new ArrayList<>();
}
isCalculatingDiff = false;
updateItemList();
super.notifyDataSetChanged();
}
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
if (holder.itemView instanceof DialogCell) {
DialogCell dialogCell = (DialogCell) holder.itemView;
dialogCell.onReorderStateChanged(isReordering, false);
dialogCell.checkCurrentDialogIndex(dialogsListFrozen);
dialogCell.setChecked(selectedDialogs.contains(dialogCell.getDialogId()), false);
}
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
int viewType = holder.getItemViewType();
return viewType != VIEW_TYPE_FLICKER && viewType != VIEW_TYPE_EMPTY && viewType != VIEW_TYPE_DIVIDER &&
viewType != VIEW_TYPE_SHADOW && viewType != VIEW_TYPE_HEADER &&
viewType != VIEW_TYPE_LAST_EMPTY && viewType != VIEW_TYPE_NEW_CHAT_HINT && viewType != VIEW_TYPE_CONTACTS_FLICKER &&
viewType != VIEW_TYPE_REQUIREMENTS && viewType != VIEW_TYPE_REQUIRED_EMPTY && viewType != VIEW_TYPE_STORIES && viewType != VIEW_TYPE_ARCHIVE_FULLSCREEN;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view;
switch (viewType) {
case VIEW_TYPE_DIALOG:
if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO ||
dialogsType == DialogsActivity.DIALOGS_TYPE_BOT_REQUEST_PEER) {
view = new ProfileSearchCell(mContext);
} else {
DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount, null);
dialogCell.setArchivedPullAnimation(pullForegroundDrawable);
dialogCell.setPreloader(preloader);
dialogCell.setDialogCellDelegate(this);
dialogCell.setIsTransitionSupport(isTransitionSupport);
view = dialogCell;
}
if (dialogsType == DialogsActivity.DIALOGS_TYPE_BOT_REQUEST_PEER) {
view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
}
break;
case VIEW_TYPE_REQUIREMENTS:
view = new RequestPeerRequirementsCell(mContext);
break;
case VIEW_TYPE_FLICKER:
case VIEW_TYPE_CONTACTS_FLICKER:
FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext);
flickerLoadingView.setIsSingleCell(true);
int flickerType = viewType == VIEW_TYPE_CONTACTS_FLICKER ? FlickerLoadingView.CONTACT_TYPE : FlickerLoadingView.DIALOG_CELL_TYPE;
flickerLoadingView.setViewType(flickerType);
if (flickerType == FlickerLoadingView.CONTACT_TYPE) {
flickerLoadingView.setIgnoreHeightCheck(true);
}
if (viewType == VIEW_TYPE_CONTACTS_FLICKER) {
flickerLoadingView.setItemsCount((int) (AndroidUtilities.displaySize.y * 0.5f / AndroidUtilities.dp(64)));
}
view = flickerLoadingView;
break;
case VIEW_TYPE_RECENTLY_VIEWED: {
HeaderCell headerCell = new HeaderCell(mContext);
headerCell.setText(LocaleController.getString("RecentlyViewed", R.string.RecentlyViewed));
TextView textView = new TextView(mContext);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
textView.setText(LocaleController.getString("RecentlyViewedHide", R.string.RecentlyViewedHide));
textView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL);
headerCell.addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, 17, 15, 17, 0));
textView.setOnClickListener(view1 -> {
MessagesController.getInstance(currentAccount).hintDialogs.clear();
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
preferences.edit().remove("installReferer").commit();
notifyDataSetChanged();
});
view = headerCell;
break;
}
case VIEW_TYPE_DIVIDER:
FrameLayout frameLayout = new FrameLayout(mContext) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(12), MeasureSpec.EXACTLY));
}
};
frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
View v = new View(mContext);
v.setBackgroundDrawable(Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
frameLayout.addView(v, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
view = frameLayout;
break;
case VIEW_TYPE_ME_URL:
view = new DialogMeUrlCell(mContext);
break;
case VIEW_TYPE_EMPTY:
view = new DialogsEmptyCell(mContext);
break;
case VIEW_TYPE_REQUIRED_EMPTY:
view = new DialogsRequestedEmptyCell(mContext) {
@Override
protected void onButtonClick() {
onCreateGroupForThisClick();
}
};
break;
case VIEW_TYPE_USER:
view = new UserCell(mContext, 8, 0, false);
break;
case VIEW_TYPE_HEADER:
view = new HeaderCell(mContext);
view.setPadding(0, 0, 0, AndroidUtilities.dp(12));
break;
case VIEW_TYPE_HEADER_2:
HeaderCell cell = new HeaderCell(mContext, Theme.key_graySectionText, 16, 0, false);
cell.setHeight(32);
view = cell;
view.setClickable(false);
break;
case VIEW_TYPE_SHADOW: {
view = new ShadowSectionCell(mContext);
Drawable drawable = Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow);
CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable);
combinedDrawable.setFullsize(true);
view.setBackgroundDrawable(combinedDrawable);
break;
}
case VIEW_TYPE_ARCHIVE_FULLSCREEN:
LastEmptyView lastEmptyView = new LastEmptyView(mContext);
lastEmptyView.addView(
new ArchiveHelp(mContext, currentAccount, null, DialogsAdapter.this::onArchiveSettingsClick, null),
LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER, 0, -(int) (DialogStoriesCell.HEIGHT_IN_DP * .5f), 0, 0)
);
view = lastEmptyView;
break;
case VIEW_TYPE_LAST_EMPTY: {
view = new LastEmptyView(mContext);
break;
}
case VIEW_TYPE_NEW_CHAT_HINT: {
view = new TextInfoPrivacyCell(mContext) {
private int movement;
private float moveProgress;
private long lastUpdateTime;
private int originalX;
private int originalY;
@Override
protected void afterTextDraw() {
if (arrowDrawable != null) {
Rect bounds = arrowDrawable.getBounds();
arrowDrawable.setBounds(originalX, originalY, originalX + bounds.width(), originalY + bounds.height());
}
}
@Override
protected void onTextDraw() {
if (arrowDrawable != null) {
Rect bounds = arrowDrawable.getBounds();
int dx = (int) (moveProgress * AndroidUtilities.dp(3));
originalX = bounds.left;
originalY = bounds.top;
arrowDrawable.setBounds(originalX + dx, originalY + AndroidUtilities.dp(1), originalX + dx + bounds.width(), originalY + AndroidUtilities.dp(1) + bounds.height());
long newUpdateTime = SystemClock.elapsedRealtime();
long dt = newUpdateTime - lastUpdateTime;
if (dt > 17) {
dt = 17;
}
lastUpdateTime = newUpdateTime;
if (movement == 0) {
moveProgress += dt / 664.0f;
if (moveProgress >= 1.0f) {
movement = 1;
moveProgress = 1.0f;
}
} else {
moveProgress -= dt / 664.0f;
if (moveProgress <= 0.0f) {
movement = 0;
moveProgress = 0.0f;
}
}
getTextView().invalidate();
}
}
};
Drawable drawable = Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow);
CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable);
combinedDrawable.setFullsize(true);
view.setBackgroundDrawable(combinedDrawable);
break;
}
case VIEW_TYPE_FOLDER_UPDATE_HINT:
view = new DialogsHintCell(mContext);
break;
case VIEW_TYPE_STORIES: {
view = new View(mContext) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(DialogStoriesCell.HEIGHT_IN_DP), MeasureSpec.EXACTLY));
}
};
break;
}
case VIEW_TYPE_TEXT:
default: {
view = new TextCell(mContext);
if (dialogsType == DialogsActivity.DIALOGS_TYPE_BOT_REQUEST_PEER) {
view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
}
break;
}
}
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, viewType == VIEW_TYPE_EMPTY || viewType == VIEW_TYPE_ARCHIVE_FULLSCREEN ? RecyclerView.LayoutParams.MATCH_PARENT : RecyclerView.LayoutParams.WRAP_CONTENT));
return new RecyclerListView.Holder(view);
}
public void onCreateGroupForThisClick() {
}
protected void onArchiveSettingsClick() {
}
public int lastDialogsEmptyType = -1;
public int dialogsEmptyType() {
if (dialogsType == 7 || dialogsType == 8) {
if (MessagesController.getInstance(currentAccount).isDialogsEndReached(folderId)) {
return DialogsEmptyCell.TYPE_FILTER_NO_CHATS_TO_DISPLAY;
} else {
return DialogsEmptyCell.TYPE_FILTER_ADDING_CHATS;
}
} else if (folderId == 1) {
return DialogsEmptyCell.TYPE_FILTER_NO_CHATS_TO_DISPLAY;
} else {
return onlineContacts != null ? DialogsEmptyCell.TYPE_WELCOME_WITH_CONTACTS : DialogsEmptyCell.TYPE_WELCOME_NO_CONTACTS;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
switch (holder.getItemViewType()) {
case VIEW_TYPE_DIALOG: {
TLRPC.Dialog dialog = (TLRPC.Dialog) getItem(i);
TLRPC.Dialog nextDialog = (TLRPC.Dialog) getItem(i + 1);
if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO || dialogsType == DialogsActivity.DIALOGS_TYPE_BOT_REQUEST_PEER) {
ProfileSearchCell cell = (ProfileSearchCell) holder.itemView;
long oldDialogId = cell.getDialogId();
TLObject object = null;
TLRPC.Chat chat = null;
CharSequence title = null;
CharSequence subtitle;
boolean isRecent = false;
if (dialog.id != 0) {
chat = MessagesController.getInstance(currentAccount).getChat(-dialog.id);
if (chat != null && chat.migrated_to != null) {
TLRPC.Chat chat2 = MessagesController.getInstance(currentAccount).getChat(chat.migrated_to.channel_id);
if (chat2 != null) {
chat = chat2;
}
}
}
if (chat != null) {
object = chat;
title = chat.title;
if (ChatObject.isChannel(chat) && !chat.megagroup) {
if (chat.participants_count != 0) {
subtitle = LocaleController.formatPluralStringComma("Subscribers", chat.participants_count);
} else {
if (!ChatObject.isPublic(chat)) {
subtitle = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate).toLowerCase();
} else {
subtitle = LocaleController.getString("ChannelPublic", R.string.ChannelPublic).toLowerCase();
}
}
} else {
if (chat.participants_count != 0) {
subtitle = LocaleController.formatPluralStringComma("Members", chat.participants_count);
} else {
if (chat.has_geo) {
subtitle = LocaleController.getString("MegaLocation", R.string.MegaLocation);
} else if (!ChatObject.isPublic(chat)) {
subtitle = LocaleController.getString("MegaPrivate", R.string.MegaPrivate).toLowerCase();
} else {
subtitle = LocaleController.getString("MegaPublic", R.string.MegaPublic).toLowerCase();
}
}
}
} else {
subtitle = "";
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialog.id);
if (user != null) {
object = user;
title = UserObject.getUserName(user);
if (!UserObject.isReplyUser(user)) {
if (user.bot) {
subtitle = LocaleController.getString("Bot", R.string.Bot);
} else {
subtitle = LocaleController.formatUserStatus(currentAccount, user);
}
}
}
}
cell.useSeparator = nextDialog != null;
cell.setData(object, null, title, subtitle, isRecent, false);
cell.setChecked(selectedDialogs.contains(cell.getDialogId()), oldDialogId == cell.getDialogId());
} else {
DialogCell cell = (DialogCell) holder.itemView;
cell.useSeparator = nextDialog != null;
cell.fullSeparator = dialog.pinned && nextDialog != null && !nextDialog.pinned;
if (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT) {
if (AndroidUtilities.isTablet()) {
cell.setDialogSelected(dialog.id == openedDialogId);
}
}
cell.setChecked(selectedDialogs.contains(dialog.id), false);
cell.setDialog(dialog, dialogsType, folderId);
cell.checkHeight();
if (cell.collapsed != collapsedView) {
cell.collapsed = collapsedView;
cell.requestLayout();
}
if (preloader != null && i < 10) {
preloader.add(dialog.id);
}
}
break;
}
case VIEW_TYPE_EMPTY: {
DialogsEmptyCell cell = (DialogsEmptyCell) holder.itemView;
int fromDialogsEmptyType = lastDialogsEmptyType;
cell.setType(lastDialogsEmptyType = dialogsEmptyType(), isOnlySelect);
if (dialogsType != 7 && dialogsType != 8) {
cell.setOnUtyanAnimationEndListener(() -> parentFragment.setScrollDisabled(false));
cell.setOnUtyanAnimationUpdateListener(progress -> parentFragment.setContactsAlpha(progress));
if (!cell.isUtyanAnimationTriggered() && dialogsCount == 0) {
parentFragment.setContactsAlpha(0f);
parentFragment.setScrollDisabled(true);
}
if (onlineContacts != null && fromDialogsEmptyType == DialogsEmptyCell.TYPE_WELCOME_NO_CONTACTS) {
if (!cell.isUtyanAnimationTriggered()) {
cell.startUtyanCollapseAnimation(true);
}
} else if (forceUpdatingContacts) {
if (dialogsCount == 0) {
cell.startUtyanCollapseAnimation(false);
}
} else if (cell.isUtyanAnimationTriggered() && lastDialogsEmptyType == DialogsEmptyCell.TYPE_WELCOME_NO_CONTACTS) {
cell.startUtyanExpandAnimation();
}
}
break;
}
case VIEW_TYPE_REQUIRED_EMPTY: {
((DialogsRequestedEmptyCell) holder.itemView).set(requestPeerType);
break;
}
case VIEW_TYPE_ME_URL: {
DialogMeUrlCell cell = (DialogMeUrlCell) holder.itemView;
cell.setRecentMeUrl((TLRPC.RecentMeUrl) getItem(i));
break;
}
case VIEW_TYPE_USER: {
UserCell cell = (UserCell) holder.itemView;
TLRPC.User user = (TLRPC.User) getItem(i);
cell.setData(user, null, null, 0);
break;
}
case VIEW_TYPE_HEADER: {
HeaderCell cell = (HeaderCell) holder.itemView;
if (
dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_GROUPS ||
dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_USERS ||
dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY
) {
if (i == 0) {
cell.setText(LocaleController.getString("ImportHeader", R.string.ImportHeader));
} else {
cell.setText(LocaleController.getString("ImportHeaderContacts", R.string.ImportHeaderContacts));
}
} else {
cell.setText(LocaleController.getString(dialogsCount == 0 && forceUpdatingContacts ? R.string.ConnectingYourContacts : R.string.YourContacts));
}
break;
}
case VIEW_TYPE_HEADER_2: {
HeaderCell cell = (HeaderCell) holder.itemView;
cell.setTextSize(14);
cell.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText));
cell.setBackgroundColor(Theme.getColor(Theme.key_graySection));
switch (((DialogsActivity.DialogsHeader) getItem(i)).headerType) {
case DialogsActivity.DialogsHeader.HEADER_TYPE_MY_CHANNELS:
cell.setText(LocaleController.getString("MyChannels", R.string.MyChannels));
break;
case DialogsActivity.DialogsHeader.HEADER_TYPE_MY_GROUPS:
cell.setText(LocaleController.getString("MyGroups", R.string.MyGroups));
break;
case DialogsActivity.DialogsHeader.HEADER_TYPE_GROUPS:
cell.setText(LocaleController.getString("FilterGroups", R.string.FilterGroups));
break;
}
break;
}
case VIEW_TYPE_NEW_CHAT_HINT: {
TextInfoPrivacyCell cell = (TextInfoPrivacyCell) holder.itemView;
cell.setText(LocaleController.getString("TapOnThePencil", R.string.TapOnThePencil));
if (arrowDrawable == null) {
arrowDrawable = mContext.getResources().getDrawable(R.drawable.arrow_newchat);
arrowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4), PorterDuff.Mode.MULTIPLY));
}
TextView textView = cell.getTextView();
textView.setCompoundDrawablePadding(AndroidUtilities.dp(4));
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, parentFragment != null && parentFragment.storiesEnabled ? null : arrowDrawable, null);
textView.getLayoutParams().width = LayoutHelper.WRAP_CONTENT;
break;
}
case VIEW_TYPE_TEXT: {
if (!(holder.itemView instanceof TextCell)) {
return;
}
TextCell cell = (TextCell) holder.itemView;
cell.setColors(Theme.key_windowBackgroundWhiteBlueText4, Theme.key_windowBackgroundWhiteBlueText4);
if (requestPeerType != null) {
if (requestPeerType instanceof TLRPC.TL_requestPeerTypeBroadcast) {
cell.setTextAndIcon(LocaleController.getString("CreateChannelForThis", R.string.CreateChannelForThis), R.drawable.msg_channel_create, true);
} else {
cell.setTextAndIcon(LocaleController.getString("CreateGroupForThis", R.string.CreateGroupForThis), R.drawable.msg_groups_create, true);
}
} else {
cell.setTextAndIcon(LocaleController.getString("CreateGroupForImport", R.string.CreateGroupForImport), R.drawable.msg_groups_create, dialogsCount != 0);
}
cell.setIsInDialogs();
cell.setOffsetFromImage(75);
break;
}
case VIEW_TYPE_REQUIREMENTS: {
RequestPeerRequirementsCell cell = (RequestPeerRequirementsCell) holder.itemView;
cell.set(requestPeerType);
break;
}
case VIEW_TYPE_FOLDER_UPDATE_HINT: {
DialogsHintCell hintCell = (DialogsHintCell) holder.itemView;
ItemInternal item = itemInternals.get(i);
if (item.chatlistUpdates != null) {
int count = item.chatlistUpdates.missing_peers.size();
hintCell.setText(
AndroidUtilities.replaceSingleTag(
LocaleController.formatPluralString("FolderUpdatesTitle", count),
Theme.key_windowBackgroundWhiteValueText,
0,
null
),
LocaleController.formatPluralString("FolderUpdatesSubtitle", count)
);
}
break;
}
}
if (i >= dialogsCount + 1) {
holder.itemView.setAlpha(1f);
}
}
public TL_chatlists.TL_chatlists_chatlistUpdates getChatlistUpdate() {
ItemInternal item = itemInternals.get(0);
if (item != null && item.viewType == VIEW_TYPE_FOLDER_UPDATE_HINT) {
return item.chatlistUpdates;
}
return null;
}
public void setForceUpdatingContacts(boolean forceUpdatingContacts) {
this.forceUpdatingContacts = forceUpdatingContacts;
}
@Override
public int getItemViewType(int i) {
return itemInternals.get(i).viewType;
}
public void moveDialogs(RecyclerListView recyclerView, int fromPosition, int toPosition) {
ArrayList<TLRPC.Dialog> dialogs = parentFragment.getDialogsArray(currentAccount, dialogsType, folderId, false);
int fromIndex = fixPosition(fromPosition);
int toIndex = fixPosition(toPosition);
TLRPC.Dialog fromDialog = dialogs.get(fromIndex);
TLRPC.Dialog toDialog = dialogs.get(toIndex);
if (dialogsType == 7 || dialogsType == 8) {
MessagesController.DialogFilter filter = MessagesController.getInstance(currentAccount).selectedDialogFilter[dialogsType == 8 ? 1 : 0];
int idx1 = filter.pinnedDialogs.get(fromDialog.id);
int idx2 = filter.pinnedDialogs.get(toDialog.id);
filter.pinnedDialogs.put(fromDialog.id, idx2);
filter.pinnedDialogs.put(toDialog.id, idx1);
} else {
int oldNum = fromDialog.pinnedNum;
fromDialog.pinnedNum = toDialog.pinnedNum;
toDialog.pinnedNum = oldNum;
}
Collections.swap(dialogs, fromIndex, toIndex);
updateList(null);
}
@Override
public void notifyItemMoved(int fromPosition, int toPosition) {
super.notifyItemMoved(fromPosition, toPosition);
}
public void setArchivedPullDrawable(PullForegroundDrawable drawable) {
pullForegroundDrawable = drawable;
}
public void didDatabaseCleared() {
if (preloader != null) {
preloader.clear();
}
}
public void resume() {
if (preloader != null) {
preloader.resume();
}
}
public void pause() {
if (preloader != null) {
preloader.pause();
}
}
@Override
public void onButtonClicked(DialogCell dialogCell) {
}
@Override
public void onButtonLongPress(DialogCell dialogCell) {
}
@Override
public boolean canClickButtonInside() {
return selectedDialogs.isEmpty();
}
@Override
public void openStory(DialogCell dialogCell, Runnable onDone) {
MessagesController messagesController = MessagesController.getInstance(currentAccount);
if (MessagesController.getInstance(currentAccount).getStoriesController().hasStories(dialogCell.getDialogId())) {
parentFragment.getOrCreateStoryViewer().doOnAnimationReady(onDone);
parentFragment.getOrCreateStoryViewer().open(parentFragment.getContext(), dialogCell.getDialogId(), StoriesListPlaceProvider.of((RecyclerListView) dialogCell.getParent()));
return;
}
}
@Override
public void showChatPreview(DialogCell cell) {
parentFragment.showChatPreview(cell);
}
@Override
public void openHiddenStories() {
StoriesController storiesController = MessagesController.getInstance(currentAccount).getStoriesController();
if (storiesController.getHiddenList().isEmpty()) {
return;
}
boolean unreadOnly = storiesController.getUnreadState(DialogObject.getPeerDialogId(storiesController.getHiddenList().get(0).peer)) != StoriesController.STATE_READ;
ArrayList<Long> peerIds = new ArrayList<>();
for (int i = 0; i < storiesController.getHiddenList().size(); i++) {
long dialogId = DialogObject.getPeerDialogId(storiesController.getHiddenList().get(i).peer);
if (!unreadOnly || storiesController.getUnreadState(dialogId) != StoriesController.STATE_READ) {
peerIds.add(dialogId);
}
}
parentFragment.getOrCreateStoryViewer().open(mContext, null, peerIds, 0, null, null, StoriesListPlaceProvider.of(recyclerListView, true), false);
}
public void setIsTransitionSupport() {
this.isTransitionSupport = true;
}
public void setCollapsedView(boolean collapsedView, RecyclerListView listView) {
this.collapsedView = collapsedView;
for (int i = 0; i < listView.getChildCount(); i++) {
if (listView.getChildAt(i) instanceof DialogCell) {
((DialogCell) listView.getChildAt(i)).collapsed = collapsedView;
}
}
for (int i = 0; i < listView.getCachedChildCount(); i++) {
if (listView.getCachedChildAt(i) instanceof DialogCell) {
((DialogCell) listView.getCachedChildAt(i)).collapsed = collapsedView;
}
}
for (int i = 0; i < listView.getHiddenChildCount(); i++) {
if (listView.getHiddenChildAt(i) instanceof DialogCell) {
((DialogCell) listView.getHiddenChildAt(i)).collapsed = collapsedView;
}
}
for (int i = 0; i < listView.getAttachedScrapChildCount(); i++) {
if (listView.getAttachedScrapChildAt(i) instanceof DialogCell) {
((DialogCell) listView.getAttachedScrapChildAt(i)).collapsed = collapsedView;
}
}
}
public static class DialogsPreloader {
private final int MAX_REQUEST_COUNT = 4;
private final int MAX_NETWORK_REQUEST_COUNT = 10 - MAX_REQUEST_COUNT;
private final int NETWORK_REQUESTS_RESET_TIME = 60_000;
HashSet<Long> dialogsReadyMap = new HashSet<>();
HashSet<Long> preloadedErrorMap = new HashSet<>();
HashSet<Long> loadingDialogs = new HashSet<>();
ArrayList<Long> preloadDialogsPool = new ArrayList<>();
int currentRequestCount;
int networkRequestCount;
boolean resumed;
Runnable clearNetworkRequestCount = () -> {
networkRequestCount = 0;
start();
};
public void add(long dialog_id) {
if (isReady(dialog_id) || preloadedErrorMap.contains(dialog_id) || loadingDialogs.contains(dialog_id) || preloadDialogsPool.contains(dialog_id)) {
return;
}
preloadDialogsPool.add(dialog_id);
start();
}
private void start() {
if (!preloadIsAvilable() || !resumed || preloadDialogsPool.isEmpty() || currentRequestCount >= MAX_REQUEST_COUNT || networkRequestCount > MAX_NETWORK_REQUEST_COUNT) {
return;
}
long dialog_id = preloadDialogsPool.remove(0);
currentRequestCount++;
loadingDialogs.add(dialog_id);
MessagesController.getInstance(UserConfig.selectedAccount).ensureMessagesLoaded(dialog_id, 0, new MessagesController.MessagesLoadedCallback() {
@Override
public void onMessagesLoaded(boolean fromCache) {
AndroidUtilities.runOnUIThread(() -> {
if (!fromCache) {
networkRequestCount++;
if (networkRequestCount >= MAX_NETWORK_REQUEST_COUNT) {
AndroidUtilities.cancelRunOnUIThread(clearNetworkRequestCount);
AndroidUtilities.runOnUIThread(clearNetworkRequestCount, NETWORK_REQUESTS_RESET_TIME);
}
}
if (loadingDialogs.remove(dialog_id)) {
dialogsReadyMap.add(dialog_id);
updateList();
currentRequestCount--;
start();
}
});
}
@Override
public void onError() {
AndroidUtilities.runOnUIThread(() -> {
if (loadingDialogs.remove(dialog_id)) {
preloadedErrorMap.add(dialog_id);
currentRequestCount--;
start();
}
});
}
});
}
private boolean preloadIsAvilable() {
return false;
// return DownloadController.getInstance(UserConfig.selectedAccount).getCurrentDownloadMask() != 0;
}
public void updateList() {
}
public boolean isReady(long currentDialogId) {
return dialogsReadyMap.contains(currentDialogId);
}
public boolean preloadedError(long currendDialogId) {
return preloadedErrorMap.contains(currendDialogId);
}
public void remove(long currentDialogId) {
preloadDialogsPool.remove(currentDialogId);
}
public void clear() {
dialogsReadyMap.clear();
preloadedErrorMap.clear();
loadingDialogs.clear();
preloadDialogsPool.clear();
currentRequestCount = 0;
networkRequestCount = 0;
AndroidUtilities.cancelRunOnUIThread(clearNetworkRequestCount);
updateList();
}
public void resume() {
resumed = true;
start();
}
public void pause() {
resumed = false;
}
}
public int getCurrentCount() {
return currentCount;
}
public void setForceShowEmptyCell(boolean forceShowEmptyCell) {
this.forceShowEmptyCell = forceShowEmptyCell;
}
public class LastEmptyView extends FrameLayout {
public boolean moving;
public LastEmptyView(Context context) {
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int size = itemInternals.size();
boolean hasArchive = folderId == 0 && dialogsType == 0 && MessagesController.getInstance(currentAccount).dialogs_dict.get(DialogObject.makeFolderDialogId(1)) != null;
View parent = (View) getParent();
int height;
int blurOffset = 0;
if (parent instanceof BlurredRecyclerView) {
blurOffset = ((BlurredRecyclerView) parent).blurTopPadding;
}
boolean collapsedView = DialogsAdapter.this.collapsedView;
int paddingTop = parent.getPaddingTop();
paddingTop -= blurOffset;
if (folderId == 1 && size == 1 && itemInternals.get(0).viewType == VIEW_TYPE_ARCHIVE_FULLSCREEN) {
height = MeasureSpec.getSize(heightMeasureSpec);
if (height == 0) {
height = parent.getMeasuredHeight();
}
if (height == 0) {
height = AndroidUtilities.displaySize.y - ActionBar.getCurrentActionBarHeight() - (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
}
if (parentFragment.hasStories) {
height += AndroidUtilities.dp(DialogStoriesCell.HEIGHT_IN_DP);
}
} else if (size == 0 || paddingTop == 0 && !hasArchive) {
height = 0;
} else {
height = MeasureSpec.getSize(heightMeasureSpec);
if (height == 0) {
height = parent.getMeasuredHeight();
}
if (height == 0) {
height = AndroidUtilities.displaySize.y - ActionBar.getCurrentActionBarHeight() - (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
}
height -= blurOffset;
int cellHeight = AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 78 : 72);
int dialogsHeight = 0;
for (int i = 0; i < size; i++) {
if (itemInternals.get(i).viewType == VIEW_TYPE_DIALOG) {
if (itemInternals.get(i).isForumCell && !collapsedView) {
dialogsHeight += AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 86 : 91);
} else {
dialogsHeight += cellHeight;
}
} else if (itemInternals.get(i).viewType == VIEW_TYPE_FLICKER) {
dialogsHeight += cellHeight;
}
}
dialogsHeight += size - 1;
if (onlineContacts != null) {
dialogsHeight += onlineContacts.size() * AndroidUtilities.dp(58) + (onlineContacts.size() - 1) + AndroidUtilities.dp(52);
}
int archiveHeight = (hasArchive ? cellHeight + 1 : 0);
if (dialogsHeight < height) {
height = height - dialogsHeight + archiveHeight;
if (paddingTop != 0) {
height -= AndroidUtilities.statusBarHeight;
if (parentFragment.hasStories && !collapsedView && !isTransitionSupport) {
height -= ActionBar.getCurrentActionBarHeight();
if (getParent() instanceof DialogsActivity.DialogsRecyclerView) {
DialogsActivity.DialogsRecyclerView dialogsRecyclerView = (DialogsActivity.DialogsRecyclerView) getParent();
height -= dialogsRecyclerView.additionalPadding;
}
} else if (collapsedView) {
height -= paddingTop;
}
}
} else if (dialogsHeight - height < archiveHeight) {
height = archiveHeight - (dialogsHeight - height);
if (paddingTop != 0) {
height -= AndroidUtilities.statusBarHeight;
if (parentFragment.hasStories && !collapsedView && !isTransitionSupport) {
height -= ActionBar.getCurrentActionBarHeight();
if (getParent() instanceof DialogsActivity.DialogsRecyclerView) {
DialogsActivity.DialogsRecyclerView dialogsRecyclerView = (DialogsActivity.DialogsRecyclerView) getParent();
height -= dialogsRecyclerView.additionalPadding;
}
} else if (collapsedView) {
height -= paddingTop;
}
}
} else {
height = 0;
}
}
if (height < 0) {
height = 0;
}
if (isTransitionSupport) {
height += AndroidUtilities.dp(1000);
}
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
private void updateItemList() {
itemInternals.clear();
updateHasHints();
MessagesController messagesController = MessagesController.getInstance(currentAccount);
ArrayList<TLRPC.Dialog> array = parentFragment.getDialogsArray(currentAccount, dialogsType, folderId, dialogsListFrozen);
if (array == null) {
array = new ArrayList<>();
}
dialogsCount = array.size();
isEmpty = false;
if (dialogsCount == 0 && parentFragment.isArchive()) {
itemInternals.add(new ItemInternal(VIEW_TYPE_ARCHIVE_FULLSCREEN));
return;
}
if (!hasHints && dialogsType == 0 && folderId == 0 && messagesController.isDialogsEndReached(folderId) && !forceUpdatingContacts) {
if (messagesController.getAllFoldersDialogsCount() <= 10 && ContactsController.getInstance(currentAccount).doneLoadingContacts && !ContactsController.getInstance(currentAccount).contacts.isEmpty()) {
onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts);
long selfId = UserConfig.getInstance(currentAccount).clientUserId;
for (int a = 0, N = onlineContacts.size(); a < N; a++) {
long userId = onlineContacts.get(a).user_id;
if (userId == selfId || messagesController.dialogs_dict.get(userId) != null) {
onlineContacts.remove(a);
a--;
N--;
}
}
if (onlineContacts.isEmpty()) {
onlineContacts = null;
} else {
sortOnlineContacts(false);
}
} else {
onlineContacts = null;
}
}
hasChatlistHint = false;
if (dialogsType == 7 || dialogsType == 8) {
MessagesController.DialogFilter filter = messagesController.selectedDialogFilter[dialogsType - 7];
if (filter != null && filter.isChatlist()) {
messagesController.checkChatlistFolderUpdate(filter.id, false);
TL_chatlists.TL_chatlists_chatlistUpdates updates = messagesController.getChatlistFolderUpdates(filter.id);
if (updates != null && updates.missing_peers.size() > 0) {
hasChatlistHint = true;
itemInternals.add(new ItemInternal(updates));
}
}
}
if (requestPeerType != null) {
itemInternals.add(new ItemInternal(VIEW_TYPE_REQUIREMENTS));
}
if (collapsedView || isTransitionSupport) {
for (int k = 0; k < array.size(); k++) {
if (dialogsType == 2 && array.get(k) instanceof DialogsActivity.DialogsHeader) {
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER_2, array.get(k)));
} else {
itemInternals.add(new ItemInternal(VIEW_TYPE_DIALOG, array.get(k)));
}
}
itemInternals.add(new ItemInternal(VIEW_TYPE_LAST_EMPTY));
return;
}
boolean stopUpdate = false;
if (dialogsCount == 0 && forceUpdatingContacts) {
isEmpty = true;
if (requestPeerType != null) {
itemInternals.add(new ItemInternal(VIEW_TYPE_REQUIRED_EMPTY));
} else {
itemInternals.add(new ItemInternal(VIEW_TYPE_EMPTY, dialogsEmptyType()));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_SHADOW));
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER));
itemInternals.add(new ItemInternal(VIEW_TYPE_CONTACTS_FLICKER));
} else if (onlineContacts != null && !onlineContacts.isEmpty() && dialogsType != 7 && dialogsType != 8) {
if (dialogsCount == 0) {
isEmpty = true;
if (requestPeerType != null) {
itemInternals.add(new ItemInternal(VIEW_TYPE_REQUIRED_EMPTY));
} else {
itemInternals.add(new ItemInternal(VIEW_TYPE_EMPTY, dialogsEmptyType()));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_SHADOW));
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER));
} else {
for (int k = 0; k < array.size(); k++) {
itemInternals.add(new ItemInternal(VIEW_TYPE_DIALOG, array.get(k)));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_SHADOW));
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER));
}
for (int k = 0; k < onlineContacts.size(); k++) {
itemInternals.add(new ItemInternal(VIEW_TYPE_USER, onlineContacts.get(k)));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_LAST_EMPTY));
stopUpdate = true;
} else if (hasHints) {
int count = MessagesController.getInstance(currentAccount).hintDialogs.size();
itemInternals.add(new ItemInternal(VIEW_TYPE_RECENTLY_VIEWED));
for (int k = 0; k < count; k++) {
itemInternals.add(new ItemInternal(VIEW_TYPE_ME_URL, MessagesController.getInstance(currentAccount).hintDialogs.get(k)));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_DIVIDER));
} else if (dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_GROUPS || dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY) {
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER));
itemInternals.add(new ItemInternal(VIEW_TYPE_TEXT));
} else if (dialogsType == DialogsActivity.DIALOGS_TYPE_IMPORT_HISTORY_USERS) {
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER));
}
if ((requestPeerType instanceof TLRPC.TL_requestPeerTypeBroadcast || requestPeerType instanceof TLRPC.TL_requestPeerTypeChat) && dialogsCount > 0) {
itemInternals.add(new ItemInternal(VIEW_TYPE_TEXT));
}
if (!stopUpdate) {
for (int k = 0; k < array.size(); k++) {
if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO && array.get(k) instanceof DialogsActivity.DialogsHeader) {
itemInternals.add(new ItemInternal(VIEW_TYPE_HEADER_2, array.get(k)));
} else {
itemInternals.add(new ItemInternal(VIEW_TYPE_DIALOG, array.get(k)));
}
}
if (!forceShowEmptyCell && dialogsType != 7 && dialogsType != 8 && !MessagesController.getInstance(currentAccount).isDialogsEndReached(folderId)) {
if (dialogsCount != 0) {
itemInternals.add(new ItemInternal(VIEW_TYPE_FLICKER));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_LAST_EMPTY));
} else if (dialogsCount == 0) {
isEmpty = true;
if (requestPeerType != null) {
itemInternals.add(new ItemInternal(VIEW_TYPE_REQUIRED_EMPTY));
} else {
itemInternals.add(new ItemInternal(VIEW_TYPE_EMPTY, dialogsEmptyType()));
}
} else {
if (folderId == 0 && dialogsCount > 10 && dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT) {
itemInternals.add(new ItemInternal(VIEW_TYPE_NEW_CHAT_HINT));
}
itemInternals.add(new ItemInternal(VIEW_TYPE_LAST_EMPTY));
}
}
if (!messagesController.hiddenUndoChats.isEmpty()) {
for (int i = 0; i < itemInternals.size(); ++i) {
ItemInternal item = itemInternals.get(i);
if (item.viewType == VIEW_TYPE_DIALOG && item.dialog != null && messagesController.isHiddenByUndo(item.dialog.id)) {
itemInternals.remove(i);
i--;
}
}
}
}
public int getItemHeight(int position) {
int cellHeight = AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 78 : 72);
if (itemInternals.get(position).viewType == VIEW_TYPE_DIALOG) {
if (itemInternals.get(position).isForumCell && !collapsedView) {
return AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 86 : 91);
} else {
return cellHeight;
}
}
return 0;
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsAdapter.java |
45,289 | package org.telegram.ui.Components;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.core.graphics.ColorUtils;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.XiaomiUtilities;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.AdjustPanLayoutHelper;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.FloatingToolbar;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.Premium.PremiumFeatureBottomSheet;
import org.telegram.ui.PremiumPreviewFragment;
public class EditTextEmoji extends FrameLayout implements NotificationCenter.NotificationCenterDelegate, SizeNotifierFrameLayout.SizeNotifierFrameLayoutDelegate {
private EditTextCaption editText;
private ImageView emojiButton;
private ReplaceableIconDrawable emojiIconDrawable;
private EmojiView emojiView;
private boolean emojiViewVisible;
private SizeNotifierFrameLayout sizeNotifierLayout;
private BaseFragment parentFragment;
private ItemOptions formatOptions;
private boolean shownFormatButton;
private int keyboardHeight;
private int keyboardHeightLand;
private boolean keyboardVisible;
private int emojiPadding;
private boolean destroyed;
private boolean isPaused = true;
private boolean showKeyboardOnResume;
private int lastSizeChangeValue1;
private boolean lastSizeChangeValue2;
private int innerTextChange;
private boolean allowAnimatedEmoji;
public boolean includeNavigationBar;
AdjustPanLayoutHelper adjustPanLayoutHelper;
private EditTextEmojiDelegate delegate;
private int currentStyle;
private final Theme.ResourcesProvider resourcesProvider;
public static final int STYLE_FRAGMENT = 0;
public static final int STYLE_DIALOG = 1;
public static final int STYLE_STORY = 2;
public static final int STYLE_PHOTOVIEWER = 3;
private boolean waitingForKeyboardOpen;
private boolean isAnimatePopupClosing;
private Runnable openKeyboardRunnable = new Runnable() {
@Override
public void run() {
if (!destroyed && editText != null && waitingForKeyboardOpen && !keyboardVisible && !AndroidUtilities.usingHardwareInput && !AndroidUtilities.isInMultiwindow && AndroidUtilities.isTablet()) {
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
AndroidUtilities.cancelRunOnUIThread(openKeyboardRunnable);
AndroidUtilities.runOnUIThread(openKeyboardRunnable, 100);
}
}
};
public boolean isPopupVisible() {
return emojiView != null && emojiView.getVisibility() == View.VISIBLE;
}
public boolean isWaitingForKeyboardOpen() {
return waitingForKeyboardOpen;
}
public boolean isAnimatePopupClosing() {
return isAnimatePopupClosing;
}
public void setAdjustPanLayoutHelper(AdjustPanLayoutHelper adjustPanLayoutHelper) {
this.adjustPanLayoutHelper = adjustPanLayoutHelper;
}
public interface EditTextEmojiDelegate {
void onWindowSizeChanged(int size);
}
public EditTextEmoji(Context context, SizeNotifierFrameLayout parent, BaseFragment fragment, int style, boolean allowAnimatedEmoji) {
this(context, parent, fragment, style, allowAnimatedEmoji, null);
}
public EditTextEmoji(Context context, SizeNotifierFrameLayout parent, BaseFragment fragment, int style, boolean allowAnimatedEmoji, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.allowAnimatedEmoji = allowAnimatedEmoji;
this.resourcesProvider = resourcesProvider;
currentStyle = style;
NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded);
parentFragment = fragment;
sizeNotifierLayout = parent;
sizeNotifierLayout.setDelegate(this);
editText = new EditTextCaption(context, resourcesProvider) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isPopupShowing() && event.getAction() == MotionEvent.ACTION_DOWN) {
onWaitingForKeyboard();
showPopup(AndroidUtilities.usingHardwareInput ? 0 : 2);
openKeyboardInternal();
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
requestFocus();
if (!AndroidUtilities.showKeyboard(this)) {
clearFocus();
requestFocus();
}
}
try {
return super.onTouchEvent(event);
} catch (Exception e) {
FileLog.e(e);
}
return false;
}
@Override
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
EditTextEmoji.this.onLineCountChanged(oldLineCount, newLineCount);
}
@Override
protected int getActionModeStyle() {
if (style == STYLE_STORY || style == STYLE_PHOTOVIEWER) {
return FloatingToolbar.STYLE_BLACK;
}
return super.getActionModeStyle();
}
@Override
protected void extendActionMode(ActionMode actionMode, Menu menu) {
if (allowEntities()) {
ChatActivity.fillActionModeMenu(menu, null, currentStyle == STYLE_PHOTOVIEWER);
}
super.extendActionMode(actionMode, menu);
}
@Override
public void scrollTo(int x, int y) {
if (EditTextEmoji.this.onScrollYChange(y)) {
super.scrollTo(x, y);
}
}
private Drawable lastIcon = null;
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
if (emojiIconDrawable != null) {
boolean selected = selEnd != selStart;
boolean showFormat = allowEntities() && selected && (XiaomiUtilities.isMIUI() || true);
if (shownFormatButton != showFormat) {
shownFormatButton = showFormat;
if (showFormat) {
lastIcon = emojiIconDrawable.getIcon();
emojiIconDrawable.setIcon(R.drawable.msg_edit, true);
} else {
emojiIconDrawable.setIcon(lastIcon, true);
lastIcon = null;
}
}
}
}
};
editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
editText.setInputType(editText.getInputType() | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
editText.setFocusable(editText.isEnabled());
editText.setCursorSize(AndroidUtilities.dp(20));
editText.setCursorWidth(1.5f);
editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
if (style == STYLE_FRAGMENT) {
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
editText.setMaxLines(4);
editText.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT));
editText.setBackground(null);
editText.setLineColors(getThemedColor(Theme.key_windowBackgroundWhiteInputField), getThemedColor(Theme.key_windowBackgroundWhiteInputFieldActivated), getThemedColor(Theme.key_text_RedRegular));
editText.setHintTextColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText));
editText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
editText.setHandlesColor(getThemedColor(Theme.key_chat_TextSelectionCursor));
editText.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), AndroidUtilities.dp(11));
addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 11 : 0, 1, LocaleController.isRTL ? 0 : 11, 0));
} else if (style == STYLE_STORY || style == STYLE_PHOTOVIEWER) {
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
editText.setMaxLines(8);
editText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
editText.setAllowTextEntitiesIntersection(true);
editText.setHintTextColor(0x8cffffff);
editText.setTextColor(0xffffffff);
editText.setCursorColor(0xffffffff);
editText.setBackground(null);
editText.setClipToPadding(false);
editText.setPadding(0, AndroidUtilities.dp(9), 0, AndroidUtilities.dp(9));
editText.setHandlesColor(0xffffffff);
editText.setHighlightColor(0x30ffffff);
editText.setLinkTextColor(0xFF46A3EB);
editText.quoteColor = 0xffffffff;
editText.setTextIsSelectable(true);
setClipChildren(false);
setClipToPadding(false);
addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 40, 0, 24, 0));
} else {
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
editText.setMaxLines(4);
editText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
editText.setHintTextColor(getThemedColor(Theme.key_dialogTextHint));
editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
editText.setBackground(null);
editText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12));
addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 48, 0, 0, 0));
}
emojiButton = new ImageView(context) {
@Override
protected void dispatchDraw(Canvas canvas) {
if (!customEmojiButtonDraw(canvas, emojiButton, emojiIconDrawable)) {
super.dispatchDraw(canvas);
}
}
};
emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
emojiButton.setImageDrawable(emojiIconDrawable = new ReplaceableIconDrawable(context));
if (style == STYLE_FRAGMENT) {
emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
emojiIconDrawable.setIcon(R.drawable.smiles_tab_smiles, false);
addView(emojiButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT), 0, 0, 0, 5));
} else if (style == STYLE_STORY || style == STYLE_PHOTOVIEWER) {
emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(0x8cffffff, PorterDuff.Mode.MULTIPLY));
emojiIconDrawable.setIcon(R.drawable.input_smile, false);
addView(emojiButton, LayoutHelper.createFrame(40, 40, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 0));
} else {
emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
emojiIconDrawable.setIcon(R.drawable.input_smile, false);
addView(emojiButton, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 0));
}
if (Build.VERSION.SDK_INT >= 21) {
emojiButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector)));
}
emojiButton.setOnClickListener(view -> {
if (!emojiButton.isEnabled() || emojiButton.getAlpha() < 0.5f || (adjustPanLayoutHelper != null && adjustPanLayoutHelper.animationInProgress())) {
return;
}
if (shownFormatButton) {
if (formatOptions == null) {
editText.hideActionMode();
ItemOptions itemOptions = ItemOptions.makeOptions(parent, resourcesProvider, emojiButton);
itemOptions.setMaxHeight(AndroidUtilities.dp(280));
editText.extendActionMode(null, new MenuToItemOptions(itemOptions, editText::performMenuAction, editText.getOnPremiumMenuLockClickListener()));
itemOptions.forceTop(true);
itemOptions.show();
} else {
formatOptions.dismiss();
formatOptions = null;
}
} else if (!isPopupShowing()) {
showPopup(1);
emojiView.onOpen(editText.length() > 0, false);
editText.requestFocus();
} else {
openKeyboardInternal();
}
});
emojiButton.setContentDescription(LocaleController.getString("Emoji", R.string.Emoji));
}
protected boolean allowEntities() {
return currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER;
}
public void setSuggestionsEnabled(boolean enabled) {
int inputType = editText.getInputType();
if (!enabled) {
inputType |= EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
} else {
inputType &= ~EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
}
if (editText.getInputType() != inputType) {
editText.setInputType(inputType);
}
}
protected boolean onScrollYChange(int scrollY) {
return true;
}
protected boolean customEmojiButtonDraw(Canvas canvas, View button, Drawable drawable) {
return false;
}
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
}
public void setSizeNotifierLayout(SizeNotifierFrameLayout layout) {
sizeNotifierLayout = layout;
sizeNotifierLayout.setDelegate(this);
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.emojiLoaded) {
if (emojiView != null) {
emojiView.invalidateViews();
}
if (editText != null) {
int color = editText.getCurrentTextColor();
editText.setTextColor(0xffffffff);
editText.setTextColor(color);
}
}
}
@Override
public void setEnabled(boolean enabled) {
editText.setEnabled(enabled);
emojiButton.setVisibility(enabled ? VISIBLE : GONE);
int bottomPadding = AndroidUtilities.dp(currentStyle == STYLE_FRAGMENT ? 11 : 8);
if (enabled) {
editText.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), bottomPadding);
} else {
editText.setPadding(0, 0, 0, bottomPadding);
}
}
@Override
public void setFocusable(boolean focusable) {
editText.setFocusable(focusable);
}
public void hideEmojiView() {
if (!emojiViewVisible && emojiView != null && emojiView.getVisibility() != GONE) {
emojiView.setVisibility(GONE);
}
emojiPadding = 0;
}
public EmojiView getEmojiView() {
return emojiView;
}
public void setDelegate(EditTextEmojiDelegate editTextEmojiDelegate) {
delegate = editTextEmojiDelegate;
}
public void onPause() {
isPaused = true;
closeKeyboard();
}
public void onResume() {
isPaused = false;
if (showKeyboardOnResume) {
showKeyboardOnResume = false;
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
if (!AndroidUtilities.usingHardwareInput && !keyboardVisible && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet()) {
waitingForKeyboardOpen = true;
onWaitingForKeyboard();
AndroidUtilities.cancelRunOnUIThread(openKeyboardRunnable);
AndroidUtilities.runOnUIThread(openKeyboardRunnable, 100);
}
}
}
public void onDestroy() {
destroyed = true;
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded);
if (emojiView != null) {
emojiView.onDestroy();
}
if (sizeNotifierLayout != null) {
sizeNotifierLayout.setDelegate(null);
}
}
public void updateColors() {
if (currentStyle == STYLE_FRAGMENT) {
editText.setHintTextColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText));
editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
editText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
} else if (currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER) {
editText.setHintTextColor(0x8cffffff);
editText.setTextColor(0xffffffff);
editText.setCursorColor(0xffffffff);
editText.setHandlesColor(0xffffffff);
editText.setHighlightColor(0x30ffffff);
editText.quoteColor = 0xffffffff;
} else {
editText.setHintTextColor(getThemedColor(Theme.key_dialogTextHint));
editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
}
emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
if (emojiView != null) {
emojiView.updateColors();
}
}
public void setMaxLines(int value) {
editText.setMaxLines(value);
}
public int length() {
return editText.length();
}
public void setFilters(InputFilter[] filters) {
editText.setFilters(filters);
}
public Editable getText() {
return editText.getText();
}
public void setHint(CharSequence hint) {
editText.setHint(hint);
}
public void setText(CharSequence text) {
editText.setText(text);
}
public void setSelection(int selection) {
editText.setSelection(selection);
}
public void setSelection(int from, int to) {
editText.setSelection(from, to);
}
public void hidePopup(boolean byBackButton) {
if (isPopupShowing()) {
showPopup(0);
}
if (byBackButton) {
if (emojiView != null && emojiView.getVisibility() == View.VISIBLE && !waitingForKeyboardOpen) {
int height = emojiView.getMeasuredHeight();
if (emojiView.getParent() instanceof ViewGroup) {
height += ((ViewGroup) emojiView.getParent()).getHeight() - emojiView.getBottom();
}
final int finalHeight = height;
ValueAnimator animator = ValueAnimator.ofFloat(0, finalHeight);
animator.addUpdateListener(animation -> {
float v = (float) animation.getAnimatedValue();
emojiView.setTranslationY(v);
if (finalHeight > 0 && (currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER)) {
emojiView.setAlpha(1f - v / (float) finalHeight);
}
bottomPanelTranslationY(v - finalHeight);
});
isAnimatePopupClosing = true;
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isAnimatePopupClosing = false;
emojiView.setTranslationY(0);
emojiView.setAlpha(0);
bottomPanelTranslationY(0);
hideEmojiView();
}
});
animator.setDuration(AdjustPanLayoutHelper.keyboardDuration);
animator.setInterpolator(AdjustPanLayoutHelper.keyboardInterpolator);
animator.start();
} else {
hideEmojiView();
}
}
}
protected void bottomPanelTranslationY(float translation) {
}
public void openKeyboard() {
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
}
public void closeKeyboard() {
AndroidUtilities.hideKeyboard(editText);
}
public boolean isPopupShowing() {
return emojiViewVisible;
}
public boolean isKeyboardVisible() {
return keyboardVisible;
}
protected void openKeyboardInternal() {
onWaitingForKeyboard();
showPopup(AndroidUtilities.usingHardwareInput || isPaused ? 0 : 2);
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
if (isPaused) {
showKeyboardOnResume = true;
} else if (!AndroidUtilities.usingHardwareInput && !keyboardVisible && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet()) {
waitingForKeyboardOpen = true;
AndroidUtilities.cancelRunOnUIThread(openKeyboardRunnable);
AndroidUtilities.runOnUIThread(openKeyboardRunnable, 100);
}
}
protected void showPopup(int show) {
if (show == 1) {
boolean emojiWasVisible = emojiView != null && emojiView.getVisibility() == View.VISIBLE;
createEmojiView();
emojiView.setVisibility(VISIBLE);
emojiViewVisible = true;
View currentView = emojiView;
if (keyboardHeight <= 0) {
if (AndroidUtilities.isTablet()) {
keyboardHeight = AndroidUtilities.dp(150);
} else {
keyboardHeight = MessagesController.getGlobalEmojiSettings().getInt("kbd_height", AndroidUtilities.dp(200));
}
}
if (keyboardHeightLand <= 0) {
if (AndroidUtilities.isTablet()) {
keyboardHeightLand = AndroidUtilities.dp(150);
} else {
keyboardHeightLand = MessagesController.getGlobalEmojiSettings().getInt("kbd_height_land3", AndroidUtilities.dp(200));
}
}
int currentHeight = (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y ? keyboardHeightLand : keyboardHeight) + (includeNavigationBar ? AndroidUtilities.navigationBarHeight : 0);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) currentView.getLayoutParams();
layoutParams.height = currentHeight;
currentView.setLayoutParams(layoutParams);
if (!AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet()) {
AndroidUtilities.hideKeyboard(editText);
}
if (sizeNotifierLayout != null) {
emojiPadding = currentHeight;
sizeNotifierLayout.requestLayout();
emojiIconDrawable.setIcon(R.drawable.input_keyboard, true);
onWindowSizeChanged();
}
onEmojiKeyboardUpdate();
if (!keyboardVisible && !emojiWasVisible) {
ValueAnimator animator = ValueAnimator.ofFloat(emojiPadding, 0);
animator.addUpdateListener(animation -> {
float v = (float) animation.getAnimatedValue();
emojiView.setTranslationY(v);
if (emojiPadding > 0 && (currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER)) {
emojiView.setAlpha(1f - v / (float) emojiPadding);
}
bottomPanelTranslationY(v);
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
emojiView.setTranslationY(0);
emojiView.setAlpha(1f);
bottomPanelTranslationY(0);
}
});
animator.setDuration(AdjustPanLayoutHelper.keyboardDuration);
animator.setInterpolator(AdjustPanLayoutHelper.keyboardInterpolator);
animator.start();
} else {
emojiView.setAlpha(1f);
}
} else {
if (emojiButton != null) {
if (currentStyle == STYLE_FRAGMENT) {
emojiIconDrawable.setIcon(R.drawable.smiles_tab_smiles, true);
} else {
emojiIconDrawable.setIcon(R.drawable.input_smile, true);
}
}
if (emojiView != null) {
emojiViewVisible = false;
onEmojiKeyboardUpdate();
if (AndroidUtilities.usingHardwareInput || AndroidUtilities.isInMultiwindow) {
emojiView.setVisibility(GONE);
}
}
if (sizeNotifierLayout != null) {
if (show == 0) {
emojiPadding = 0;
}
sizeNotifierLayout.requestLayout();
onWindowSizeChanged();
}
}
}
private void onWindowSizeChanged() {
int size = sizeNotifierLayout.getHeight();
if (!keyboardVisible) {
size -= emojiPadding;
}
if (delegate != null) {
delegate.onWindowSizeChanged(size);
}
}
protected void closeParent() {
}
protected void drawEmojiBackground(Canvas canvas, View view) {
}
protected void createEmojiView() {
if (emojiView != null && emojiView.currentAccount != UserConfig.selectedAccount) {
sizeNotifierLayout.removeView(emojiView);
emojiView = null;
}
if (emojiView != null) {
return;
}
emojiView = new EmojiView(parentFragment, allowAnimatedEmoji, false, false, getContext(), false, null, null, currentStyle != STYLE_STORY && currentStyle != STYLE_PHOTOVIEWER, resourcesProvider, false) {
@Override
protected void dispatchDraw(Canvas canvas) {
if (currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER) {
drawEmojiBackground(canvas, this);
}
super.dispatchDraw(canvas);
}
};
emojiView.setVisibility(GONE);
if (AndroidUtilities.isTablet()) {
emojiView.setForseMultiwindowLayout(true);
}
emojiView.setDelegate(new EmojiView.EmojiViewDelegate() {
@Override
public boolean onBackspace() {
if (editText.length() == 0) {
return false;
}
editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
return true;
}
@Override
public void onAnimatedEmojiUnlockClick() {
BaseFragment fragment = parentFragment;
if (fragment == null) {
fragment = new BaseFragment() {
@Override
public int getCurrentAccount() {
return currentAccount;
}
@Override
public Context getContext() {
return EditTextEmoji.this.getContext();
}
@Override
public Activity getParentActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
@Override
public Dialog getVisibleDialog() {
return new Dialog(EditTextEmoji.this.getContext()) {
@Override
public void dismiss() {
hidePopup(false);
closeParent();
}
};
}
};
new PremiumFeatureBottomSheet(fragment, PremiumPreviewFragment.PREMIUM_FEATURE_ANIMATED_EMOJI, false).show();
} else {
fragment.showDialog(new PremiumFeatureBottomSheet(fragment, PremiumPreviewFragment.PREMIUM_FEATURE_ANIMATED_EMOJI, false));
}
}
@Override
public void onEmojiSelected(String symbol) {
int i = editText.getSelectionEnd();
if (i < 0) {
i = 0;
}
try {
innerTextChange = 2;
CharSequence localCharSequence = Emoji.replaceEmoji(symbol, editText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false);
editText.setText(editText.getText().insert(i, localCharSequence));
int j = i + localCharSequence.length();
editText.setSelection(j, j);
} catch (Exception e) {
FileLog.e(e);
} finally {
innerTextChange = 0;
}
}
@Override
public void onCustomEmojiSelected(long documentId, TLRPC.Document document, String emoticon, boolean isRecent) {
int i = editText.getSelectionEnd();
if (i < 0) {
i = 0;
}
try {
innerTextChange = 2;
SpannableString spannable = new SpannableString(emoticon);
AnimatedEmojiSpan span;
if (document != null) {
span = new AnimatedEmojiSpan(document, editText.getPaint().getFontMetricsInt());
} else {
span = new AnimatedEmojiSpan(documentId, editText.getPaint().getFontMetricsInt());
}
span.cacheType = emojiView.emojiCacheType;
spannable.setSpan(span, 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(editText.getText().insert(i, spannable));
int j = i + spannable.length();
editText.setSelection(j, j);
} catch (Exception e) {
FileLog.e(e);
} finally {
innerTextChange = 0;
}
}
@Override
public void onClearEmojiRecent() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), resourcesProvider);
builder.setTitle(LocaleController.getString("ClearRecentEmojiTitle", R.string.ClearRecentEmojiTitle));
builder.setMessage(LocaleController.getString("ClearRecentEmojiText", R.string.ClearRecentEmojiText));
builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton), (dialogInterface, i) -> emojiView.clearRecentEmoji());
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
if (parentFragment != null) {
parentFragment.showDialog(builder.create());
} else {
builder.show();
}
}
});
sizeNotifierLayout.addView(emojiView);
}
protected void onEmojiKeyboardUpdate() {}
protected void onWaitingForKeyboard() {}
public boolean isPopupView(View view) {
return view == emojiView;
}
public int getEmojiPadding() {
return emojiPadding;
}
public int getKeyboardHeight() {
return (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y ? keyboardHeightLand : keyboardHeight) + (includeNavigationBar ? AndroidUtilities.navigationBarHeight : 0);
}
@Override
public void onSizeChanged(int height, boolean isWidthGreater) {
if (height > AndroidUtilities.dp(50) && (keyboardVisible || currentStyle == STYLE_STORY || currentStyle == STYLE_PHOTOVIEWER) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet()) {
if (isWidthGreater) {
keyboardHeightLand = height;
MessagesController.getGlobalEmojiSettings().edit().putInt("kbd_height_land3", keyboardHeightLand).commit();
} else {
keyboardHeight = height;
MessagesController.getGlobalEmojiSettings().edit().putInt("kbd_height", keyboardHeight).commit();
}
}
if (isPopupShowing()) {
int newHeight = (isWidthGreater ? keyboardHeightLand : keyboardHeight) + (includeNavigationBar ? AndroidUtilities.navigationBarHeight : 0);;
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emojiView.getLayoutParams();
if (layoutParams.width != AndroidUtilities.displaySize.x || layoutParams.height != newHeight) {
layoutParams.width = AndroidUtilities.displaySize.x;
layoutParams.height = newHeight;
emojiView.setLayoutParams(layoutParams);
if (sizeNotifierLayout != null) {
emojiPadding = layoutParams.height;
sizeNotifierLayout.requestLayout();
onWindowSizeChanged();
}
}
}
if (lastSizeChangeValue1 == height && lastSizeChangeValue2 == isWidthGreater) {
onWindowSizeChanged();
return;
}
lastSizeChangeValue1 = height;
lastSizeChangeValue2 = isWidthGreater;
boolean oldValue = keyboardVisible;
keyboardVisible = editText.isFocused() && height > 0;
if (keyboardVisible && isPopupShowing()) {
showPopup(0);
}
if (emojiPadding != 0 && !keyboardVisible && keyboardVisible != oldValue && !isPopupShowing()) {
emojiPadding = 0;
sizeNotifierLayout.requestLayout();
}
if (keyboardVisible && waitingForKeyboardOpen) {
waitingForKeyboardOpen = false;
AndroidUtilities.cancelRunOnUIThread(openKeyboardRunnable);
}
onWindowSizeChanged();
}
public EditTextCaption getEditText() {
return editText;
}
public View getEmojiButton() {
return emojiButton;
}
private int getThemedColor(int key) {
return Theme.getColor(key, resourcesProvider);
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextEmoji.java |
45,290 | package hex;
import water.Iced;
import water.MRTask;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Chunk;
import water.fvec.Vec;
import water.util.Log;
import water.util.fp.Function;
import java.util.Arrays;
import static hex.AUC2.ThresholdCriterion.*;
/** One-pass approximate AUC
*
* This algorithm can compute the AUC in 1-pass with good resolution. During
* the pass, it builds an online histogram of the probabilities up to the
* resolution (number of bins) asked-for. It also computes the true-positive
* and false-positive counts for the histogramed thresholds. With these in
* hand, we can compute the TPR (True Positive Rate) and the FPR for the given
* thresholds; these define the (X,Y) coordinates of the AUC.
*/
public class AUC2 extends Iced {
public final int _nBins; // Max number of bins; can be less if there are fewer points
public final double[] _ths; // Thresholds
public final double[] _tps; // True Positives
public final double[] _fps; // False Positives
public final double _p, _n; // Actual trues, falses
public double _auc, _gini, _pr_auc; // Actual AUC value
public final int _max_idx; // Threshold that maximizes the default criterion
public static final ThresholdCriterion DEFAULT_CM = ThresholdCriterion.f1;
// Default bins, good answers on a highly unbalanced sorted (and reverse
// sorted) datasets
public static final int NBINS = 400;
/** Criteria for 2-class Confusion Matrices
*
* This is an Enum class, with an exec() function to compute the criteria
* from the basic parts, and from an AUC2 at a given threshold index.
*/
public enum ThresholdCriterion {
f1(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
final double prec = precision.exec(tp,fp,fn,tn);
final double recl = tpr .exec(tp,fp,fn,tn);
return 2. * (prec * recl) / (prec + recl);
} },
f2(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
final double prec = precision.exec(tp,fp,fn,tn);
final double recl = tpr .exec(tp,fp,fn,tn);
return 5. * (prec * recl) / (4. * prec + recl);
} },
f0point5(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
final double prec = precision.exec(tp,fp,fn,tn);
final double recl = tpr .exec(tp,fp,fn,tn);
return 1.25 * (prec * recl) / (.25 * prec + recl);
} },
accuracy(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return (tn+tp)/(tp+fn+tn+fp); } },
precision(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return tp/(tp+fp); } },
recall(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return tp/(tp+fn); } },
specificity(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return tn/(tn+fp); } },
absolute_mcc(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
double mcc = (tp*tn - fp*fn);
if (mcc == 0) return 0;
mcc /= Math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn));
// due tp and tn are double; the MCC could be slightly higher than 1. for example 1.000000000000002
double eps = 1e-10;
double absMcc = Math.abs(mcc);
assert(absMcc <= 1. + eps) : "Absolute mcc is greater than 1: mcc="+absMcc+" tp="+tp + " fp=" + fp + " fn=" + fn + " tn=" + tn;
if(absMcc > 1){
return 1;
}
return absMcc;
} },
// minimize max-per-class-error by maximizing min-per-class-accuracy.
// Report from max_criterion is the smallest correct rate for both classes.
// The max min-error-rate is 1.0 minus that.
min_per_class_accuracy(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
return Math.min(tp/(tp+fn),tn/(tn+fp));
} },
mean_per_class_accuracy(false) { @Override double exec( double tp, double fp, double fn, double tn ) {
return 0.5*(tp/(tp+fn) + tn/(tn+fp));
} },
tns(true ) { @Override double exec( double tp, double fp, double fn, double tn ) { return tn; } },
fns(true ) { @Override double exec( double tp, double fp, double fn, double tn ) { return fn; } },
fps(true ) { @Override double exec( double tp, double fp, double fn, double tn ) { return fp; } },
tps(true ) { @Override double exec( double tp, double fp, double fn, double tn ) { return tp; } },
tnr(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return tn/(fp+tn); } },
fnr(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return fn/(fn+tp); } },
fpr(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return fp/(fp+tn); } },
tpr(false) { @Override double exec( double tp, double fp, double fn, double tn ) { return tp/(tp+fn); } },
;
public final boolean _isInt; // Integral-Valued data vs Real-Valued
ThresholdCriterion(boolean isInt) { _isInt = isInt; }
/** @param tp True Positives (predicted true, actual true )
* @param fp False Positives (predicted true, actual false)
* @param fn False Negatives (predicted false, actual true )
* @param tn True Negatives (predicted false, actual false)
* @return criteria */
abstract double exec( double tp, double fp, double fn, double tn );
public double exec( AUC2 auc, int idx ) { return exec(auc.tp(idx),auc.fp(idx),auc.fn(idx),auc.tn(idx)); }
public double max_criterion( AUC2 auc ) { return exec(auc,max_criterion_idx(auc)); }
/** Convert a criterion into a threshold index that maximizes the criterion
* @return Threshold index that maximizes the criterion
*/
public int max_criterion_idx( AUC2 auc ) {
double md = -Double.MAX_VALUE;
int mx = -1;
for( int i=0; i<auc._nBins; i++ ) {
double d = exec(auc,i);
if( d > md ) {
md = d;
mx = i;
}
}
return mx;
}
public static final ThresholdCriterion[] VALUES = values();
public static AUC2.ThresholdCriterion fromString(String strRepr) {
for (ThresholdCriterion tc : ThresholdCriterion.values()) {
if (tc.toString().equalsIgnoreCase(strRepr)) {
return tc;
}
}
return null;
}
} // public enum ThresholdCriterion
public double threshold( int idx ) { return _ths[idx]; }
public double tp( int idx ) { return _tps[idx]; }
public double fp( int idx ) { return _fps[idx]; }
public double tn( int idx ) { return _n-_fps[idx]; }
public double fn( int idx ) { return _p-_tps[idx]; }
/** @return maximum F1 */
public double maxF1() { return ThresholdCriterion.f1.max_criterion(this); }
public Function<Integer, Double> forCriterion(final ThresholdCriterion tc) {
return new Function<Integer, Double>() {
public Double apply(Integer i) {
return tc.exec(AUC2.this, i);
}
};
}
/** Default bins, good answers on a highly unbalanced sorted (and reverse
* sorted) datasets */
public AUC2( Vec probs, Vec actls ) { this(NBINS,probs,actls); }
/** User-specified bin limits. Time taken is product of nBins and rows;
* large nBins can be very slow. */
AUC2( int nBins, Vec probs, Vec actls ) { this(new AUC_Impl(nBins).doAll(probs,actls)._bldr); }
public AUC2( AUCBuilder bldr ) {
this(bldr, true);
}
private AUC2( AUCBuilder bldr, boolean trueProbabilities ) {
// Copy result arrays into base object, shrinking to match actual bins
_nBins = bldr._n;
assert _nBins >= 1 : "Must have >= 1 bins for AUC calculation, but got " + _nBins;
assert trueProbabilities || bldr._ths[_nBins - 1] == 1 : "Bins need to contain pred = 1 when 0-1 probabilities are used";
_ths = Arrays.copyOf(bldr._ths,_nBins);
_tps = Arrays.copyOf(bldr._tps,_nBins);
_fps = Arrays.copyOf(bldr._fps,_nBins);
// Reverse everybody; thresholds from 1 down to 0, easier to read
for( int i=0; i<((_nBins)>>1); i++ ) {
double tmp= _ths[i]; _ths[i] = _ths[_nBins-1-i]; _ths[_nBins-1-i] = tmp ;
double tmpt = _tps[i]; _tps[i] = _tps[_nBins-1-i]; _tps[_nBins-1-i] = tmpt;
double tmpf = _fps[i]; _fps[i] = _fps[_nBins-1-i]; _fps[_nBins-1-i] = tmpf;
}
// Rollup counts, so that computing the rates are easier.
// The AUC is (TPR,FPR) as the thresholds roll about
double p=0, n=0;
for( int i=0; i<_nBins; i++ ) {
p += _tps[i]; _tps[i] = p;
n += _fps[i]; _fps[i] = n;
}
_p = p; _n = n;
if (trueProbabilities) {
_auc = compute_auc();
_pr_auc = pr_auc();
_gini = 2 * _auc - 1;
_max_idx = DEFAULT_CM.max_criterion_idx(this);
} else {
_auc = Double.NaN;
_pr_auc = Double.NaN;
_gini = Double.NaN;
_max_idx = 0;
}
}
private AUC2( AUC2 auc, int idx) {
_nBins = 1;
_ths = new double[]{auc._ths[idx]};
_tps = new double[]{auc._tps[idx]};
_fps = new double[]{auc._fps[idx]};
_p = auc._p;
_n = auc._n;
_auc = auc._auc;
_pr_auc = auc._pr_auc;
_gini = auc._gini;
_max_idx = auc._max_idx >= 0 ? 0 : -1;
}
/**
* Subsets the AUC values to a single bin corresponding to the threshold that maximizes the default criterion.
* @return AUC2 instance if there is threshold that maximizes the default criterion, null otherwise
*/
AUC2 restrictToMaxCriterion() {
return _max_idx >= 0 ? new AUC2(this, _max_idx) : null;
}
/**
* Creates an instance of AUC2 for classifiers that do not return probabilities, only 0-1.
* AUC, PR_AUC, and Gini index will be undefined in this case.
* @param bldr AUCBuilder
* @return instance of AUC2 restricted to a single bin, can be used to create a confusion matrix for the classifier
* and allows to ThresholdCriterion to calculate metrics.
*/
public static AUC2 make01AUC(AUCBuilder bldr) {
bldr.perRow(1, 0, 0); // trick: add a dummy prediction with 0 weight to make sure we always have class 1
return new AUC2(bldr, false).restrictToMaxCriterion();
}
// empty AUC, helps avoid NPE in edge cases
AUC2() {
_nBins = 0;
_ths = _tps = _fps = new double[0];
_p =_n = 0;
_auc = _gini = _pr_auc = Double.NaN;
_max_idx = -1;
}
/**
* Creates a dummy AUC2 instance with no metrics, meant to prevent possible NPEs
* @return a valid AUC2 instance
*/
public static AUC2 emptyAUC() {
return new AUC2();
}
public boolean isEmpty() {
return _nBins == 0;
}
// Checks that recall is a non-decreasing function
void checkRecallValidity() {
double x0 = recall.exec(this, 0);
for (int i = 1; i < _nBins; i++) {
double x1 = recall.exec(this, i);
if (x0 > x1)
throw new H2OIllegalArgumentException(String.valueOf(i), "recall", x0 + " > " + x1);
x0 = x1;
}
}
// Compute the Area Under the Curve, where the curve is defined by (TPR,FPR)
// points. TPR and FPR are monotonically increasing from 0 to 1.
private double compute_auc() {
if (_fps[_nBins-1] == 0) return 1.0; //special case
if (_tps[_nBins-1] == 0) return 0.0; //special case
// All math is computed scaled by TP and FP. We'll descale once at the
// end. Trapezoids from (tps[i-1],fps[i-1]) to (tps[i],fps[i])
double tp0 = 0, fp0 = 0;
double area = 0;
for( int i=0; i<_nBins; i++ ) {
area += (_fps[i]-fp0)*(_tps[i]+tp0)/2.0; // Trapezoid
tp0 = _tps[i]; fp0 = _fps[i];
}
// Descale
return area/_p/_n;
}
/**
* Compute the Area under Precision-Recall Curves using TPs and FPs.
* TPs and FPs are monotonically increasing.
* Calulation inspired by XGBoost implementation:
* https://github.com/dmlc/xgboost/blob/master/src/metric/rank_metric.cc#L566-L591
* @return
*/
public double pr_auc() {
if (isEmpty()) {
return Double.NaN;
}
checkRecallValidity();
if (_fps[_nBins-1] == 0) return 1.0;
if (_tps[_nBins-1] == 0) return 0.0;
double area = 0.0;
assert _p > 0 && _n > 0 : "AUC-PR calculation error, sum of positives and sum of negatives should be greater than zero.";
double tp, prevtp = 0.0, fp, prevfp = 0.0, tpp, prevtpp, h, a, b;
for (int j = 0; j < _nBins; j++) {
tp = _tps[j];
fp = _fps[j];
if (tp == prevtp) {
a = 1.0;
b = 0.0;
} else {
h = (fp - prevfp) / (tp - prevtp);
a = 1.0 + h;
b = (prevfp - h * prevtp) / _p;
}
tpp = tp / _p;
prevtpp = prevtp / _p;
if (0.0 != b) {
area += (tpp - prevtpp -
b / a * (Math.log(a * tpp + b) -
Math.log(a * prevtpp + b))) / a;
} else {
area += (tpp - prevtpp) / a;
}
prevtp = tp;
prevfp = fp;
}
return area;
}
// Build a CM for a threshold index. - typed as doubles because of double observation weights
public double[/*actual*/][/*predicted*/] buildCM( int idx ) {
// \ predicted: 0 1
// actual 0: TN FP
// 1: FN TP
return new double[][]{{tn(idx),fp(idx)},{fn(idx),tp(idx)}};
}
/** @return the default CM, or null for an empty AUC */
public double[/*actual*/][/*predicted*/] defaultCM( ) { return _max_idx == -1 ? null : buildCM(_max_idx); }
/** @return the CM that corresponds to a bin's index which brings max value for a given {@code criterion} */
public double[/*actual*/][/*predicted*/] cmByCriterion( ThresholdCriterion criterion) {
int maxIdx = criterion.max_criterion_idx(this);
return buildCM(maxIdx);
}
/** @return the default threshold; threshold that maximizes the default criterion */
public double defaultThreshold( ) { return _max_idx == -1 ? 0.5 : _ths[_max_idx]; }
/** @return the error of the default CM */
public double defaultErr( ) { return _max_idx == -1 ? Double.NaN : (fp(_max_idx)+fn(_max_idx))/(_p+_n); }
// Compute an online histogram of the predicted probabilities, along with
// true positive and false positive totals in each histogram bin.
private static class AUC_Impl extends MRTask<AUC_Impl> {
final int _nBins;
AUCBuilder _bldr;
AUC_Impl( int nBins ) { _nBins = nBins; }
@Override public void map( Chunk ps, Chunk as ) {
AUCBuilder bldr = _bldr = new AUCBuilder(_nBins);
for( int row = 0; row < ps._len; row++ )
if( !ps.isNA(row) && !as.isNA(row) )
bldr.perRow(ps.atd(row),(int)as.at8(row),1);
}
@Override public void reduce( AUC_Impl auc ) { _bldr.reduce(auc._bldr); }
}
public static class AUCBuilder extends Iced {
final int _nBins;
int _n; // Current number of bins
final double _ths[]; // Histogram bins, center
final double _sqe[]; // Histogram bins, squared error
final double _tps[]; // Histogram bins, true positives
final double _fps[]; // Histogram bins, false positives
// Merging this bin with the next gives the least increase in squared
// error, or -1 if not known. Requires a linear scan to find.
int _ssx;
private boolean _useFastPath = true; // only used for unit tests to check that the
public AUCBuilder(int nBins) {
_nBins = nBins;
_ths = new double[nBins<<1]; // Threshold; also the mean for this bin
_sqe = new double[nBins<<1]; // Squared error (variance) in this bin
_tps = new double[nBins<<1]; // True positives
_fps = new double[nBins<<1]; // False positives
_ssx = -1; // Unknown best merge bin
}
// Intended for unit tests only
AUCBuilder(int nBins, boolean useFastPath) {
this(nBins);
_useFastPath = useFastPath;
}
public void perRow(double pred, int act, double w ) {
// Insert the prediction into the set of histograms in sorted order, as
// if its a new histogram bin with 1 count.
assert !Double.isNaN(pred);
assert act==0 || act==1; // Actual better be 0 or 1
assert !Double.isNaN(w) && !Double.isInfinite(w);
int idx = Arrays.binarySearch(_ths,0,_n,pred);
if( idx >= 0 ) { // Found already in histogram; merge results
if( act==0 ) _fps[idx]+=w; else _tps[idx]+=w; // One more count; no change in squared error
_ssx = -1; // Blows the known best merge
return;
}
idx = -idx-1; // Get index to insert at
// If already full bins, try to instantly merge into an existing bin
if (_n == _nBins &&
_useFastPath && // Optimization enabled
idx > 0 && idx < _n && // Give up for the corner cases
_ths[idx - 1] != _ths[idx]) // Histogram has duplicates (mergeOneBin will get rid of them)
{ // Need to merge to shrink things
final int ssx = find_smallest();
double dssx = _sqe[ssx] + _sqe[ssx+1] + compute_delta_error(_ths[ssx+1], k(ssx+1), _ths[ssx], k(ssx));
// See if this point will fold into either the left or right bin
// immediately. This is the desired fast-path.
double d0 = _sqe[idx-1] + compute_delta_error(pred,w,_ths[idx-1],k(idx-1));
double d1 = _sqe[idx] + compute_delta_error(_ths[idx],k(idx),pred,w);
if (d0 < dssx || d1 < dssx) {
if (d0 <= d1) idx--; // Pick correct bin
if (ssx == idx-1 || ssx == idx)
_ssx = -1; // We don't know the minimum anymore
double k = k(idx);
if (act == 0) _fps[idx] += w; else _tps[idx] += w;
_sqe[idx] = _sqe[idx] + compute_delta_error(pred, w, _ths[idx], k);
_ths[idx] = combine_centers(_ths[idx], k, pred, w);
return;
}
}
// Must insert this point as it's own threshold (which is not insertion
// point), either because we have too few bins or because we cannot
// instantly merge the new point into an existing bin.
if (idx == 0 || idx == _n || // Just because we didn't bother to deal with the corner cases ^^^
idx == _ssx) _ssx = -1; // Smallest error becomes one of the splits
else if( idx < _ssx ) _ssx++; // Smallest error will slide right 1
// Slide over to do the insert. Horrible slowness.
System.arraycopy(_ths,idx,_ths,idx+1,_n-idx);
System.arraycopy(_sqe,idx,_sqe,idx+1,_n-idx);
System.arraycopy(_tps,idx,_tps,idx+1,_n-idx);
System.arraycopy(_fps,idx,_fps,idx+1,_n-idx);
// Insert into the histogram
_ths[idx] = pred; // New histogram center
_sqe[idx] = 0; // Only 1 point, so no squared error
if( act==0 ) { _tps[idx]=0; _fps[idx]=w; }
else { _tps[idx]=w; _fps[idx]=0; }
_n++;
if( _n > _nBins ) // Merge as needed back down to nBins
mergeOneBin(); // Merge best pair of bins
}
public void reduce( AUCBuilder bldr ) {
// Merge sort the 2 sorted lists into the double-sized arrays. The tail
// half of the double-sized array is unused, but the front half is
// probably a source. Merge into the back.
int x= _n-1;
int y=bldr._n-1;
while( x+y+1 >= 0 ) {
boolean self_is_larger = y < 0 || (x >= 0 && _ths[x] >= bldr._ths[y]);
AUCBuilder b = self_is_larger ? this : bldr;
int idx = self_is_larger ? x : y ;
_ths[x+y+1] = b._ths[idx];
_sqe[x+y+1] = b._sqe[idx];
_tps[x+y+1] = b._tps[idx];
_fps[x+y+1] = b._fps[idx];
if( self_is_larger ) x--; else y--;
}
_n += bldr._n;
_ssx = -1; // We no longer know what bin has the smallest error
// Merge elements with least squared-error increase until we get fewer
// than _nBins and no duplicates. May require many merges.
while( _n > _nBins || dups() )
mergeOneBin();
}
static double combine_centers(double ths1, double n1, double ths0, double n0) {
double center = (ths0 * n0 + ths1 * n1) / (n0 + n1);
if (Double.isNaN(center) || Double.isInfinite(center)) {
// use a simple average as a fallback
return (ths0 + ths1) / 2;
}
return center;
}
private void mergeOneBin( ) {
// Too many bins; must merge bins. Merge into bins with least total
// squared error. Horrible slowness linear arraycopy.
int ssx = find_smallest();
// Merge two bins. Classic bins merging by averaging the histogram
// centers based on counts.
double k0 = k(ssx);
double k1 = k(ssx+1);
_sqe[ssx] = _sqe[ssx]+_sqe[ssx+1]+compute_delta_error(_ths[ssx+1],k1,_ths[ssx],k0);
_ths[ssx] = combine_centers(_ths[ssx], k0, _ths[ssx+1], k1);
_tps[ssx] += _tps[ssx+1];
_fps[ssx] += _fps[ssx+1];
// Slide over to crush the removed bin at index (ssx+1)
System.arraycopy(_ths,ssx+2,_ths,ssx+1,_n-ssx-2);
System.arraycopy(_sqe,ssx+2,_sqe,ssx+1,_n-ssx-2);
System.arraycopy(_tps,ssx+2,_tps,ssx+1,_n-ssx-2);
System.arraycopy(_fps,ssx+2,_fps,ssx+1,_n-ssx-2);
_n--;
_ssx = -1;
}
// Find the pair of bins that when combined give the smallest increase in
// squared error. Dups never increase squared error.
//
// I tried code for merging bins with keeping the bins balanced in size,
// but this leads to bad errors if the probabilities are sorted. Also
// tried the original: merge bins with the least distance between bin
// centers. Same problem for sorted data.
private int find_smallest() {
if( _ssx == -1 ) {
_ssx = find_smallest_impl();
assert _ssx != -1 : toDebugString();
}
return _ssx;
}
private String toDebugString() {
return "_ssx = " + _ssx +
"; n = " + _n +
"; ths = " + Arrays.toString(_ths) +
"; tps = " + Arrays.toString(_tps) +
"; fps = " + Arrays.toString(_fps) +
"; sqe = " + Arrays.toString(_sqe);
}
private int find_smallest_impl() {
if (_n == 1)
return 0;
double minSQE = Double.MAX_VALUE;
int minI = -1;
int n = _n;
for( int i=0; i<n-1; i++ ) {
double derr = compute_delta_error(_ths[i+1],k(i+1),_ths[i],k(i));
if( derr == 0 ) return i; // Dup; no increase in SQE so return immediately
double sqe = _sqe[i]+_sqe[i+1]+derr;
if( sqe < minSQE ) {
minI = i; minSQE = sqe;
}
}
if (minI == -1) {
// we couldn't find any bins to merge based on SE (the math can be producing Double.Infinity or Double.NaN)
// revert to using a simple distance of the bin centers
minI = 0;
double minDist = _ths[1] - _ths[0];
for (int i = 1; i < n - 1; i++) {
double dist = _ths[i + 1] - _ths[i];
if (dist < minDist) {
minDist = dist;
minI = i;
}
}
}
return minI;
}
private boolean dups() {
int n = _n;
for( int i=0; i<n-1; i++ ) {
double derr = compute_delta_error(_ths[i+1],k(i+1),_ths[i],k(i));
if( derr == 0 ) { _ssx = i; return true; }
}
return false;
}
private double compute_delta_error( double ths1, double n1, double ths0, double n0 ) {
// If thresholds vary by less than a float ULP, treat them as the same.
// Some models only output predictions to within float accuracy (so a
// variance here is junk), and also it's not statistically sane to have
// a model which varies predictions by such a tiny change in thresholds.
double delta = (float)ths1-(float)ths0;
if (delta == 0)
return 0;
// Parallel equation drawn from:
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
return delta*delta*n0*n1 / (n0+n1);
}
private double k( int idx ) { return _tps[idx]+_fps[idx]; }
}
// ==========
// Given the probabilities of a 1, and the actuals (0/1) report the perfect
// AUC found by sorting the entire dataset. Expensive, and only works for
// smaller data (hundreds of millions of observations).
public static double perfectAUC( Vec vprob, Vec vacts ) {
if( vacts.min() < 0 || vacts.max() > 1 || !vacts.isInt() )
throw new IllegalArgumentException("Actuals are either 0 or 1");
if( vprob.min() < 0 || vprob.max() > 1 )
throw new IllegalArgumentException("Probabilities are between 0 and 1");
Vec.Reader rprob = vprob.new Reader();
Vec.Reader racts = vacts.new Reader();
final int posCnt = (int) vacts.nzCnt();
final int negCnt = (int) (vacts.length() - posCnt);
double[] posProbs = new double[posCnt];
double[] negProbs = new double[negCnt];
int pc = 0;
int nc = 0;
for (int i = 0; i < posCnt + negCnt; i++) {
byte actual = (byte) racts.at8(i);
double prob = rprob.at(i);
if (actual == 1) {
posProbs[pc++] = prob;
} else {
negProbs[nc++] = prob;
}
}
assert pc == posProbs.length;
assert nc == negProbs.length;
return perfectAUCFromComponents(negProbs, posProbs);
}
static double perfectAUC(double ds[], double[] acts) {
int posCnt = 0;
for (double act : acts) {
if (act == 1.0d)
posCnt++;
}
double[] posProbs = new double[posCnt];
double[] negProbs = new double[acts.length - posCnt];
int pi = 0;
int ni = 0;
for (int i = 0; i < acts.length; i++) {
if (acts[i] == 1.0d)
posProbs[pi++] = ds[i];
else
negProbs[ni++] = ds[i];
}
return perfectAUCFromComponents(negProbs, posProbs);
}
private static double perfectAUCFromComponents(double[] negProbs, double[] posProbs) {
Arrays.sort(posProbs);
Arrays.sort(negProbs);
double[] probs = new double[negProbs.length + posProbs.length];
byte[] acts = new byte[probs.length];
int pi = 0;
int ni = 0;
for (int i = 0; i < probs.length; i++) {
boolean takeNeg = pi == posProbs.length || (ni < negProbs.length && negProbs[ni] <= posProbs[pi]);
if (takeNeg) {
probs[i] = negProbs[ni++];
acts[i] = 0;
} else {
probs[i] = posProbs[pi++];
acts[i] = 1;
}
}
return perfectAUC(probs, acts);
}
private static double perfectAUC(double[] sortedProbs, byte[] sortedActs) {
// Compute Area Under Curve.
// All math is computed scaled by TP and FP. We'll descale once at the
// end. Trapezoids from (tps[i-1],fps[i-1]) to (tps[i],fps[i])
int tp0=0, fp0=0, tp1=0, fp1=0;
double prob = 1.0;
double area = 0;
for (int i = sortedProbs.length - 1; i >= 0; i--) {
if( sortedProbs[i]!=prob ) { // Tied probabilities: build a diagonal line
area += (fp1-fp0)*(tp1+tp0)/2.0; // Trapezoid
tp0 = tp1; fp0 = fp1;
prob = sortedProbs[i];
}
if( sortedActs[i]==1 ) tp1++; else fp1++;
}
area += (double)tp0*(fp1-fp0); // Trapezoid: Rectangle +
area += (double)(tp1-tp0)*(fp1-fp0)/2.0; // Right Triangle
// Descale
return area/tp1/fp1;
}
}
| h2oai/h2o-3 | h2o-core/src/main/java/hex/AUC2.java |
45,291 | /**
* Copyright (c) 2020, JGraph Ltd
* Copyright (c) 2020, draw.io AG
*/
package com.mxgraph.online;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet to fake a .well-known directory, GAE does not directly support . prefixed directories
*/
@SuppressWarnings("serial")
public class WellKnownServlet extends HttpServlet
{
private static final Logger log = Logger
.getLogger(HttpServlet.class.getName());
/**
* @see HttpServlet#HttpServlet()
*/
public WellKnownServlet()
{
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// GAE can't serve dot prefixed folders
String uri = request.getRequestURI().replace("/.", "/");
// Currently, there is only one file that this servlet serves. This is only
// needed if you want OneDrive integration.
if (uri != null && uri.equals("/well-known/microsoft-identity-association.json"))
{
if (uri.toLowerCase().contains(".json"))
{
response.setContentType("application/json");
}
// Serve whatever was requested from .well-known
try (InputStream in = getServletContext().getResourceAsStream(uri))
{
if (in == null)
{
response.sendError(404);
return;
}
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
response.getOutputStream().write(buffer, 0, count);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
else
{
response.sendError(404);
return;
}
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/WellKnownServlet.java |
45,292 | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PermanentInstallationID;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public final class LicensingFacade {
public String platformProductCode;
public String licensedTo;
public @NlsSafe String licenseeEmail;
public List<String> restrictions;
public boolean isEvaluation;
public Date expirationDate;
public Date perpetualFallbackDate;
public Map<String, Date> expirationDates;
public Map<String, String> confirmationStamps;
public Map<String, ProductLicenseData> productLicenses;
public String metadata;
public boolean ai_enabled;
public static volatile boolean isUnusedSignalled;
/**
* @deprecated Use {@link #getInstance()} instead.
*/
@Deprecated
public static volatile LicensingFacade INSTANCE;
public static @Nullable LicensingFacade getInstance() {
return INSTANCE;
}
@ApiStatus.Internal
public static void setInstance(@Nullable LicensingFacade instance) {
INSTANCE = instance;
final MessageBus messageBus = ApplicationManager.getApplication().getMessageBus();
messageBus.syncPublisher(LicenseStateListener.TOPIC).licenseStateChanged(instance);
}
public @Nullable String getLicensedToMessage() {
return licensedTo;
}
public @NlsSafe @Nullable String getLicenseeEmail() {
return licenseeEmail;
}
public @NotNull List<String> getLicenseRestrictionsMessages() {
final List<String> result = restrictions;
return result != null? result : Collections.emptyList();
}
public boolean isEvaluationLicense() {
return isEvaluation;
}
public boolean isApplicableForProduct(@NotNull Date releaseDate) {
final Date expDate = expirationDate;
return isPerpetualForProduct(releaseDate) || (expDate == null || releaseDate.before(expDate));
}
public boolean isPerpetualForProduct(@NotNull Date releaseDate) {
final Date result = perpetualFallbackDate;
return result != null && releaseDate.before(result);
}
/**
* @return the first day when the IDE license becomes invalid
*/
public @Nullable Date getLicenseExpirationDate() {
return expirationDate;
}
/**
* @param productCode the product code to lookup the expiration date for
* @return the expiration date for the specified product as it is hard-coded in the license.
* Normally the is the last day when the license is still valid.
* null value is returned if expiration date is not applicable for the product, or the licence has net been obtained
*/
public @Nullable Date getExpirationDate(String productCode) {
final Map<String, Date> result = expirationDates;
return result != null? result.get(productCode) : null;
}
/**
* @return a "confirmation stamp" string describing the license obtained by the licensing subsystem for the product with the given productCode.
* returns null, if no license is currently obtained for the product.
*
* A confirmation stamp is structured according to the following rules:
* <pre>
* confirmationStamp := key:'license-key' | stamp:'license-server-stamp' | eval:'eval-key'
* <br><br>
* licenseKey := 'licenseId'-'licenseJsonBase64'-'signatureBase64'-'certificateBase64' <br>
* the signed part is licenseJson
* <br><br>
* license-server-stamp := 'timestampLong':'machineId':'signatureType':'signatureBase64':'certificateBase64'[:'intermediate-certificateBase64']
* <br>
* the signed part is 'timestampLong':'machineId' <br>
* machineId should be the same as {@link PermanentInstallationID#get()} returns
* <br><br>
* eval-key := 'expiration-date-long'
*
* @see <a href="https://plugins.jetbrains.com/docs/marketplace/add-marketplace-license-verification-calls-to-the-plugin-code.html">JetBrains Marketplace online documentation</a> for more information
* </pre>
*/
public @Nullable String getConfirmationStamp(String productCode) {
final Map<String, String> result = confirmationStamps;
return result != null? result.get(productCode) : null;
}
private static @NotNull Gson createGson() {
return new GsonBuilder().setDateFormat("yyyyMMdd").create();
}
public String toJson() {
return createGson().toJson(this);
}
public static @Nullable LicensingFacade fromJson(String json) {
try {
return createGson().fromJson(json, LicensingFacade.class);
}
catch (Throwable e) {
return null;
}
}
public static void signalUnused(boolean value) {
isUnusedSignalled = value;
}
public static final class ProductLicenseData {
public String productCode;
public @Nullable String confirmationStamp;
public @Nullable Date expirationDate;
public boolean isPersonal;
}
public interface LicenseStateListener extends EventListener {
@NotNull Topic<LicenseStateListener> TOPIC = new Topic<>(LicenseStateListener.class);
void licenseStateChanged(@Nullable LicensingFacade newState);
}
} | JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ui/LicensingFacade.java |
45,293 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.DownloadController;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessagesController;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.NotificationsController;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.WebFile;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.MessageObject;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.ChatActivityEnterView;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.PlayingGameDrawable;
import org.telegram.ui.Components.PopupAudioView;
import org.telegram.ui.Components.RecordStatusDrawable;
import org.telegram.ui.Components.RoundStatusDrawable;
import org.telegram.ui.Components.SendingFileDrawable;
import org.telegram.ui.Components.SizeNotifierFrameLayout;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.StatusDrawable;
import org.telegram.ui.Components.TypingDotsDrawable;
import java.io.File;
import java.util.ArrayList;
public class PopupNotificationActivity extends Activity implements NotificationCenter.NotificationCenterDelegate {
private ActionBar actionBar;
private ChatActivityEnterView chatActivityEnterView;
private BackupImageView avatarImageView;
private TextView nameTextView;
private TextView onlineTextView;
private FrameLayout avatarContainer;
private TextView countText;
private ViewGroup messageContainer;
private ViewGroup centerView;
private ViewGroup leftView;
private ViewGroup rightView;
private ViewGroup centerButtonsView;
private ViewGroup leftButtonsView;
private ViewGroup rightButtonsView;
private RelativeLayout popupContainer;
private ArrayList<ViewGroup> textViews = new ArrayList<>();
private ArrayList<ViewGroup> imageViews = new ArrayList<>();
private ArrayList<ViewGroup> audioViews = new ArrayList<>();
private VelocityTracker velocityTracker = null;
private StatusDrawable[] statusDrawables = new StatusDrawable[5];
private final static int id_chat_compose_panel = 1000;
private int classGuid;
private int lastResumedAccount = -1;
private TLRPC.User currentUser;
private TLRPC.Chat currentChat;
private boolean finished = false;
private CharSequence lastPrintString;
private MessageObject currentMessageObject = null;
private MessageObject[] setMessageObjects = new MessageObject[3];
private int currentMessageNum = 0;
private PowerManager.WakeLock wakeLock = null;
private boolean animationInProgress = false;
private long animationStartTime = 0;
private float moveStartX = -1;
private boolean startedMoving = false;
private Runnable onAnimationEndRunnable = null;
private boolean isReply;
private ArrayList<MessageObject> popupMessages = new ArrayList<>();
private class FrameLayoutTouch extends FrameLayout {
public FrameLayoutTouch(Context context) {
super(context);
}
public FrameLayoutTouch(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FrameLayoutTouch(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
((PopupNotificationActivity) getContext()).onTouchEventMy(null);
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme.createDialogsResources(this);
Theme.createChatResources(this, false);
AndroidUtilities.fillStatusBarHeight(this, false);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.contactsDidLoad);
}
NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.pushMessagesUpdated);
NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded);
classGuid = ConnectionsManager.generateClassGuid();
statusDrawables[0] = new TypingDotsDrawable(false);
statusDrawables[1] = new RecordStatusDrawable(false);
statusDrawables[2] = new SendingFileDrawable(false);
statusDrawables[3] = new PlayingGameDrawable(false, null);
statusDrawables[4] = new RoundStatusDrawable(false);
SizeNotifierFrameLayout contentView = new SizeNotifierFrameLayout(this) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
int keyboardSize = measureKeyboardHeight();
if (keyboardSize <= AndroidUtilities.dp(20)) {
heightSize -= chatActivityEnterView.getEmojiPadding();
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
if (chatActivityEnterView.isPopupView(child)) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
} else if (chatActivityEnterView.isRecordCircle(child)) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), heightSize + AndroidUtilities.dp(2)), MeasureSpec.EXACTLY));
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int paddingBottom = measureKeyboardHeight() <= AndroidUtilities.dp(20) ? chatActivityEnterView.getEmojiPadding() : 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.LEFT;
}
final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = r - width - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.CENTER_VERTICAL:
childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
break;
default:
childTop = lp.topMargin;
}
if (chatActivityEnterView.isPopupView(child)) {
childTop = paddingBottom != 0 ? getMeasuredHeight() - paddingBottom : getMeasuredHeight();
} else if (chatActivityEnterView.isRecordCircle(child)) {
childTop = popupContainer.getTop() + popupContainer.getMeasuredHeight() - child.getMeasuredHeight() - lp.bottomMargin;
childLeft = popupContainer.getLeft() + popupContainer.getMeasuredWidth() - child.getMeasuredWidth() - lp.rightMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
notifyHeightChanged();
}
};
setContentView(contentView);
contentView.setBackgroundColor(0x99000000);
RelativeLayout relativeLayout = new RelativeLayout(this);
contentView.addView(relativeLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
popupContainer = new RelativeLayout(this) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = chatActivityEnterView.getMeasuredWidth();
int h = chatActivityEnterView.getMeasuredHeight();
for (int a = 0, count; a < getChildCount(); a++) {
View v = getChildAt(a);
if (v.getTag() instanceof String) {
v.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(h - AndroidUtilities.dp(3), MeasureSpec.EXACTLY));
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
for (int a = 0, count; a < getChildCount(); a++) {
View v = getChildAt(a);
if (v.getTag() instanceof String) {
v.layout(v.getLeft(), chatActivityEnterView.getTop() + AndroidUtilities.dp(3), v.getRight(), chatActivityEnterView.getBottom());
}
}
}
};
popupContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
relativeLayout.addView(popupContainer, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, 240, 12, 0, 12, 0, RelativeLayout.CENTER_IN_PARENT));
if (chatActivityEnterView != null) {
chatActivityEnterView.onDestroy();
}
chatActivityEnterView = new ChatActivityEnterView(this, contentView, null, false);
chatActivityEnterView.setId(id_chat_compose_panel);
popupContainer.addView(chatActivityEnterView, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_BOTTOM));
chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
@Override
public void onMessageSend(CharSequence message, boolean notify, int scheduleDate) {
if (currentMessageObject == null) {
return;
}
if (currentMessageNum >= 0 && currentMessageNum < popupMessages.size()) {
popupMessages.remove(currentMessageNum);
}
MessagesController.getInstance(currentMessageObject.currentAccount).markDialogAsRead(currentMessageObject.getDialogId(), currentMessageObject.getId(), Math.max(0, currentMessageObject.getId()), currentMessageObject.messageOwner.date, true, 0, 0, true, 0);
currentMessageObject = null;
getNewMessage();
}
@Override
public void onTextChanged(CharSequence text, boolean big, boolean fromDraft) {
}
@Override
public void onTextSelectionChanged(int start, int end) {
}
@Override
public void onTextSpansChanged(CharSequence text) {
}
@Override
public void onStickersExpandedChange() {
}
@Override
public void onSwitchRecordMode(boolean video) {
}
@Override
public void onPreAudioVideoRecord() {
}
@Override
public void onMessageEditEnd(boolean loading) {
}
@Override
public void needSendTyping() {
if (currentMessageObject != null) {
MessagesController.getInstance(currentMessageObject.currentAccount).sendTyping(currentMessageObject.getDialogId(), 0, 0, classGuid);
}
}
@Override
public void onAttachButtonHidden() {
}
@Override
public void onAttachButtonShow() {
}
@Override
public void onWindowSizeChanged(int size) {
}
@Override
public void onStickersTab(boolean opened) {
}
@Override
public void didPressAttachButton() {
}
@Override
public void needStartRecordVideo(int state, boolean notify, int scheduleDate, int ttl) {
}
@Override
public void toggleVideoRecordingPause() {
}
@Override
public void needStartRecordAudio(int state) {
}
@Override
public void needChangeVideoPreviewState(int state, float seekProgress) {
}
@Override
public void needShowMediaBanHint() {
}
@Override
public void onUpdateSlowModeButton(View button, boolean show, CharSequence time) {
}
@Override
public void onSendLongClick() {
}
@Override
public void onAudioVideoInterfaceUpdated() {
}
});
messageContainer = new FrameLayoutTouch(this);
popupContainer.addView(messageContainer, 0);
actionBar = new ActionBar(this);
actionBar.setOccupyStatusBar(false);
actionBar.setBackButtonImage(R.drawable.ic_close_white);
actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault));
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSelector), false);
popupContainer.addView(actionBar);
ViewGroup.LayoutParams layoutParams = actionBar.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
actionBar.setLayoutParams(layoutParams);
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem view = menu.addItemWithWidth(2, 0, AndroidUtilities.dp(56));
countText = new TextView(this);
countText.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle));
countText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
countText.setGravity(Gravity.CENTER);
view.addView(countText, LayoutHelper.createFrame(56, LayoutHelper.MATCH_PARENT));
avatarContainer = new FrameLayout(this);
avatarContainer.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
actionBar.addView(avatarContainer);
FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) avatarContainer.getLayoutParams();
layoutParams2.height = LayoutHelper.MATCH_PARENT;
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.rightMargin = AndroidUtilities.dp(48);
layoutParams2.leftMargin = AndroidUtilities.dp(60);
layoutParams2.gravity = Gravity.TOP | Gravity.LEFT;
avatarContainer.setLayoutParams(layoutParams2);
avatarImageView = new BackupImageView(this);
avatarImageView.setRoundRadius(AndroidUtilities.dp(21));
avatarContainer.addView(avatarImageView);
layoutParams2 = (FrameLayout.LayoutParams) avatarImageView.getLayoutParams();
layoutParams2.width = AndroidUtilities.dp(42);
layoutParams2.height = AndroidUtilities.dp(42);
layoutParams2.topMargin = AndroidUtilities.dp(3);
avatarImageView.setLayoutParams(layoutParams2);
nameTextView = new TextView(this);
nameTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
nameTextView.setLines(1);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
nameTextView.setGravity(Gravity.LEFT);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
avatarContainer.addView(nameTextView);
layoutParams2 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams();
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.height = LayoutHelper.WRAP_CONTENT;
layoutParams2.leftMargin = AndroidUtilities.dp(54);
layoutParams2.bottomMargin = AndroidUtilities.dp(22);
layoutParams2.gravity = Gravity.BOTTOM;
nameTextView.setLayoutParams(layoutParams2);
onlineTextView = new TextView(this);
onlineTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle));
onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
onlineTextView.setLines(1);
onlineTextView.setMaxLines(1);
onlineTextView.setSingleLine(true);
onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
onlineTextView.setGravity(Gravity.LEFT);
avatarContainer.addView(onlineTextView);
layoutParams2 = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams();
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.height = LayoutHelper.WRAP_CONTENT;
layoutParams2.leftMargin = AndroidUtilities.dp(54);
layoutParams2.bottomMargin = AndroidUtilities.dp(4);
layoutParams2.gravity = Gravity.BOTTOM;
onlineTextView.setLayoutParams(layoutParams2);
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
onFinish();
finish();
} else if (id == 1) {
openCurrentMessage();
} else if (id == 2) {
switchToNextMessage();
}
}
});
PowerManager pm = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "screen");
wakeLock.setReferenceCounted(false);
handleIntent(getIntent());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
AndroidUtilities.checkDisplaySize(this, newConfig);
fixLayout();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 3) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("PermissionNoAudioWithHint", R.string.PermissionNoAudioWithHint));
builder.setNegativeButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialog, which) -> {
try {
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + ApplicationLoader.applicationContext.getPackageName()));
startActivity(intent);
} catch (Exception e) {
FileLog.e(e);
}
});
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
builder.show();
}
}
private void switchToNextMessage() {
if (popupMessages.size() > 1) {
if (currentMessageNum < popupMessages.size() - 1) {
currentMessageNum++;
} else {
currentMessageNum = 0;
}
currentMessageObject = popupMessages.get(currentMessageNum);
updateInterfaceForCurrentMessage(2);
countText.setText(String.format("%d/%d", currentMessageNum + 1, popupMessages.size()));
}
}
private void switchToPreviousMessage() {
if (popupMessages.size() > 1) {
if (currentMessageNum > 0) {
currentMessageNum--;
} else {
currentMessageNum = popupMessages.size() - 1;
}
currentMessageObject = popupMessages.get(currentMessageNum);
updateInterfaceForCurrentMessage(1);
countText.setText(String.format("%d/%d", currentMessageNum + 1, popupMessages.size()));
}
}
public boolean checkTransitionAnimation() {
if (animationInProgress && animationStartTime < System.currentTimeMillis() - 400) {
animationInProgress = false;
if (onAnimationEndRunnable != null) {
onAnimationEndRunnable.run();
onAnimationEndRunnable = null;
}
}
return animationInProgress;
}
public boolean onTouchEventMy(MotionEvent motionEvent) {
if (checkTransitionAnimation()) {
return false;
}
if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
moveStartX = motionEvent.getX();
} else if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
int diff = (int) (x - moveStartX);
if (moveStartX != -1 && !startedMoving) {
if (Math.abs(diff) > AndroidUtilities.dp(10)) {
startedMoving = true;
moveStartX = x;
AndroidUtilities.lockOrientation(this);
diff = 0;
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
} else {
velocityTracker.clear();
}
}
}
if (startedMoving) {
if (leftView == null && diff > 0) {
diff = 0;
}
if (rightView == null && diff < 0) {
diff = 0;
}
if (velocityTracker != null) {
velocityTracker.addMovement(motionEvent);
}
applyViewsLayoutParams(diff);
}
} else if (motionEvent == null || motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
if (motionEvent != null && startedMoving) {
int diff = (int) (motionEvent.getX() - moveStartX);
int width = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
float moveDiff = 0;
int forceMove = 0;
View otherView = null;
View otherButtonsView = null;
if (velocityTracker != null) {
velocityTracker.computeCurrentVelocity(1000);
if (velocityTracker.getXVelocity() >= 3500) {
forceMove = 1;
} else if (velocityTracker.getXVelocity() <= -3500) {
forceMove = 2;
}
}
if ((forceMove == 1 || diff > width / 3) && leftView != null) {
moveDiff = width - centerView.getTranslationX();
otherView = leftView;
otherButtonsView = leftButtonsView;
onAnimationEndRunnable = () -> {
animationInProgress = false;
switchToPreviousMessage();
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
};
} else if ((forceMove == 2 || diff < -width / 3) && rightView != null) {
moveDiff = -width - centerView.getTranslationX();
otherView = rightView;
otherButtonsView = rightButtonsView;
onAnimationEndRunnable = () -> {
animationInProgress = false;
switchToNextMessage();
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
};
} else if (centerView.getTranslationX() != 0) {
moveDiff = -centerView.getTranslationX();
otherView = diff > 0 ? leftView : rightView;
otherButtonsView = diff > 0 ? leftButtonsView : rightButtonsView;
onAnimationEndRunnable = () -> {
animationInProgress = false;
applyViewsLayoutParams(0);
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
};
}
if (moveDiff != 0) {
int time = (int) (Math.abs(moveDiff / (float) width) * 200);
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(centerView, "translationX", centerView.getTranslationX() + moveDiff));
if (centerButtonsView != null) {
animators.add(ObjectAnimator.ofFloat(centerButtonsView, "translationX", centerButtonsView.getTranslationX() + moveDiff));
}
if (otherView != null) {
animators.add(ObjectAnimator.ofFloat(otherView, "translationX", otherView.getTranslationX() + moveDiff));
}
if (otherButtonsView != null) {
animators.add(ObjectAnimator.ofFloat(otherButtonsView, "translationX", otherButtonsView.getTranslationX() + moveDiff));
}
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animators);
animatorSet.setDuration(time);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (onAnimationEndRunnable != null) {
onAnimationEndRunnable.run();
onAnimationEndRunnable = null;
}
}
});
animatorSet.start();
animationInProgress = true;
animationStartTime = System.currentTimeMillis();
}
} else {
applyViewsLayoutParams(0);
}
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
startedMoving = false;
moveStartX = -1;
}
return startedMoving;
}
private void applyViewsLayoutParams(int xOffset) {
FrameLayout.LayoutParams layoutParams;
RelativeLayout.LayoutParams rLayoutParams;
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
if (leftView != null) {
layoutParams = (FrameLayout.LayoutParams) leftView.getLayoutParams();
if (layoutParams.width != widht) {
layoutParams.width = widht;
leftView.setLayoutParams(layoutParams);
}
leftView.setTranslationX(-widht + xOffset);
}
if (leftButtonsView != null) {
leftButtonsView.setTranslationX(-widht + xOffset);
}
if (centerView != null) {
layoutParams = (FrameLayout.LayoutParams) centerView.getLayoutParams();
if (layoutParams.width != widht) {
layoutParams.width = widht;
centerView.setLayoutParams(layoutParams);
}
centerView.setTranslationX(xOffset);
}
if (centerButtonsView != null) {
centerButtonsView.setTranslationX(xOffset);
}
if (rightView != null) {
layoutParams = (FrameLayout.LayoutParams) rightView.getLayoutParams();
if (layoutParams.width != widht) {
layoutParams.width = widht;
rightView.setLayoutParams(layoutParams);
}
rightView.setTranslationX(widht + xOffset);
}
if (rightButtonsView != null) {
rightButtonsView.setTranslationX(widht + xOffset);
}
messageContainer.invalidate();
}
private LinearLayout getButtonsViewForMessage(int num, boolean applyOffset) {
if (popupMessages.size() == 1 && (num < 0 || num >= popupMessages.size())) {
return null;
}
if (num == -1) {
num = popupMessages.size() - 1;
} else if (num == popupMessages.size()) {
num = 0;
}
LinearLayout view = null;
final MessageObject messageObject = popupMessages.get(num);
int buttonsCount = 0;
TLRPC.ReplyMarkup markup = messageObject.messageOwner.reply_markup;
if (messageObject.getDialogId() == 777000 && markup != null) {
ArrayList<TLRPC.TL_keyboardButtonRow> rows = markup.rows;
for (int a = 0, size = rows.size(); a < size; a++) {
TLRPC.TL_keyboardButtonRow row = rows.get(a);
for (int b = 0, size2 = row.buttons.size(); b < size2; b++) {
TLRPC.KeyboardButton button = row.buttons.get(b);
if (button instanceof TLRPC.TL_keyboardButtonCallback) {
buttonsCount++;
}
}
}
}
final int account = messageObject.currentAccount;
if (buttonsCount > 0) {
ArrayList<TLRPC.TL_keyboardButtonRow> rows = markup.rows;
for (int a = 0, size = rows.size(); a < size; a++) {
TLRPC.TL_keyboardButtonRow row = rows.get(a);
for (int b = 0, size2 = row.buttons.size(); b < size2; b++) {
TLRPC.KeyboardButton button = row.buttons.get(b);
if (button instanceof TLRPC.TL_keyboardButtonCallback) {
if (view == null) {
view = new LinearLayout(this);
view.setOrientation(LinearLayout.HORIZONTAL);
view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
view.setWeightSum(100);
view.setTag("b");
view.setOnTouchListener((v, event) -> true);
}
TextView textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText));
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setText(button.text.toUpperCase());
textView.setTag(button);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundDrawable(Theme.getSelectorDrawable(true));
view.addView(textView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 100.0f / buttonsCount));
textView.setOnClickListener(v -> {
TLRPC.KeyboardButton button1 = (TLRPC.KeyboardButton) v.getTag();
if (button1 != null) {
SendMessagesHelper.getInstance(account).sendNotificationCallback(messageObject.getDialogId(), messageObject.getId(), button1.data);
}
});
}
}
}
}
if (view != null) {
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
if (applyOffset) {
if (num == currentMessageNum) {
view.setTranslationX(0);
} else if (num == currentMessageNum - 1) {
view.setTranslationX(-widht);
} else if (num == currentMessageNum + 1) {
view.setTranslationX(widht);
}
}
popupContainer.addView(view, layoutParams);
}
return view;
}
private ViewGroup getViewForMessage(int num, boolean applyOffset) {
if (popupMessages.size() == 1 && (num < 0 || num >= popupMessages.size())) {
return null;
}
if (num == -1) {
num = popupMessages.size() - 1;
} else if (num == popupMessages.size()) {
num = 0;
}
ViewGroup view;
MessageObject messageObject = popupMessages.get(num);
if ((messageObject.type == MessageObject.TYPE_PHOTO || messageObject.type == MessageObject.TYPE_GEO) && !messageObject.isSecretMedia()) {
if (imageViews.size() > 0) {
view = imageViews.get(0);
imageViews.remove(0);
} else {
view = new FrameLayout(this);
FrameLayout frameLayout = new FrameLayout(this);
frameLayout.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10));
frameLayout.setBackgroundDrawable(Theme.getSelectorDrawable(false));
view.addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
BackupImageView backupImageView = new BackupImageView(this);
backupImageView.setTag(311);
frameLayout.addView(backupImageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
TextView textView = new TextView(this);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setGravity(Gravity.CENTER);
textView.setTag(312);
frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
view.setTag(2);
view.setOnClickListener(v -> openCurrentMessage());
}
TextView messageText = view.findViewWithTag(312);
BackupImageView imageView = view.findViewWithTag(311);
imageView.setAspectFit(true);
if (messageObject.type == MessageObject.TYPE_PHOTO) {
TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize());
TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 100);
boolean photoSet = false;
if (currentPhotoObject != null) {
boolean photoExist = true;
if (messageObject.type == MessageObject.TYPE_PHOTO) {
File cacheFile = FileLoader.getInstance(UserConfig.selectedAccount).getPathToMessage(messageObject.messageOwner);
if (!cacheFile.exists()) {
photoExist = false;
}
}
if (!messageObject.needDrawBluredPreview()) {
if (photoExist || DownloadController.getInstance(messageObject.currentAccount).canDownloadMedia(messageObject)) {
imageView.setImage(ImageLocation.getForObject(currentPhotoObject, messageObject.photoThumbsObject), "100_100", ImageLocation.getForObject(thumb, messageObject.photoThumbsObject), "100_100_b", currentPhotoObject.size, messageObject);
photoSet = true;
} else {
if (thumb != null) {
imageView.setImage(ImageLocation.getForObject(thumb, messageObject.photoThumbsObject), "100_100_b", null, null, messageObject);
photoSet = true;
}
}
}
}
if (!photoSet) {
imageView.setVisibility(View.GONE);
messageText.setVisibility(View.VISIBLE);
messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, SharedConfig.fontSize);
messageText.setText(messageObject.messageText);
} else {
imageView.setVisibility(View.VISIBLE);
messageText.setVisibility(View.GONE);
}
} else if (messageObject.type == MessageObject.TYPE_GEO) {
messageText.setVisibility(View.GONE);
messageText.setText(messageObject.messageText);
imageView.setVisibility(View.VISIBLE);
TLRPC.GeoPoint geoPoint = messageObject.messageOwner.media.geo;
double lat = geoPoint.lat;
double lon = geoPoint._long;
if (MessagesController.getInstance(messageObject.currentAccount).mapProvider == 2) {
imageView.setImage(ImageLocation.getForWebFile(WebFile.createWithGeoPoint(geoPoint, 100, 100, 15, Math.min(2, (int) Math.ceil(AndroidUtilities.density)))), null, null, null, messageObject);
} else {
String currentUrl = AndroidUtilities.formapMapUrl(messageObject.currentAccount, lat, lon, 100, 100, true, 15, -1);
imageView.setImage(currentUrl, null, null);
}
}
} else if (messageObject.type == MessageObject.TYPE_VOICE) {
PopupAudioView cell;
if (audioViews.size() > 0) {
view = audioViews.get(0);
audioViews.remove(0);
cell = view.findViewWithTag(300);
} else {
view = new FrameLayout(this);
FrameLayout frameLayout = new FrameLayout(this);
frameLayout.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10));
frameLayout.setBackgroundDrawable(Theme.getSelectorDrawable(false));
view.addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
FrameLayout frameLayout1 = new FrameLayout(this);
frameLayout.addView(frameLayout1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 20, 0, 20, 0));
cell = new PopupAudioView(this);
cell.setTag(300);
frameLayout1.addView(cell);
view.setTag(3);
view.setOnClickListener(v -> openCurrentMessage());
}
cell.setMessageObject(messageObject);
if (DownloadController.getInstance(messageObject.currentAccount).canDownloadMedia(messageObject)) {
cell.downloadAudioIfNeed();
}
} else {
if (textViews.size() > 0) {
view = textViews.get(0);
textViews.remove(0);
} else {
view = new FrameLayout(this);
ScrollView scrollView = new ScrollView(this);
scrollView.setFillViewport(true);
view.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setBackgroundDrawable(Theme.getSelectorDrawable(false));
scrollView.addView(linearLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL));
linearLayout.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(10));
linearLayout.setOnClickListener(v -> openCurrentMessage());
TextView textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setTag(301);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setGravity(Gravity.CENTER);
linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
view.setTag(1);
}
TextView messageText = view.findViewWithTag(301);
messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, SharedConfig.fontSize);
messageText.setText(messageObject.messageText);
}
if (view.getParent() == null) {
messageContainer.addView(view);
}
view.setVisibility(View.VISIBLE);
if (applyOffset) {
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
if (num == currentMessageNum) {
view.setTranslationX(0);
} else if (num == currentMessageNum - 1) {
view.setTranslationX(-widht);
} else if (num == currentMessageNum + 1) {
view.setTranslationX(widht);
}
view.setLayoutParams(layoutParams);
view.invalidate();
}
return view;
}
private void reuseButtonsView(ViewGroup view) {
if (view == null) {
return;
}
popupContainer.removeView(view);
}
private void reuseView(ViewGroup view) {
if (view == null) {
return;
}
int tag = (Integer) view.getTag();
view.setVisibility(View.GONE);
if (tag == 1) {
textViews.add(view);
} else if (tag == 2) {
imageViews.add(view);
} else if (tag == 3) {
audioViews.add(view);
}
}
private void prepareLayouts(int move) {
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
if (move == 0) {
reuseView(centerView);
reuseView(leftView);
reuseView(rightView);
reuseButtonsView(centerButtonsView);
reuseButtonsView(leftButtonsView);
reuseButtonsView(rightButtonsView);
for (int a = currentMessageNum - 1; a < currentMessageNum + 2; a++) {
if (a == currentMessageNum - 1) {
leftView = getViewForMessage(a, true);
leftButtonsView = getButtonsViewForMessage(a, true);
} else if (a == currentMessageNum) {
centerView = getViewForMessage(a, true);
centerButtonsView = getButtonsViewForMessage(a, true);
} else if (a == currentMessageNum + 1) {
rightView = getViewForMessage(a, true);
rightButtonsView = getButtonsViewForMessage(a, true);
}
}
} else if (move == 1) {
reuseView(rightView);
reuseButtonsView(rightButtonsView);
rightView = centerView;
centerView = leftView;
leftView = getViewForMessage(currentMessageNum - 1, true);
rightButtonsView = centerButtonsView;
centerButtonsView = leftButtonsView;
leftButtonsView = getButtonsViewForMessage(currentMessageNum - 1, true);
} else if (move == 2) {
reuseView(leftView);
reuseButtonsView(leftButtonsView);
leftView = centerView;
centerView = rightView;
rightView = getViewForMessage(currentMessageNum + 1, true);
leftButtonsView = centerButtonsView;
centerButtonsView = rightButtonsView;
rightButtonsView = getButtonsViewForMessage(currentMessageNum + 1, true);
} else if (move == 3) {
if (rightView != null) {
float offset = rightView.getTranslationX();
reuseView(rightView);
if ((rightView = getViewForMessage(currentMessageNum + 1, false)) != null) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) rightView.getLayoutParams();
layoutParams.width = widht;
rightView.setLayoutParams(layoutParams);
rightView.setTranslationX(offset);
rightView.invalidate();
}
}
if (rightButtonsView != null) {
float offset = rightButtonsView.getTranslationX();
reuseButtonsView(rightButtonsView);
if ((rightButtonsView = getButtonsViewForMessage(currentMessageNum + 1, false)) != null) {
rightButtonsView.setTranslationX(offset);
}
}
} else if (move == 4) {
if (leftView != null) {
float offset = leftView.getTranslationX();
reuseView(leftView);
if ((leftView = getViewForMessage(0, false)) != null) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) leftView.getLayoutParams();
layoutParams.width = widht;
leftView.setLayoutParams(layoutParams);
leftView.setTranslationX(offset);
leftView.invalidate();
}
}
if (leftButtonsView != null) {
float offset = leftButtonsView.getTranslationX();
reuseButtonsView(leftButtonsView);
if ((leftButtonsView = getButtonsViewForMessage(0, false)) != null) {
leftButtonsView.setTranslationX(offset);
}
}
}
for (int a = 0; a < 3; a++) {
int num = currentMessageNum - 1 + a;
MessageObject messageObject;
if (popupMessages.size() == 1 && (num < 0 || num >= popupMessages.size())) {
messageObject = null;
} else {
if (num == -1) {
num = popupMessages.size() - 1;
} else if (num == popupMessages.size()) {
num = 0;
}
messageObject = popupMessages.get(num);
}
setMessageObjects[a] = messageObject;
}
}
private void fixLayout() {
if (avatarContainer != null) {
avatarContainer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (avatarContainer != null) {
avatarContainer.getViewTreeObserver().removeOnPreDrawListener(this);
}
int padding = (ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(48)) / 2;
avatarContainer.setPadding(avatarContainer.getPaddingLeft(), padding, avatarContainer.getPaddingRight(), padding);
return true;
}
});
}
if (messageContainer != null) {
messageContainer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
messageContainer.getViewTreeObserver().removeOnPreDrawListener(this);
if (!checkTransitionAnimation() && !startedMoving) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) messageContainer.getLayoutParams();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight();
layoutParams.bottomMargin = AndroidUtilities.dp(48);
layoutParams.width = ViewGroup.MarginLayoutParams.MATCH_PARENT;
layoutParams.height = ViewGroup.MarginLayoutParams.MATCH_PARENT;
messageContainer.setLayoutParams(layoutParams);
applyViewsLayoutParams(0);
}
return true;
}
});
}
}
private void handleIntent(Intent intent) {
isReply = intent != null && intent.getBooleanExtra("force", false);
popupMessages.clear();
if (isReply) {
int account = intent != null ? intent.getIntExtra("currentAccount", UserConfig.selectedAccount) : UserConfig.selectedAccount;
if (!UserConfig.isValidAccount(account)) {
return;
}
popupMessages.addAll(NotificationsController.getInstance(account).popupReplyMessages);
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (UserConfig.getInstance(a).isClientActivated()) {
popupMessages.addAll(NotificationsController.getInstance(a).popupMessages);
}
}
}
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode() || !ApplicationLoader.isScreenOn) {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
if (currentMessageObject == null) {
currentMessageNum = 0;
}
getNewMessage();
}
private void getNewMessage() {
if (popupMessages.isEmpty()) {
onFinish();
finish();
return;
}
boolean found = false;
if ((currentMessageNum != 0 || chatActivityEnterView.hasText() || startedMoving) && currentMessageObject != null) {
for (int a = 0, size = popupMessages.size(); a < size; a++) {
MessageObject messageObject = popupMessages.get(a);
if (messageObject.currentAccount == currentMessageObject.currentAccount && messageObject.getDialogId() == currentMessageObject.getDialogId() && messageObject.getId() == currentMessageObject.getId()) {
currentMessageNum = a;
found = true;
break;
}
}
}
if (!found) {
currentMessageNum = 0;
currentMessageObject = popupMessages.get(0);
updateInterfaceForCurrentMessage(0);
} else if (startedMoving) {
if (currentMessageNum == popupMessages.size() - 1) {
prepareLayouts(3);
} else if (currentMessageNum == 1) {
prepareLayouts(4);
}
}
countText.setText(String.format("%d/%d", currentMessageNum + 1, popupMessages.size()));
}
private void openCurrentMessage() {
if (currentMessageObject == null) {
return;
}
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
long dialogId = currentMessageObject.getDialogId();
if (DialogObject.isEncryptedDialog(dialogId)) {
intent.putExtra("encId", DialogObject.getEncryptedChatId(dialogId));
} else if (DialogObject.isUserDialog(dialogId)) {
intent.putExtra("userId", dialogId);
} else if (DialogObject.isChatDialog(dialogId)) {
intent.putExtra("chatId", -dialogId);
}
intent.putExtra("currentAccount", currentMessageObject.currentAccount);
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
onFinish();
finish();
}
private void updateInterfaceForCurrentMessage(int move) {
if (actionBar == null) {
return;
}
if (lastResumedAccount != currentMessageObject.currentAccount) {
if (lastResumedAccount >= 0) {
ConnectionsManager.getInstance(lastResumedAccount).setAppPaused(true, false);
}
lastResumedAccount = currentMessageObject.currentAccount;
ConnectionsManager.getInstance(lastResumedAccount).setAppPaused(false, false);
}
currentChat = null;
currentUser = null;
long dialogId = currentMessageObject.getDialogId();
chatActivityEnterView.setDialogId(dialogId, currentMessageObject.currentAccount);
if (DialogObject.isEncryptedDialog(dialogId)) {
TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentMessageObject.currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId));
currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(encryptedChat.user_id);
} else if (DialogObject.isUserDialog(dialogId)) {
currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(dialogId);
} else if (DialogObject.isChatDialog(dialogId)) {
currentChat = MessagesController.getInstance(currentMessageObject.currentAccount).getChat(-dialogId);
if (currentMessageObject.isFromUser()) {
currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(currentMessageObject.messageOwner.from_id.user_id);
}
}
if (currentChat != null) {
nameTextView.setText(currentChat.title);
if (currentUser != null) {
onlineTextView.setText(UserObject.getUserName(currentUser));
} else {
onlineTextView.setText(null);
}
nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
nameTextView.setCompoundDrawablePadding(0);
} else if (currentUser != null) {
nameTextView.setText(UserObject.getUserName(currentUser));
if (DialogObject.isEncryptedDialog(dialogId)) {
nameTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_white, 0, 0, 0);
nameTextView.setCompoundDrawablePadding(AndroidUtilities.dp(4));
} else {
nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
nameTextView.setCompoundDrawablePadding(0);
}
}
prepareLayouts(move);
updateSubtitle();
checkAndUpdateAvatar();
applyViewsLayoutParams(0);
}
private void updateSubtitle() {
if (actionBar == null || currentMessageObject == null) {
return;
}
if (currentChat != null || currentUser == null) {
return;
}
if (currentUser.id / 1000 != 777 && currentUser.id / 1000 != 333 && ContactsController.getInstance(currentMessageObject.currentAccount).contactsDict.get(currentUser.id) == null && (ContactsController.getInstance(currentMessageObject.currentAccount).contactsDict.size() != 0 || !ContactsController.getInstance(currentMessageObject.currentAccount).isLoadingContacts())) {
if (currentUser.phone != null && currentUser.phone.length() != 0) {
nameTextView.setText(PhoneFormat.getInstance().format("+" + currentUser.phone));
} else {
nameTextView.setText(UserObject.getUserName(currentUser));
}
} else {
nameTextView.setText(UserObject.getUserName(currentUser));
}
if (currentUser != null && currentUser.id == 777000) {
onlineTextView.setText(LocaleController.getString("ServiceNotifications", R.string.ServiceNotifications));
} else {
CharSequence printString = MessagesController.getInstance(currentMessageObject.currentAccount).getPrintingString(currentMessageObject.getDialogId(), 0, false);
if (printString == null || printString.length() == 0) {
lastPrintString = null;
setTypingAnimation(false);
TLRPC.User user = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(currentUser.id);
if (user != null) {
currentUser = user;
}
onlineTextView.setText(LocaleController.formatUserStatus(currentMessageObject.currentAccount, currentUser));
} else {
lastPrintString = printString;
onlineTextView.setText(printString);
setTypingAnimation(true);
}
}
}
private void checkAndUpdateAvatar() {
if (currentMessageObject == null) {
return;
}
if (currentChat != null) {
TLRPC.Chat chat = MessagesController.getInstance(currentMessageObject.currentAccount).getChat(currentChat.id);
if (chat == null) {
return;
}
currentChat = chat;
if (avatarImageView != null) {
AvatarDrawable avatarDrawable = new AvatarDrawable(currentChat);
avatarImageView.setForUserOrChat(chat, avatarDrawable);
}
} else if (currentUser != null) {
TLRPC.User user = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(currentUser.id);
if (user == null) {
return;
}
currentUser = user;
if (avatarImageView != null) {
AvatarDrawable avatarDrawable = new AvatarDrawable(currentUser);
avatarImageView.setForUserOrChat(user, avatarDrawable);
}
}
}
private void setTypingAnimation(boolean start) {
if (actionBar == null) {
return;
}
if (start) {
try {
Integer type = MessagesController.getInstance(currentMessageObject.currentAccount).getPrintingStringType(currentMessageObject.getDialogId(), 0);
onlineTextView.setCompoundDrawablesWithIntrinsicBounds(statusDrawables[type], null, null, null);
onlineTextView.setCompoundDrawablePadding(AndroidUtilities.dp(4));
for (int a = 0; a < statusDrawables.length; a++) {
if (a == type) {
statusDrawables[a].start();
} else {
statusDrawables[a].stop();
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
onlineTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
onlineTextView.setCompoundDrawablePadding(0);
for (int a = 0; a < statusDrawables.length; a++) {
statusDrawables[a].stop();
}
}
}
@Override
public void onBackPressed() {
if (chatActivityEnterView.isPopupShowing()) {
chatActivityEnterView.hidePopup(true);
return;
}
super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
MediaController.getInstance().setFeedbackView(chatActivityEnterView, true);
if (chatActivityEnterView != null) {
chatActivityEnterView.setFieldFocused(true);
}
fixLayout();
checkAndUpdateAvatar();
wakeLock.acquire(7000);
}
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
if (chatActivityEnterView != null) {
chatActivityEnterView.hidePopup(false);
chatActivityEnterView.setFieldFocused(false);
}
if (lastResumedAccount >= 0) {
ConnectionsManager.getInstance(lastResumedAccount).setAppPaused(true, false);
}
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.appDidLogout) {
if (account == lastResumedAccount) {
onFinish();
finish();
}
} else if (id == NotificationCenter.pushMessagesUpdated) {
if (!isReply) {
popupMessages.clear();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (UserConfig.getInstance(a).isClientActivated()) {
popupMessages.addAll(NotificationsController.getInstance(a).popupMessages);
}
}
getNewMessage();
if (!popupMessages.isEmpty()) {
for (int a = 0; a < 3; a++) {
int num = currentMessageNum - 1 + a;
MessageObject messageObject;
if (popupMessages.size() == 1 && (num < 0 || num >= popupMessages.size())) {
messageObject = null;
} else {
if (num == -1) {
num = popupMessages.size() - 1;
} else if (num == popupMessages.size()) {
num = 0;
}
messageObject = popupMessages.get(num);
}
if (setMessageObjects[a] != messageObject) {
updateInterfaceForCurrentMessage(0);
}
}
}
}
} else if (id == NotificationCenter.updateInterfaces) {
if (currentMessageObject == null || account != lastResumedAccount) {
return;
}
int updateMask = (Integer) args[0];
if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) {
updateSubtitle();
}
if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0) {
checkAndUpdateAvatar();
}
if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.getInstance(currentMessageObject.currentAccount).getPrintingString(currentMessageObject.getDialogId(), 0, false);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && !lastPrintString.equals(printString)) {
updateSubtitle();
}
}
} else if (id == NotificationCenter.messagePlayingDidReset) {
Integer mid = (Integer) args[0];
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
if ((Integer) view.getTag() == 3) {
PopupAudioView cell = view.findViewWithTag(300);
MessageObject messageObject = cell.getMessageObject();
if (messageObject != null && messageObject.currentAccount == account && messageObject.getId() == mid) {
cell.updateButtonState();
break;
}
}
}
}
} else if (id == NotificationCenter.messagePlayingProgressDidChanged) {
Integer mid = (Integer) args[0];
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
if ((Integer) view.getTag() == 3) {
PopupAudioView cell = view.findViewWithTag(300);
MessageObject messageObject = cell.getMessageObject();
if (messageObject != null && messageObject.currentAccount == account && messageObject.getId() == mid) {
cell.updateProgress();
break;
}
}
}
}
} else if (id == NotificationCenter.emojiLoaded) {
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
if ((Integer) view.getTag() == 1) {
TextView textView = view.findViewWithTag(301);
if (textView != null) {
textView.invalidate();
}
}
}
}
} else if (id == NotificationCenter.contactsDidLoad) {
if (account == lastResumedAccount) {
updateSubtitle();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
onFinish();
MediaController.getInstance().setFeedbackView(chatActivityEnterView, false);
if (wakeLock.isHeld()) {
wakeLock.release();
}
if (avatarImageView != null) {
avatarImageView.setImageDrawable(null);
}
}
protected void onFinish() {
if (finished) {
return;
}
finished = true;
if (isReply) {
popupMessages.clear();
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.contactsDidLoad);
}
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.pushMessagesUpdated);
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded);
if (chatActivityEnterView != null) {
chatActivityEnterView.onDestroy();
}
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java |
45,294 | /*
* Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.net.ssl;
import java.security.cert.*;
/**
* Instance of this interface manage which X509 certificates
* may be used to authenticate the remote side of a secure
* socket. Decisions may be based on trusted certificate
* authorities, certificate revocation lists, online
* status checking or other means.
*
* @since 1.4
*/
public interface X509TrustManager extends TrustManager {
/**
* Given the partial or complete certificate chain provided by the
* peer, build a certificate path to a trusted root and return if
* it can be validated and is trusted for client SSL
* authentication based on the authentication type.
* <p>
* The authentication type is determined by the actual certificate
* used. For instance, if RSAPublicKey is used, the authType
* should be "RSA". Checking is case-sensitive.
*
* @param chain the peer certificate chain
* @param authType the authentication type based on the client certificate
* @throws IllegalArgumentException if null or zero-length chain
* is passed in for the chain parameter or if null or zero-length
* string is passed in for the authType parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager.
*/
void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException;
/**
* Given the partial or complete certificate chain provided by the
* peer, build a certificate path to a trusted root and return if
* it can be validated and is trusted for server SSL
* authentication based on the authentication type.
* <p>
* The authentication type is the key exchange algorithm portion
* of the cipher suites represented as a String, such as "RSA",
* "DHE_DSS". Note: for some exportable cipher suites, the key
* exchange algorithm is determined at run time during the
* handshake. For instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5,
* the authType should be RSA_EXPORT when an ephemeral RSA key is
* used for the key exchange, and RSA when the key from the server
* certificate is used. Checking is case-sensitive.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @throws IllegalArgumentException if null or zero-length chain
* is passed in for the chain parameter or if null or zero-length
* string is passed in for the authType parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager.
*/
void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException;
/**
* Return an array of certificate authority certificates
* which are trusted for authenticating peers.
*
* @return a non-null (possibly empty) array of acceptable
* CA issuer certificates.
*/
X509Certificate[] getAcceptedIssuers();
}
| openjdk/jdk | src/java.base/share/classes/javax/net/ssl/X509TrustManager.java |
45,295 | package com.twitter.search.earlybird;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.GuardedBy;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.twitter.common.zookeeper.ServerSet;
import com.twitter.common.zookeeper.ZooKeeperClient;
import com.twitter.common_internal.zookeeper.TwitterServerSet;
import com.twitter.search.common.config.Config;
import com.twitter.search.common.database.DatabaseConfig;
import com.twitter.search.common.metrics.SearchCounter;
import com.twitter.search.common.metrics.SearchLongGauge;
import com.twitter.search.common.metrics.SearchStatsReceiver;
import com.twitter.search.common.util.zookeeper.ZooKeeperProxy;
import com.twitter.search.earlybird.common.config.EarlybirdConfig;
import com.twitter.search.earlybird.common.config.EarlybirdProperty;
import com.twitter.search.earlybird.config.TierConfig;
import com.twitter.search.earlybird.exception.AlreadyInServerSetUpdateException;
import com.twitter.search.earlybird.exception.NotInServerSetUpdateException;
import com.twitter.search.earlybird.partition.PartitionConfig;
public class EarlybirdServerSetManager implements ServerSetMember {
private static final Logger LOG = LoggerFactory.getLogger(EarlybirdServerSetManager.class);
// How many times this earlybird joined/left its partition's server set
@VisibleForTesting
protected final SearchCounter leaveServerSetCounter;
@VisibleForTesting
protected final SearchCounter joinServerSetCounter;
private final ZooKeeperProxy discoveryZKClient;
private final SearchLongGauge inServerSetGauge;
private final PartitionConfig partitionConfig;
private final int port;
private final String serverSetNamePrefix;
@VisibleForTesting
protected final SearchLongGauge connectedToZooKeeper;
private final Object endpointStatusLock = new Object();
@GuardedBy("endpointStatusLock")
private ServerSet.EndpointStatus endpointStatus = null;
private boolean inServerSetForServiceProxy = false;
public EarlybirdServerSetManager(
SearchStatsReceiver searchStatsReceiver,
ZooKeeperProxy discoveryZKClient,
final PartitionConfig partitionConfig,
int port,
String serverSetNamePrefix) {
this.discoveryZKClient = discoveryZKClient;
this.partitionConfig = partitionConfig;
this.port = port;
this.serverSetNamePrefix = serverSetNamePrefix;
// Export serverset related stats
Preconditions.checkNotNull(searchStatsReceiver);
this.joinServerSetCounter = searchStatsReceiver.getCounter(
serverSetNamePrefix + "join_server_set_count");
this.leaveServerSetCounter = searchStatsReceiver.getCounter(
serverSetNamePrefix + "leave_server_set_count");
// Create a new stat based on the partition number for hosts-in-partition aggregation.
// The value of the stat is dependent on whether the server is in the serverset so that the
// aggregate stat reflects the number serving traffic instead of the live process count.
AtomicLong sharedInServerSetStatus = new AtomicLong();
this.inServerSetGauge = searchStatsReceiver.getLongGauge(
serverSetNamePrefix + "is_in_server_set", sharedInServerSetStatus);
this.connectedToZooKeeper = searchStatsReceiver.getLongGauge(
serverSetNamePrefix + "connected_to_zookeeper");
searchStatsReceiver.getLongGauge(
serverSetNamePrefix + "member_of_partition_" + partitionConfig.getIndexingHashPartitionID(),
sharedInServerSetStatus);
this.discoveryZKClient.registerExpirationHandler(() -> connectedToZooKeeper.set(0));
this.discoveryZKClient.register(event -> {
if (event.getType() == Watcher.Event.EventType.None
&& event.getState() == Watcher.Event.KeeperState.SyncConnected) {
connectedToZooKeeper.set(1);
}
});
}
/**
* Join ServerSet and update endpointStatus.
* This will allow Earlybird consumers, e.g. Blender, to detect when an
* Earlybird goes online and offline.
* @param username
*/
@Override
public void joinServerSet(String username) throws ServerSet.UpdateException {
joinServerSetCounter.increment();
synchronized (endpointStatusLock) {
LOG.info("Joining {} ServerSet (instructed by: {}) ...", serverSetNamePrefix, username);
if (endpointStatus != null) {
LOG.warn("Already in ServerSet. Nothing done.");
throw new AlreadyInServerSetUpdateException("Already in ServerSet. Nothing done.");
}
try {
TwitterServerSet.Service service = getServerSetService();
ServerSet serverSet = discoveryZKClient.createServerSet(service);
endpointStatus = serverSet.join(
new InetSocketAddress(InetAddress.getLocalHost().getHostName(), port),
Maps.newHashMap(),
partitionConfig.getHostPositionWithinHashPartition());
inServerSetGauge.set(1);
String path = service.getPath();
EarlybirdStatus.recordEarlybirdEvent("Joined " + serverSetNamePrefix + " ServerSet " + path
+ " (instructed by: " + username + ")");
LOG.info("Successfully joined {} ServerSet {} (instructed by: {})",
serverSetNamePrefix, path, username);
} catch (Exception e) {
endpointStatus = null;
String message = "Failed to join " + serverSetNamePrefix + " ServerSet of partition "
+ partitionConfig.getIndexingHashPartitionID();
LOG.error(message, e);
throw new ServerSet.UpdateException(message, e);
}
}
}
/**
* Takes this Earlybird out of its registered ServerSet.
*
* @throws ServerSet.UpdateException if there was a problem leaving the ServerSet,
* or if this Earlybird is already not in a ServerSet.
* @param username
*/
@Override
public void leaveServerSet(String username) throws ServerSet.UpdateException {
leaveServerSetCounter.increment();
synchronized (endpointStatusLock) {
LOG.info("Leaving {} ServerSet (instructed by: {}) ...", serverSetNamePrefix, username);
if (endpointStatus == null) {
String message = "Not in a ServerSet. Nothing done.";
LOG.warn(message);
throw new NotInServerSetUpdateException(message);
}
endpointStatus.leave();
endpointStatus = null;
inServerSetGauge.set(0);
EarlybirdStatus.recordEarlybirdEvent("Left " + serverSetNamePrefix
+ " ServerSet (instructed by: " + username + ")");
LOG.info("Successfully left {} ServerSet. (instructed by: {})",
serverSetNamePrefix, username);
}
}
@Override
public int getNumberOfServerSetMembers()
throws InterruptedException, ZooKeeperClient.ZooKeeperConnectionException, KeeperException {
String path = getServerSetService().getPath();
return discoveryZKClient.getNumberOfServerSetMembers(path);
}
/**
* Determines if this earlybird is in the server set.
*/
@Override
public boolean isInServerSet() {
synchronized (endpointStatusLock) {
return endpointStatus != null;
}
}
/**
* Returns the server set that this earlybird should join.
*/
public String getServerSetIdentifier() {
TwitterServerSet.Service service = getServerSetService();
return String.format("/cluster/local/%s/%s/%s",
service.getRole(),
service.getEnv(),
service.getName());
}
private TwitterServerSet.Service getServerSetService() {
// If the tier name is 'all' then it treat it as an untiered EB cluster
// and do not add the tier component into the ZK path it registers under.
String tierZKPathComponent = "";
if (!TierConfig.DEFAULT_TIER_NAME.equalsIgnoreCase(partitionConfig.getTierName())) {
tierZKPathComponent = "/" + partitionConfig.getTierName();
}
if (EarlybirdConfig.isAurora()) {
// ROLE, EARYLBIRD_NAME, and ENV properties are required on Aurora, thus will be set here
return new TwitterServerSet.Service(
EarlybirdProperty.ROLE.get(),
EarlybirdProperty.ENV.get(),
getServerSetPath(EarlybirdProperty.EARLYBIRD_NAME.get() + tierZKPathComponent));
} else {
return new TwitterServerSet.Service(
DatabaseConfig.getZooKeeperRole(),
Config.getEnvironment(),
getServerSetPath("earlybird" + tierZKPathComponent));
}
}
private String getServerSetPath(String earlybirdName) {
return String.format("%s%s/hash_partition_%d", serverSetNamePrefix, earlybirdName,
partitionConfig.getIndexingHashPartitionID());
}
/**
* Join ServerSet for ServiceProxy with a named admin port and with a zookeeper path that Service
* Proxy can translate to a domain name label that is less than 64 characters (due to the size
* limit for domain name labels described here: https://tools.ietf.org/html/rfc1035)
* This will allow us to access Earlybirds that are not on mesos via ServiceProxy.
*/
@Override
public void joinServerSetForServiceProxy() {
// This additional Zookeeper server set is only necessary for Archive Earlybirds which are
// running on bare metal hardware, so ensure that this method is never called for services
// on Aurora.
Preconditions.checkArgument(!EarlybirdConfig.isAurora(),
"Attempting to join server set for ServiceProxy on Earlybird running on Aurora");
LOG.info("Attempting to join ServerSet for ServiceProxy");
try {
TwitterServerSet.Service service = getServerSetForServiceProxyOnArchive();
ServerSet serverSet = discoveryZKClient.createServerSet(service);
String hostName = InetAddress.getLocalHost().getHostName();
int adminPort = EarlybirdConfig.getAdminPort();
serverSet.join(
new InetSocketAddress(hostName, port),
ImmutableMap.of("admin", new InetSocketAddress(hostName, adminPort)),
partitionConfig.getHostPositionWithinHashPartition());
String path = service.getPath();
LOG.info("Successfully joined ServerSet for ServiceProxy {}", path);
inServerSetForServiceProxy = true;
} catch (Exception e) {
String message = "Failed to join ServerSet for ServiceProxy of partition "
+ partitionConfig.getIndexingHashPartitionID();
LOG.warn(message, e);
}
}
@VisibleForTesting
protected TwitterServerSet.Service getServerSetForServiceProxyOnArchive() {
String serverSetPath = String.format("proxy/%s/p_%d",
partitionConfig.getTierName(),
partitionConfig.getIndexingHashPartitionID());
return new TwitterServerSet.Service(
DatabaseConfig.getZooKeeperRole(),
Config.getEnvironment(),
serverSetPath);
}
@VisibleForTesting
protected boolean isInServerSetForServiceProxy() {
return inServerSetForServiceProxy;
}
}
| twitter/the-algorithm | src/java/com/twitter/search/earlybird/EarlybirdServerSetManager.java |
45,296 | package com.mxgraph.online;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mxgraph.online.Utils.SizeLimitExceededException;
/**
* Servlet implementation ExportProxyServlet
*/
@SuppressWarnings("serial")
public class ExportProxyServlet extends HttpServlet
{
private final String[] supportedServices = {"EXPORT_URL", "PLANTUML_URL", "VSD_CONVERT_URL", "EMF_CONVERT_URL"};
private void doRequest(String method, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
int serviceId = 0;
String proxyPath = "";
String queryString = "";
try
{
if (request.getQueryString() != null)
{
queryString = "?" + request.getQueryString();
}
if (request.getPathInfo() != null) // /{serviceId}/*
{
String[] pathParts = request.getPathInfo().split("/");
if (pathParts.length > 1)
{
serviceId = Integer.parseInt(pathParts[1]);
}
if (pathParts.length > 2)
{
proxyPath = String.join("/", Arrays.copyOfRange(pathParts, 2, pathParts.length));
}
if (serviceId < 0 || serviceId > supportedServices.length)
{
serviceId = 0;
}
}
}
catch (Exception e)
{
// Ignore and use 0
serviceId = 0;
}
String exportUrl = System.getenv(supportedServices[serviceId]);
if (exportUrl == null || exportUrl.isEmpty() ||
(!exportUrl.startsWith("http://") && !exportUrl.startsWith("https://")))
{
throw new Exception(supportedServices[serviceId] + " not set or invalid");
}
else if (!exportUrl.endsWith("/")) // There are other non-trivial cases, admins should configure these URLs carefully
{
exportUrl += "/";
}
URL url = new URL(exportUrl + proxyPath + queryString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(method);
//Copy request headers to export server
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
Enumeration<String> headers = request.getHeaders(headerName);
while (headers.hasMoreElements())
{
String headerValue = headers.nextElement();
con.addRequestProperty(headerName, headerValue);
}
}
if ("POST".equals(method))
{
// Send post request
con.setDoOutput(true);
OutputStream params = con.getOutputStream();
Utils.copyRestricted(request.getInputStream(), params);
params.flush();
params.close();
}
int responseCode = con.getResponseCode();
//Copy response code
response.setStatus(responseCode);
//Copy response headers
Map<String, List<String>> map = con.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String key = entry.getKey();
if (key != null)
{
for (String val : entry.getValue())
{
response.addHeader(entry.getKey(), val);
}
}
}
//Copy response
OutputStream out = response.getOutputStream();
//Error
if (responseCode >= 400)
{
Utils.copy(con.getErrorStream(), out);
}
else //Success
{
Utils.copy(con.getInputStream(), out);
}
out.flush();
out.close();
}
catch (SizeLimitExceededException e)
{
response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
throw e;
}
catch (Exception e)
{
response.setStatus(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest("GET", request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest("POST", request, response);
}
} | jgraph/drawio | src/main/java/com/mxgraph/online/ExportProxyServlet.java |
45,298 | /*
Copyright © 2011 - 2021, Ingo Wechsung
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution. Neither the name of the copyright holder
nor the names of its contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE
COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
package frege.runtime;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
/**
* Miscellaneous functions and methods needed in frege.
*
* @author ingo
*
*/
public class Runtime {
/**
* GLobal Random generator
*/
final public static java.util.Random stdRandom = new java.util.Random ();
/**
* Implementation for
* <code>pure native constructor frege.runtime.Runtime.constructor :: a -> Int</code>
*/
final public static int constructor(Value v) { // if it is statically known that v is a Value
return v.constructor();
}
// final public static int constructor(Integer v) { return v; }
final public static int constructor(Object v) { // if v is completely unknown, it could still be a Value
if (v instanceof Value) return ((Value)v).constructor();
if (v instanceof Integer) return ((Integer)v).intValue();
return 0;
}
/**
* Implementation for frege.prelude.PreludeBase.getClass
*/
@SuppressWarnings("unchecked") final public static<A> Class<A> getClass(A o) {
return (Class<A>) o.getClass();
}
/**
* Implementation for frege.prelude.PreludeBase.Class.forName
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
final public static<A> Class<A> classForName(final String x)
throws ClassNotFoundException {
return (Class<A>) Class.forName(x);
}
/**
* Provide UTF-8 encoded standard printer for stdout with automatic line flushing
* <p>Must be thread local so that it works in the online REPL, for instance. </p>
*/
public static ThreadLocal<PrintWriter> stdout = new ThreadLocal<PrintWriter>() {
@Override protected PrintWriter initialValue() {
return new PrintWriter(
new OutputStreamWriter(System.out, StandardCharsets.UTF_8),
true);
}
};
/**
* Provide UTF-8 encoded standard printer for stderr with autoflush
* <p>Must be thread local so that it works in the online REPL, for instance. </p>
*/
public static ThreadLocal<PrintWriter> stderr = new ThreadLocal<PrintWriter>() {
@Override protected PrintWriter initialValue() {
return new PrintWriter(
new OutputStreamWriter(System.err, StandardCharsets.UTF_8),
true);
}
};
/**
* Provide UTF-8 decoded standard input Reader
*/
public static ThreadLocal<BufferedReader> stdin = new ThreadLocal<BufferedReader>() {
@Override protected BufferedReader initialValue() {
return new BufferedReader(
new InputStreamReader(System.in, StandardCharsets.UTF_8));
}
};
/**
* <p> Utility method used by <code>String.show</code> to quote a string. </p>
*/
final public static java.lang.String quoteStr(java.lang.String a) {
java.lang.StringBuilder sr = new java.lang.StringBuilder(2+((5*a.length()) >> 2));
sr.append('"');
int i = 0;
char c; char low;
while (i<a.length()) {
c = a.charAt(i++);
if (c<' ' || c == '\177') {
if (c == '\n') sr.append("\\n");
else if (c == '\t') sr.append("\\t");
else if (c == '\f') sr.append("\\f");
else if (c == '\r') sr.append("\\r");
else if (c == '\b') sr.append("\\b");
else {
sr.append(java.lang.String.format("\\u%04x", (int) c));
}
}
else if (c == '\\' || c == '"') {
sr.append('\\');
sr.append(c);
}
// don't break surrogate pairs that denote valid characters
else if (i < a.length()
&& Character.isSurrogatePair(c, (low = a.charAt(i)))
&& Character.isDefined(Character.toCodePoint(c, low))) {
sr.append(c);
sr.append(low);
i++;
}
else if (!Character.isDefined(c)
|| Character.getType(c) == Character.CONTROL
|| Character.isSurrogate(c)) {
sr.append(String.format("\\u%04x", (int) c));
}
else sr.append(c);
}
sr.append('"');
return sr.toString();
}
/**
* <p> Utility method used by <code>Char.show</code> to quote a character. </p>
*/
final public static java.lang.String quoteChr(char c) {
java.lang.StringBuilder sr = new java.lang.StringBuilder(8);
sr.append("'");
if (c<' ' || c == '\177') {
if (c == '\n') sr.append("\\n");
else if (c == '\t') sr.append("\\t");
else if (c == '\f') sr.append("\\f");
else if (c == '\r') sr.append("\\r");
else if (c == '\b') sr.append("\\b");
else {
sr.append(java.lang.String.format("\\u%04x", (int) c));
}
}
else if (c == '\\' || c == '\'') {
sr.append('\\');
sr.append(c);
}
else if (!Character.isDefined(c)
|| Character.getType(c) == Character.CONTROL
|| Character.isSurrogate(c)) {
sr.append(String.format("\\u%04x", (int) c));
}
else sr.append(c);
sr.append("'");
return sr.toString();
}
/*
* <p> This is used to copy a mutable value. </p>
* <p> The returned value is of same type, but is considered immutable.
* Suitable for instances of classes that do implement {@link Cloneable}.</p>
* <p> Remember that only a deep copy makes a really safe copy .</p>
* @param o the value to copy
* @return a copy obtained by cloning of the argument value, followed by deserialization
*/
// public final static<T extends Cloneable> T clone(final T o) { return o.clone(); }
/**
* <p> This is used to copy a mutable value. </p>
* <p> The returned value is of same type, but is considered immutable.
* Suitable for instances of classes that do not implement {@link Cloneable},
* but do implement {@link Serializable}.</p>
* @param o the value to copy
* @return a copy obtained by serialization of the argument value, followed by deserialization
*/
public final static<T extends Serializable> T copySerializable(final T o) {
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais);
@SuppressWarnings("unchecked")
final T s = (T) ois.readObject();
ois.close();
return s;
} catch (Exception exc) {
new Undefined("error in (de)serialization", exc).die();
return null;
}
}
/**
* Identity function for reference types
* (Can be used to pseudo thaw/freeze a value)
*/
public final static <T> T identity(T x) { return x; }
/**
* Thaw a readonly array by cloning it
*/
public final static <T> T[] arrayThaw(T[] a) { return a.clone(); }
/**
* <p> Cheat with phantom types. </p>
* <p> This method is announced with type String a -> Int -> a
* but it always returns a char.</p>
* <p> This is fine as long as nobody is able to actually create a
* value with type, say String Int. <br>
* This could be done only with another malicious native function, though.</p>
*/
public final static Object itemAt(final String value, final int offset) {
return value.charAt(offset);
}
/**
* <p> The empty polymorphic value of type StringJ a </p>
* <p> Referenced in frege.prelude.List.ListLike_StringJ
*/
final public static String emptyString = "";
/**
* <p> Run a IO action as main program. </p>
* *
* <p> Called from the java <tt>main</tt> method of a frege program.
* This converts the argument String array to a list and passes this to
* the compiled frege main function, if it is a function.
* The result is an IO action of type
* <tt>IO a</tt> to which then <tt>IO.performUnsafe</tt> is applied.
* The resulting {@link Lambda} then actually executes the frege code
* when evaluated.</p>
*
*/
public static java.lang.Integer runMain(final Object arg) {
java.lang.Integer xit = null;
// try {
// Object mainres = frege.runtime.Delayed.delayed(arg).call();
// mainres = frege.runtime.Delayed.<Object>forced(mainres);
// if (mainres instanceof java.lang.Integer) {
// xit = (java.lang.Integer)mainres;
// }
// else if (mainres instanceof java.lang.Boolean) {
// xit = (boolean)(java.lang.Boolean)mainres ? 0 : 1;
// }
// }
// catch (Exception ex) {
// throw new Error(ex); // ex.printStackTrace();
// }
// finally {
// // The following is needed to terminate a program that did forkIO
// frege.runtime.Concurrent.shutDownIfExists();
// stderr.get().flush();
// stdout.get().flush();
// }
return xit;
}
final public static void exit() {
// stdout.close();
// stderr.close();
}
/**
* set this if you need a different exit code
*/
private static volatile int exitCode = 0;
final public static void setExitCode(int a) {
synchronized (stdin) {
exitCode = a > exitCode && a < 256 ? a : exitCode;
}
}
}
| Frege/frege | frege/runtime/Runtime.java |
45,299 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.common;
import org.jboss.logging.Logger;
import org.keycloak.common.Profile.Feature.Type;
import org.keycloak.common.profile.ProfileConfigResolver;
import org.keycloak.common.profile.ProfileConfigResolver.FeatureConfig;
import org.keycloak.common.profile.ProfileException;
import org.keycloak.common.util.KerberosJdkProvider;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Profile {
private static volatile Map<String, TreeSet<Feature>> FEATURES;
public enum Feature {
AUTHORIZATION("Authorization Service", Type.DEFAULT),
ACCOUNT_API("Account Management REST API", Type.DEFAULT),
ACCOUNT3("Account Console version 3", Type.DEFAULT, Feature.ACCOUNT_API),
ADMIN_FINE_GRAINED_AUTHZ("Fine-Grained Admin Permissions", Type.PREVIEW),
ADMIN_API("Admin API", Type.DEFAULT),
ADMIN2("New Admin Console", Type.DEFAULT, Feature.ADMIN_API),
LOGIN2("New Login Theme", Type.EXPERIMENTAL),
DOCKER("Docker Registry protocol", Type.DISABLED_BY_DEFAULT),
IMPERSONATION("Ability for admins to impersonate users", Type.DEFAULT),
SCRIPTS("Write custom authenticators using JavaScript", Type.PREVIEW),
TOKEN_EXCHANGE("Token Exchange Service", Type.PREVIEW),
WEB_AUTHN("W3C Web Authentication (WebAuthn)", Type.DEFAULT),
CLIENT_POLICIES("Client configuration policies", Type.DEFAULT),
CIBA("OpenID Connect Client Initiated Backchannel Authentication (CIBA)", Type.DEFAULT),
PAR("OAuth 2.0 Pushed Authorization Requests (PAR)", Type.DEFAULT),
DYNAMIC_SCOPES("Dynamic OAuth 2.0 scopes", Type.EXPERIMENTAL),
CLIENT_SECRET_ROTATION("Client Secret Rotation", Type.PREVIEW),
STEP_UP_AUTHENTICATION("Step-up Authentication", Type.DEFAULT),
// Check if kerberos is available in underlying JVM and auto-detect if feature should be enabled or disabled by default based on that
KERBEROS("Kerberos", KerberosJdkProvider.getProvider().isKerberosAvailable() ? Type.DEFAULT : Type.DISABLED_BY_DEFAULT),
RECOVERY_CODES("Recovery codes", Type.PREVIEW),
UPDATE_EMAIL("Update Email Action", Type.PREVIEW),
JS_ADAPTER("Host keycloak.js and keycloak-authz.js through the Keycloak server", Type.DEFAULT),
FIPS("FIPS 140-2 mode", Type.DISABLED_BY_DEFAULT),
DPOP("OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer", Type.PREVIEW),
DEVICE_FLOW("OAuth 2.0 Device Authorization Grant", Type.DEFAULT),
TRANSIENT_USERS("Transient users for brokering", Type.EXPERIMENTAL),
MULTI_SITE("Multi-site support", Type.DISABLED_BY_DEFAULT),
CLIENT_TYPES("Client Types", Type.EXPERIMENTAL),
HOSTNAME_V1("Hostname Options V1", Type.DEPRECATED, 1),
HOSTNAME_V2("Hostname Options V2", Type.DEFAULT, 2),
PERSISTENT_USER_SESSIONS("Persistent online user sessions across restarts and upgrades", Type.PREVIEW),
OID4VC_VCI("Support for the OID4VCI protocol as part of OID4VC.", Type.EXPERIMENTAL),
DECLARATIVE_UI("declarative ui spi", Type.EXPERIMENTAL),
ORGANIZATION("Organization support within realms", Type.EXPERIMENTAL),
;
private final Type type;
private final String label;
private final String unversionedKey;
private final String key;
private Set<Feature> dependencies;
private int version;
Feature(String label, Type type, Feature... dependencies) {
this(label, type, 1, dependencies);
}
/**
* allowNameKey should be false for new versioned features to disallow using a legacy name, like account2
*/
Feature(String label, Type type, int version, Feature... dependencies) {
this.label = label;
this.type = type;
this.version = version;
this.key = name().toLowerCase().replaceAll("_", "-");
if (this.name().endsWith("_V" + version)) {
unversionedKey = key.substring(0, key.length() - (String.valueOf(version).length() + 2));
} else {
this.unversionedKey = key;
if (this.version > 1) {
throw new IllegalStateException("It is expected that the enum name ends with the version");
}
}
this.dependencies = Arrays.stream(dependencies).collect(Collectors.toSet());
}
/**
* Get the key that uniquely identifies this feature, may be used by users if
* allowNameKey is true.
* <p>
* {@link #getVersionedKey()} should instead be shown to users where possible.
*/
public String getKey() {
return key;
}
/**
* Return the key without any versioning. All features of the same type
* will share this key.
*/
public String getUnversionedKey() {
return unversionedKey;
}
/**
* Return the key in the form key:v{version}
*/
public String getVersionedKey() {
return getUnversionedKey() + ":v" + version;
}
public String getLabel() {
return label;
}
public Type getType() {
return type;
}
public Set<Feature> getDependencies() {
return dependencies;
}
public int getVersion() {
return version;
}
public enum Type {
// in priority order
DEFAULT("Default"),
DISABLED_BY_DEFAULT("Disabled by default"),
DEPRECATED("Deprecated"),
PREVIEW("Preview"),
PREVIEW_DISABLED_BY_DEFAULT("Preview disabled by default"), // Preview features, which are not automatically enabled even with enabled preview profile (Needs to be enabled explicitly)
EXPERIMENTAL("Experimental");
private final String label;
Type(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
}
private static final Set<String> ESSENTIAL_FEATURES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(Feature.HOSTNAME_V2.getUnversionedKey())));
private static final Logger logger = Logger.getLogger(Profile.class);
private static volatile Profile CURRENT;
private final ProfileName profileName;
private final Map<Feature, Boolean> features;
public static Profile defaults() {
return configure();
}
public static Profile configure(ProfileConfigResolver... resolvers) {
ProfileName profile = Arrays.stream(resolvers).map(ProfileConfigResolver::getProfileName).filter(Objects::nonNull).findFirst().orElse(ProfileName.DEFAULT);
Map<Feature, Boolean> features = new LinkedHashMap<>();
for (Map.Entry<String, TreeSet<Feature>> entry : getOrderedFeatures().entrySet()) {
// first check by unversioned key - if enabled, choose the highest priority feature
String unversionedFeature = entry.getKey();
ProfileConfigResolver.FeatureConfig unversionedConfig = getFeatureConfig(unversionedFeature, resolvers);
Feature enabledFeature = null;
if (unversionedConfig == FeatureConfig.ENABLED) {
enabledFeature = entry.getValue().iterator().next();
} else if (unversionedConfig == FeatureConfig.DISABLED && ESSENTIAL_FEATURES.contains(unversionedFeature)) {
throw new ProfileException(String.format("Feature %s cannot be disabled.", unversionedFeature));
}
// now check each feature version to ensure consistency and select any features enabled by default
boolean isExplicitlyEnabledFeature = false;
for (Feature f : entry.getValue()) {
ProfileConfigResolver.FeatureConfig configuration = getFeatureConfig(f.getVersionedKey(), resolvers);
if (configuration != FeatureConfig.UNCONFIGURED && unversionedConfig != FeatureConfig.UNCONFIGURED) {
throw new ProfileException("Versioned feature " + f.getVersionedKey() + " is not expected as " + unversionedFeature + " is already " + unversionedConfig.name().toLowerCase());
}
switch (configuration) {
case ENABLED:
if (isExplicitlyEnabledFeature) {
throw new ProfileException(
String.format("Multiple versions of the same feature %s, %s should not be enabled.",
enabledFeature.getVersionedKey(), f.getVersionedKey()));
}
// even if something else was enabled by default, explicitly enabling a lower priority feature takes precedence
enabledFeature = f;
isExplicitlyEnabledFeature = true;
break;
case DISABLED:
throw new ProfileException("Feature " + f.getVersionedKey() + " should not be disabled using a versioned key.");
default:
if (unversionedConfig == FeatureConfig.UNCONFIGURED && enabledFeature == null && isEnabledByDefault(profile, f)) {
enabledFeature = f;
}
break;
}
}
for (Feature f : entry.getValue()) {
features.put(f, f == enabledFeature);
}
}
verifyConfig(features);
CURRENT = new Profile(profile, features);
return CURRENT;
}
private static boolean isEnabledByDefault(ProfileName profile, Feature f) {
switch (f.getType()) {
case DEFAULT:
return true;
case PREVIEW:
return profile.equals(ProfileName.PREVIEW);
default:
return false;
}
}
private static ProfileConfigResolver.FeatureConfig getFeatureConfig(String feature,
ProfileConfigResolver... resolvers) {
ProfileConfigResolver.FeatureConfig configuration = Arrays.stream(resolvers).map(r -> r.getFeatureConfig(feature))
.filter(r -> !r.equals(ProfileConfigResolver.FeatureConfig.UNCONFIGURED))
.findFirst()
.orElse(ProfileConfigResolver.FeatureConfig.UNCONFIGURED);
return configuration;
}
/**
* Compute a map of unversioned feature keys to ordered sets (highest first) of features. The priority order for features is:
* <p>
* <ul>
* <li>The highest default supported version
* <li>The highest non-default supported version
* <li>The highest deprecated version
* <li>The highest preview version
* <li>The highest experimental version
* <ul>
* <p>
* Note the {@link Type} enum is ordered based upon priority.
*/
private static Map<String, TreeSet<Feature>> getOrderedFeatures() {
if (FEATURES == null) {
// "natural" ordering low to high between two features
Comparator<Feature> comparator = Comparator.comparing(Feature::getType).thenComparingInt(Feature::getVersion);
// aggregate the features by unversioned key
HashMap<String, TreeSet<Feature>> features = new HashMap<>();
Stream.of(Feature.values()).forEach(f -> features.compute(f.getUnversionedKey(), (k, v) -> {
if (v == null) {
v = new TreeSet<>(comparator.reversed()); // we want the highest priority first
}
v.add(f);
return v;
}));
FEATURES = features;
}
return FEATURES;
}
public static Set<String> getAllUnversionedFeatureNames() {
return Collections.unmodifiableSet(getOrderedFeatures().keySet());
}
public static Set<String> getDisableableUnversionedFeatureNames() {
return getOrderedFeatures().keySet().stream().filter(f -> !ESSENTIAL_FEATURES.contains(f)).collect(Collectors.toSet());
}
/**
* Get all of the feature versions for the given feature. They will be ordered by priority.
* <p>
* If the feature does not exist an empty collection will be returned.
*/
public static Set<Feature> getFeatureVersions(String feature) {
TreeSet<Feature> versions = getOrderedFeatures().get(feature);
if (versions == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(versions);
}
public static Profile init(ProfileName profileName, Map<Feature, Boolean> features) {
CURRENT = new Profile(profileName, features);
return CURRENT;
}
private Profile(ProfileName profileName, Map<Feature, Boolean> features) {
this.profileName = profileName;
this.features = Collections.unmodifiableMap(features);
logUnsupportedFeatures();
}
public static Profile getInstance() {
return CURRENT;
}
public static boolean isFeatureEnabled(Feature feature) {
return getInstance().features.get(feature);
}
public ProfileName getName() {
return profileName;
}
public Set<Feature> getAllFeatures() {
return features.keySet();
}
public Set<Feature> getDisabledFeatures() {
return features.entrySet().stream().filter(e -> !e.getValue()).map(Map.Entry::getKey).collect(Collectors.toSet());
}
/**
* @return all features of type "preview" or "preview_disabled_by_default"
*/
public Set<Feature> getPreviewFeatures() {
return Stream.concat(getFeatures(Feature.Type.PREVIEW).stream(), getFeatures(Feature.Type.PREVIEW_DISABLED_BY_DEFAULT).stream())
.collect(Collectors.toSet());
}
public Set<Feature> getExperimentalFeatures() {
return getFeatures(Feature.Type.EXPERIMENTAL);
}
public Set<Feature> getDeprecatedFeatures() {
return getFeatures(Feature.Type.DEPRECATED);
}
public Set<Feature> getFeatures(Feature.Type type) {
return features.keySet().stream().filter(f -> f.getType().equals(type)).collect(Collectors.toSet());
}
public Map<Feature, Boolean> getFeatures() {
return features;
}
public enum ProfileName {
DEFAULT,
PREVIEW
}
private static void verifyConfig(Map<Feature, Boolean> features) {
for (Feature f : features.keySet()) {
if (features.get(f) && f.getDependencies() != null) {
for (Feature d : f.getDependencies()) {
if (!features.get(d)) {
throw new ProfileException("Feature " + f.getKey() + " depends on disabled feature " + d.getKey());
}
}
}
}
}
private void logUnsupportedFeatures() {
logUnsupportedFeatures(Feature.Type.PREVIEW, getPreviewFeatures(), Logger.Level.INFO);
logUnsupportedFeatures(Feature.Type.EXPERIMENTAL, getExperimentalFeatures(), Logger.Level.WARN);
logUnsupportedFeatures(Feature.Type.DEPRECATED, getDeprecatedFeatures(), Logger.Level.WARN);
}
private void logUnsupportedFeatures(Feature.Type type, Set<Feature> checkedFeatures, Logger.Level level) {
Set<Feature.Type> checkedFeatureTypes = checkedFeatures.stream()
.map(Feature::getType)
.collect(Collectors.toSet());
String enabledFeaturesOfType = features.entrySet().stream()
.filter(e -> e.getValue() && checkedFeatureTypes.contains(e.getKey().getType()))
.map(e -> e.getKey().getVersionedKey()).sorted().collect(Collectors.joining(", "));
if (!enabledFeaturesOfType.isEmpty()) {
logger.logv(level, "{0} features enabled: {1}", type.getLabel(), enabledFeaturesOfType);
}
}
}
| keycloak/keycloak | common/src/main/java/org/keycloak/common/Profile.java |
45,300 | /**
* $Id: ProxyServlet.java,v 1.4 2013/12/13 13:18:11 david Exp $
* Copyright (c) 2011-2012, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.apphosting.api.DeadlineExceededException;
import com.mxgraph.online.Utils.UnsupportedContentException;
import com.mxgraph.online.Utils.SizeLimitExceededException;
/**
* Servlet implementation ProxyServlet
*/
@SuppressWarnings("serial")
public class ProxyServlet extends HttpServlet
{
private static final Logger log = Logger
.getLogger(HttpServlet.class.getName());
/**
* GAE deadline is 30 secs so timeout before that to avoid
* HardDeadlineExceeded errors.
*/
private static final int TIMEOUT = 29000;
/**
* A resuable empty byte array instance.
*/
private static byte[] emptyBytes = new byte[0];
public static boolean IS_GAE = (System.getProperty("com.google.appengine.runtime.version") == null) ? false : true;
/**
* @see HttpServlet#HttpServlet()
*/
public ProxyServlet()
{
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String urlParam = request.getParameter("url");
if (!"1".equals(System.getenv("ENABLE_DRAWIO_PROXY")))
{
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
else if (Utils.sanitizeUrl(urlParam))
{
// build the UML source from the compressed request parameter
String ref = request.getHeader("referer");
String ua = request.getHeader("User-Agent");
String auth = request.getHeader("Authorization");
String dom = getCorsDomain(ref, ua);
try(OutputStream out = response.getOutputStream())
{
if ("draw.io".equals(ua))
{
log.log(Level.SEVERE, "Infinite loop detected, proxy should not call itself");
throw new UnsupportedContentException();
}
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
URL url = new URL(urlParam);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
response.setHeader("Cache-Control", "private, max-age=86400");
// Workaround for 451 response from Iconfinder CDN
connection.setRequestProperty("User-Agent", "draw.io");
//Forward auth header (Only in GAE and not protected by AUTH itself)
if (IS_GAE && auth != null)
{
connection.setRequestProperty("Authorization", auth);
}
if (dom != null && dom.length() > 0)
{
response.addHeader("Access-Control-Allow-Origin", dom);
}
// Status code pass-through and follow redirects
if (connection instanceof HttpURLConnection)
{
((HttpURLConnection) connection)
.setInstanceFollowRedirects(false);
int status = ((HttpURLConnection) connection)
.getResponseCode();
int counter = 0;
// Follows a maximum of 6 redirects
while (counter++ <= 6 && (int)(status / 10) == 30) //Any redirect status 30x
{
String redirectUrl = connection.getHeaderField("Location");
if (!Utils.sanitizeUrl(redirectUrl))
{
break;
}
url = new URL(redirectUrl);
connection = url.openConnection();
((HttpURLConnection) connection)
.setInstanceFollowRedirects(false);
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
// Workaround for 451 response from Iconfinder CDN
connection.setRequestProperty("User-Agent", "draw.io");
status = ((HttpURLConnection) connection)
.getResponseCode();
}
if (status >= 200 && status <= 299)
{
response.setStatus(status);
String contentLength = connection.getHeaderField("Content-Length");
// If content length is available, use it to enforce maximum size
if (contentLength != null && Long.parseLong(contentLength) > Utils.MAX_SIZE)
{
throw new SizeLimitExceededException();
}
// Copies input stream to output stream
InputStream is = connection.getInputStream();
byte[] head = (contentAlwaysAllowed(urlParam)) ? emptyBytes
: Utils.checkStreamContent(is);
response.setContentType("application/octet-stream");
String base64 = request.getParameter("base64");
copyResponse(is, out, head,
base64 != null && base64.equals("1"));
}
else
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
}
else
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
out.flush();
log.log(Level.FINEST, "processed proxy request: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
}
catch (DeadlineExceededException e)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
catch (UnknownHostException | FileNotFoundException e)
{
// do not log 404 and DNS errors
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
catch (UnsupportedContentException e)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
log.log(Level.SEVERE, "proxy request with invalid content: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
}
catch (SizeLimitExceededException e)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
throw e;
}
catch (Exception e)
{
response.setStatus(
HttpServletResponse.SC_BAD_REQUEST);
log.log(Level.FINE, "proxy request failed: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
e.printStackTrace();
throw e;
}
}
else
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
log.log(Level.SEVERE,
"proxy request with invalid URL parameter: url="
+ ((urlParam != null) ? urlParam : "[null]"));
}
}
/**
* Dynamically generated CORS header for known domains.
* @throws IOException
*/
protected void copyResponse(InputStream is, OutputStream out, byte[] head,
boolean base64) throws IOException
{
if (base64)
{
int total = 0;
try (BufferedInputStream in = new BufferedInputStream(is,
Utils.IO_BUFFER_SIZE))
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
os.write(head, 0, head.length);
for (int len = is.read(buffer); len != -1; len = is.read(buffer))
{
total += len;
if (total > Utils.MAX_SIZE)
{
throw new SizeLimitExceededException();
}
os.write(buffer, 0, len);
}
out.write(mxBase64.encodeToString(os.toByteArray(), false).getBytes());
}
}
else
{
out.write(head);
Utils.copyRestricted(is, out);
}
}
/**
* Returns true if the content check should be omitted.
*/
public boolean contentAlwaysAllowed(String url)
{
return url.toLowerCase()
.startsWith("https://trello-attachments.s3.amazonaws.com/")
|| url.toLowerCase().startsWith("https://docs.google.com/");
}
/**
* Gets CORS header for request. Returning null means do not respond.
*/
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("^https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("^https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("^https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/ProxyServlet.java |
45,301 | H
1533502615
tags: Array, String, Backtracking, BFS, DFS, Hash Table
给一串string, start word, end word. 找到所有从 startWord -> endWord的最短路径list.
变化方式: mutate 1 letter at a time.
#### BFS + Reverse Search
- 用BFS找最短路径.
- 问题: how to effectively store the path, if the number of paths are really large?
- If we store Queue<List<String candidates>>: all possibilities will very large and not maintainable
- 用BFS做出一个反向structure, 然后再reverse search
##### BFS Prep Step
- BFS 找到所有start string 可以走到的地方 s, 放在一个overall structure里面: 注意, 存的方式 Map<s, list of sources>
- BFS时候每次都变化1step, 所以记录一次distance, 其实就是最短路径candidate (止步于此)
- 1. 反向mutation map: `destination/end string -> all source candidates` using queue: `Mutation Map`
- Mutation Map<s, List<possible src>>: list possible source strings to mutate into target key string.
- 2. 反向distance map: `destination/end string -> shortest distance to reach dest`
- Distance Map<s, possible/shortest distance>: shortest distance from to mutate into target key string.
- BFS prep step 并没解决问题, 甚至都没有用到end string. 我们要用BFS建成的反向mapping structure, 做search
##### Search using DFS
- 从结尾end string 开始扫, 找所有可以reach的candidate && only visit candidate that is 1 step away
- dfs 直到找到start string.
##### Bi-directional BFS: Search using BFS
- reversed structure 已经做好了, 现在做search 就可以: 也可以选用bfs.
- `Queue<List<String>>` to store candidates, searching from end-> start
```
/**
LeetCode: interface has List<string>, and input dict has to contain end word, but it does not contain start word.
Given two words (beginWord and endWord), and a dictionary's word list,
find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
*/
// 69%
/*
- Distance Map<s, possible/shortest distance>: shortest distance from to mutate into target key string.
- Mutation Map<s, List<possible src>>: list possible source strings to mutate into target key string.
*/
/*
- Distance Map<s, possible/shortest distance>: shortest distance from to mutate into target key string.
- Mutation Map<s, List<possible src>>: list possible source strings to mutate into target key string.
*/
// Bi-directional search
class Solution {
Set<String> dict;
Map<String, List<String>> mutation = new HashMap<>();
Map<String, Integer> distance = new HashMap<>();
public List<List<String>> findLadders(String start, String end, List<String> wordList) {
List<List<String>> rst = new ArrayList<>();
dict = new HashSet<>(wordList);
if (!dict.contains(end)) return rst;
prep(start);
//dfs(start, end, new ArrayList<>(), rst); // option1
bfs(start, end, rst); // option2
return rst;
}
//BFS/Prep to populate mutation and distance map.
public void prep(String start) {
//Init
Queue<String> queue = new LinkedList<>();
dict.add(start);
queue.offer(start);
distance.put(start, 0);
for (String s : dict) {
mutation.put(s, new ArrayList<>());
}
// process queue
while(!queue.isEmpty()) {
String str = queue.poll();
List<String> list = transform(str);
for (String s : list) {
mutation.get(s).add(str);
if (!distance.containsKey(s)) { // only record dist->s once, as shortest
distance.put(s, distance.get(str) + 1);
queue.offer(s);
}
}
}
}
// Option2: bfs, bi-directional search
public void bfs(String start, String end, List<List<String>> rst) {
Queue<List<String>> queue = new LinkedList<>();
List<String> list = new ArrayList<>();
list.add(end);
queue.offer(new ArrayList<>(list));
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
list = queue.poll();
String str = list.get(0);
for (String s : mutation.get(str)) {//All prior-mutation sources
list.add(0, s);
if (s.equals(start)) {
rst.add(new ArrayList<>(list));
} else if (distance.containsKey(s) && distance.get(str) - 1 == distance.get(s)) {
//Only pick those that's 1 step away: keep minimum steps for optimal solution
queue.offer(new ArrayList<>(list));
}
list.remove(0);
}
size--;
}
}
}
// Option1: DFS to trace back from end string to start string. If reach start string, save result.
// Use distance<s, distance> to make sure only trace to 1-unit distance candidate
public void dfs(String start, String str, List<String> path, List<List<String>> rst) {
path.add(0, str);
if (str.equals(start)) {
rst.add(new ArrayList<String>(path));
path.remove(0);
return;
}
//Trace 1 step towards start via dfs
for (String s : mutation.get(str)) {//All prior-mutation sources
//Only pick those that's 1 step away: keep minimum steps for optimal solution
if (distance.containsKey(s) && distance.get(str) - 1 == distance.get(s)) {
dfs(start, s, path, rst);
}
}
path.remove(0);
}
//Generate all possible mutations for word. Check against dic and skip word itself.
private List<String> transform(String word) {
List<String> candidates = new ArrayList<>();
StringBuffer sb = new StringBuffer(word);
for (int i = 0; i < sb.length(); i++) {
char temp = sb.charAt(i);
for (char c = 'a'; c <= 'z'; c++) {
if (temp == c) continue;
sb.setCharAt(i, c);
String newWord = sb.toString();
if (dict.contains(newWord)) {
candidates.add(newWord);
}
}
sb.setCharAt(i, temp);//backtrack
}
return candidates;
}
}
/*
LintCode: interface has Set<String>, also, input dict does not contain end word.
Given two words (start and end), and a dictionary,
find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note
All words have the same length.
All words contain only lowercase alphabetic characters.
Tags Expand
Backtracking Depth First Search Breadth First Search
Attempt1 is by me: however it exceeds time/memory limit.
Some other good sources can be found online:
//http://www.jiuzhang.com/solutions/word-ladder-ii/
//http://www.cnblogs.com/shawnhue/archive/2013/06/05/leetcode_126.html
Adjacency List, Prefix ... etc. Let's look at them one after another. First get it through with a NineChapter solution
*/
//Attempt2: Use Nine Chapter solution, BFS + DFS. It works, very nicely, using backtracking.
/*
BFS:
1. For all mutations in dict, create pastMap: all possible mutations that can turn into each particular str in dict.
2. For all mutations in dict, create distance: distance to start point.
DFS:
3. Find minimum path by checking distance different of just 1. Use a List<String> to do DFS
Note:
Map uses containsKey. Set uses contains
In DFS, add new copy: new ArrayList<String>(path)
BFS: queue, while loop
DFS: recursion, with a structure to go deeper, remember to add/remove element when passing alone
*/
public class Solution {
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> rst = new ArrayList<List<String>>();
Map<String, ArrayList<String>> pastMap = new HashMap<String, ArrayList<String>>();
Map<String, Integer> distance = new HashMap<String, Integer>();
Queue<String> queue = new LinkedList<String>();
//Initiate the variables
dict.add(start);
dict.add(end);
queue.offer(start);
distance.put(start, 0);
for (String s : dict) {
pastMap.put(s, new ArrayList<String>());
}
//BFS
BFS(start, end, distance, pastMap, dict, queue);
//DFS
ArrayList<String> path = new ArrayList<String>();
DFS(start, end, distance, pastMap, path, rst);
return rst;
}
//BFS to populate map and distance:
//Distance: distance from each str in dict, to the starting point.
//Map: all possible ways to mutate into each str in dict.
public void BFS(String start, String end, Map<String, Integer> distance, Map<String, ArrayList<String>> pastMap, Set<String> dict, Queue<String> queue) {
while(!queue.isEmpty()) {
String str = queue.poll();
List<String> list = expand(str, dict);
for (String s : list) {
pastMap.get(s).add(str);
if (!distance.containsKey(s)) {
distance.put(s, distance.get(str) + 1);
queue.offer(s);
}
}
}
}
//DFS on the map, where map is the all possible ways to mutate into a particular str. Backtracking from end to start
public void DFS(String start, String str, Map<String, Integer> distance, Map<String, ArrayList<String>> pastMap, ArrayList<String> path, List<List<String>> rst) {
path.add(str);
if (str.equals(start)) {
Collections.reverse(path);
rst.add(new ArrayList<String>(path));
Collections.reverse(path);
} else {//next step, trace 1 step towards start
for (String s : pastMap.get(str)) {//All previous-mutation options that we have with str:
if (distance.containsKey(s) && distance.get(str) == distance.get(s) + 1) {//Only pick those that's 1 step away: keep minimum steps for optimal solution
DFS(start, s, distance, pastMap, path, rst);
}
}
}
path.remove(path.size() - 1);
}
//Populate all possible mutations for particular str, skipping the case that mutates back to itself.
public ArrayList<String> expand(String str, Set<String> dict) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {//Alternate each letter position
for (int j = 0; j < 26; j++) {//Alter 26 letters
if (str.charAt(i) != (char)('a' + j)) {
String newStr = str.substring(0, i) + (char)('a' + j) + str.substring(i + 1);
if (dict.contains(newStr)) {
list.add(newStr);
}
}
}
}
return list;
}
}
//Attempt1: probably works, however:
//Testing against input: "qa", "sq", ["si","go","se","cm","so","ph","mt","db","mb","sb","kr","ln","tm","le","av","sm","ar","ci","ca","br","ti","ba","to","ra","fa","yo","ow","sn","ya","cr","po","fe","ho","ma","re","or","rn","au","ur","rh","sr","tc","lt","lo","as","fr","nb","yb","if","pb","ge","th","pm","rb","sh","co","ga","li","ha","hz","no","bi","di","hi","qa","pi","os","uh","wm","an","me","mo","na","la","st","er","sc","ne","mn","mi","am","ex","pt","io","be","fm","ta","tb","ni","mr","pa","he","lr","sq","ye"]
//0. Could be backtrackList exceed memory limit.
//1. If use HashSet<String> set to check if particular sequence exist, then exceed memory
//2. If use StringBuffer strCheck to check if particular sequence exist, then exceed time limit.
//It looks like we'd use DFS for final results.
public class Solution {
private Queue<String> q = new LinkedList<String>();
private Queue<ArrayList<String>> backtrackList = new LinkedList<ArrayList<String>>();
private Set<String> dict;
private String end;
private int level = 1;
private int len = Integer.MAX_VALUE;
private List<List<String>> rst = new ArrayList<List<String>>();
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
if (start == null || end == null || dict == null || start.length() != end.length()) {
return rst;
}
this.dict = dict;
this.end = end;
ArrayList<String> head = new ArrayList<String>();
head.add(start);
q.offer(start);
backtrackList.offer(head);
while(!q.isEmpty()) {//BFS
int size = q.size();//Fix size
level++;
for (int k = 0; k < size; k++) {//LOOP through existing queue: for this specific level
String str = q.poll();
ArrayList<String> list = backtrackList.poll();
validateMutations(str, list);
}//END FOR K
}//END WHILE
List<List<String>> minRst = new ArrayList<List<String>>();
for (int i = 0; i < rst.size(); i++) {
if (rst.get(i).size() == len) {
minRst.add(rst.get(i));
}
}
return minRst;
}
public void validateMutations(String str, ArrayList<String> list) {
if (list.size() > len) {//No need to digger further if list is already greater than min length
return;
}
for (int i = 0; i < str.length(); i++) {//Alternate each letter position
for (int j = 0; j < 26; j++) {//Alter 26 letters
if (str.charAt(i) == (char)('a' + j)) {
continue;
}
String newStr = str.substring(0, i) + (char)('a' + j) + str.substring(i + 1);
ArrayList<String> temp = (ArrayList<String>)list.clone();
temp.add(newStr);
if (dict.contains(newStr)) {
if (newStr.equals(end)) {//Found end
len = Math.min(len, level);
rst.add(temp);
} else {
q.offer(newStr);
backtrackList.offer(temp);
}
}
}//END FOR J
}//END FOR I
}
}
``` | awangdev/leet-code | Java/Word Ladder II.java |
45,302 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AnimatedFloat;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CheckBox2;
import org.telegram.ui.Components.CounterView;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.Premium.PremiumGradient;
public class HintDialogCell extends FrameLayout {
private BackupImageView imageView;
private TextView nameTextView;
private AvatarDrawable avatarDrawable = new AvatarDrawable();
private RectF rect = new RectF();
private Theme.ResourcesProvider resourcesProvider;
private int lastUnreadCount;
private TLRPC.User currentUser;
private long dialogId;
private int currentAccount = UserConfig.selectedAccount;
float showOnlineProgress;
boolean wasDraw;
CounterView counterView;
CheckBox2 checkBox;
private final boolean drawCheckbox;
private final AnimatedFloat premiumBlockedT = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
private boolean showPremiumBlocked;
private boolean premiumBlocked;
public boolean isBlocked() {
return premiumBlocked;
}
public HintDialogCell(Context context, boolean drawCheckbox, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.drawCheckbox = drawCheckbox;
imageView = new BackupImageView(context);
imageView.setRoundRadius(AndroidUtilities.dp(27));
addView(imageView, LayoutHelper.createFrame(54, 54, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 7, 0, 0));
nameTextView = new TextView(context) {
@Override
public void setText(CharSequence text, BufferType type) {
text = Emoji.replaceEmoji(text, getPaint().getFontMetricsInt(), AndroidUtilities.dp(10), false);
super.setText(text, type);
}
};
NotificationCenter.listenEmojiLoading(nameTextView);
nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setMaxLines(1);
nameTextView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
nameTextView.setLines(1);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 6, 64, 6, 0));
counterView = new CounterView(context, resourcesProvider);
addView(counterView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP,0 ,4,0,0));
counterView.setColors(Theme.key_chats_unreadCounterText, Theme.key_chats_unreadCounter);
counterView.setGravity(Gravity.RIGHT);
if (drawCheckbox) {
checkBox = new CheckBox2(context, 21, resourcesProvider);
checkBox.setColor(Theme.key_dialogRoundCheckBox, Theme.key_dialogBackground, Theme.key_dialogRoundCheckBoxCheck);
checkBox.setDrawUnchecked(false);
checkBox.setDrawBackgroundAsArc(4);
checkBox.setProgressDelegate(progress -> {
float scale = 1.0f - (1.0f - 0.857f) * checkBox.getProgress();
imageView.setScaleX(scale);
imageView.setScaleY(scale);
invalidate();
});
addView(checkBox, LayoutHelper.createFrame(24, 24, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 19, 42, 0, 0));
checkBox.setChecked(false, false);
setWillNotDraw(false);
}
}
public void showPremiumBlocked() {
if (showPremiumBlocked) return;
showPremiumBlocked = true;
NotificationCenter.getInstance(currentAccount).listen(this, NotificationCenter.userIsPremiumBlockedUpadted, args -> {
updatePremiumBlocked(true);
});
}
private void updatePremiumBlocked(boolean animated) {
final boolean wasPremiumBlocked =premiumBlocked;
premiumBlocked = showPremiumBlocked && currentUser != null && MessagesController.getInstance(currentAccount).isUserPremiumBlocked(currentUser.id);
if (wasPremiumBlocked != premiumBlocked) {
if (!animated) {
premiumBlockedT.set(premiumBlocked, true);
}
invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(86), MeasureSpec.EXACTLY));
counterView.counterDrawable.horizontalPadding = AndroidUtilities.dp(13);
}
public void update(int mask) {
if ((mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
if (currentUser != null) {
currentUser = MessagesController.getInstance(currentAccount).getUser(currentUser.id);
imageView.invalidate();
invalidate();
}
}
if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
return;
}
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId);
if (dialog != null && dialog.unread_count != 0) {
if (lastUnreadCount != dialog.unread_count) {
lastUnreadCount = dialog.unread_count;
counterView.setCount(lastUnreadCount, wasDraw);
}
} else {
lastUnreadCount = 0;
counterView.setCount(0, wasDraw);
}
}
public void update() {
if (DialogObject.isUserDialog(dialogId)) {
currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId);
avatarDrawable.setInfo(currentAccount, currentUser);
} else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
avatarDrawable.setInfo(currentAccount, chat);
currentUser = null;
}
updatePremiumBlocked(true);
}
public void setColors(int textColorKey, int backgroundColorKey) {
nameTextView.setTextColor(Theme.getColor(textColorKey, resourcesProvider));
this.backgroundColorKey = backgroundColorKey;
checkBox.setColor(Theme.key_dialogRoundCheckBox, backgroundColorKey, Theme.key_dialogRoundCheckBoxCheck);
}
public void setDialog(long uid, boolean counter, CharSequence name) {
if (dialogId != uid) {
wasDraw = false;
invalidate();
}
dialogId = uid;
if (DialogObject.isUserDialog(uid)) {
currentUser = MessagesController.getInstance(currentAccount).getUser(uid);
if (name != null) {
nameTextView.setText(name);
} else if (currentUser != null) {
nameTextView.setText(UserObject.getFirstName(currentUser));
} else {
nameTextView.setText("");
}
avatarDrawable.setInfo(currentAccount, currentUser);
imageView.setForUserOrChat(currentUser, avatarDrawable);
} else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-uid);
if (name != null) {
nameTextView.setText(name);
} else if (chat != null) {
nameTextView.setText(chat.title);
} else {
nameTextView.setText("");
}
avatarDrawable.setInfo(currentAccount, chat);
currentUser = null;
imageView.setForUserOrChat(chat, avatarDrawable);
}
updatePremiumBlocked(false);
if (counter) {
update(0);
}
}
private int backgroundColorKey = Theme.key_windowBackgroundWhite;
private PremiumGradient.PremiumGradientTools premiumGradient;
private Drawable lockDrawable;
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == imageView) {
boolean showOnline = !premiumBlocked && currentUser != null && !currentUser.bot && (currentUser.status != null && currentUser.status.expires > ConnectionsManager.getInstance(currentAccount).getCurrentTime() || MessagesController.getInstance(currentAccount).onlinePrivacy.containsKey(currentUser.id));
if (!wasDraw) {
showOnlineProgress = showOnline ? 1f : 0f;
}
if (showOnline && showOnlineProgress != 1f) {
showOnlineProgress += 16f / 150;
if (showOnlineProgress > 1) {
showOnlineProgress = 1f;
}
invalidate();
} else if (!showOnline && showOnlineProgress != 0) {
showOnlineProgress -= 16f / 150;
if (showOnlineProgress < 0) {
showOnlineProgress = 0;
}
invalidate();
}
final float lockT = premiumBlockedT.set(premiumBlocked);
if (lockT > 0) {
float top = child.getY() + child.getHeight() / 2f + dp(18);
float left = child.getX() + child.getWidth() / 2f + dp(18);
canvas.save();
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(backgroundColorKey, resourcesProvider));
canvas.drawCircle(left, top, dp(10 + 1.33f) * lockT, Theme.dialogs_onlineCirclePaint);
if (premiumGradient == null) {
premiumGradient = new PremiumGradient.PremiumGradientTools(Theme.key_premiumGradient1, Theme.key_premiumGradient2, -1, -1, -1, resourcesProvider);
}
premiumGradient.gradientMatrix((int) (left - dp(10)), (int) (top - dp(10)), (int) (left + dp(10)), (int) (top + dp(10)), 0, 0);
canvas.drawCircle(left, top, dp(10) * lockT, premiumGradient.paint);
if (lockDrawable == null) {
lockDrawable = getContext().getResources().getDrawable(R.drawable.msg_mini_lock2).mutate();
lockDrawable.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN));
}
lockDrawable.setBounds(
(int) (left - lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT),
(int) (top - lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT),
(int) (left + lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT),
(int) (top + lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT)
);
lockDrawable.setAlpha((int) (0xFF * lockT));
lockDrawable.draw(canvas);
canvas.restore();
} else if (showOnlineProgress != 0) {
int top = AndroidUtilities.dp(53);
int left = AndroidUtilities.dp(59);
canvas.save();
canvas.scale(showOnlineProgress, showOnlineProgress, left, top);
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(backgroundColorKey));
canvas.drawCircle(left, top, AndroidUtilities.dp(7), Theme.dialogs_onlineCirclePaint);
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle));
canvas.drawCircle(left, top, AndroidUtilities.dp(5), Theme.dialogs_onlineCirclePaint);
canvas.restore();
}
wasDraw = true;
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
if (drawCheckbox) {
int cx = imageView.getLeft() + imageView.getMeasuredWidth() / 2;
int cy = imageView.getTop() + imageView.getMeasuredHeight() / 2;
Theme.checkboxSquare_checkPaint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBox));
Theme.checkboxSquare_checkPaint.setAlpha((int) (checkBox.getProgress() * 255));
canvas.drawCircle(cx, cy, AndroidUtilities.dp(28), Theme.checkboxSquare_checkPaint);
}
}
public void setChecked(boolean checked, boolean animated) {
if (drawCheckbox) {
checkBox.setChecked(checked, animated);
}
}
public long getDialogId() {
return dialogId;
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java |
45,303 | 404: Not Found | sohutv/cachecloud | cachecloud-web/src/main/java/com/sohu/cache/dao/AppDao.java |
45,304 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.vaticle.typedb.core.query;
import com.vaticle.typedb.common.collection.Either;
import com.vaticle.typedb.core.common.exception.TypeDBCheckedException;
import com.vaticle.typedb.core.common.exception.TypeDBException;
import com.vaticle.typedb.core.common.iterator.FunctionalIterator;
import com.vaticle.typedb.core.common.parameters.Context;
import com.vaticle.typedb.core.concept.ConceptManager;
import com.vaticle.typedb.core.concept.answer.ConceptMap;
import com.vaticle.typedb.core.concept.answer.ConceptMapGroup;
import com.vaticle.typedb.core.concept.answer.ValueGroup;
import com.vaticle.typedb.core.concept.thing.Attribute;
import com.vaticle.typedb.core.concept.value.Value;
import com.vaticle.typedb.core.concept.value.impl.ValueImpl;
import com.vaticle.typedb.core.pattern.Disjunction;
import com.vaticle.typedb.core.reasoner.Reasoner;
import com.vaticle.typedb.core.traversal.common.Identifier;
import com.vaticle.typeql.lang.common.TypeQLToken;
import com.vaticle.typeql.lang.common.TypeQLVariable;
import com.vaticle.typeql.lang.query.TypeQLGet;
import com.vaticle.typeql.lang.query.TypeQLQuery;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static com.vaticle.typedb.common.collection.Collections.set;
import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.ILLEGAL_OPERATION;
import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE;
import static com.vaticle.typedb.core.common.exception.ErrorMessage.Internal.UNRECOGNISED_VALUE;
import static com.vaticle.typedb.core.common.exception.ErrorMessage.ThingRead.AGGREGATE_ATTRIBUTE_NOT_NUMBER;
import static com.vaticle.typedb.core.common.iterator.Iterators.iterate;
import static com.vaticle.typedb.core.common.parameters.Arguments.Query.Producer.EXHAUSTIVE;
import static com.vaticle.typedb.core.query.Getter.Aggregator.aggregator;
import static java.lang.Math.sqrt;
import static java.util.stream.Collectors.groupingBy;
public class Getter {
private final Reasoner reasoner;
private final TypeQLQuery.MatchClause match;
private final List<Identifier.Variable.Name> filter;
private final TypeQLQuery.Modifiers modifiers;
private final Disjunction disjunction;
private final Context.Query context;
public Getter(Reasoner reasoner, ConceptManager conceptMgr, TypeQLGet query) {
this(reasoner, conceptMgr, query, null);
}
public Getter(Reasoner reasoner, ConceptManager conceptMgr, TypeQLGet query, Context.Query context) {
this.reasoner = reasoner;
this.match = query.match();
this.modifiers = query.modifiers();
this.filter = iterate(query.effectiveFilter()).map(v -> Identifier.Variable.of(v.reference().asName())).toList();
if (this.modifiers.sort().isPresent()) {
iterate(modifiers.sort().get().variables()).map(v -> Identifier.Variable.of(v.reference().asName()))
.forEachRemaining(filter::add);
}
this.disjunction = Disjunction.create(query.match().conjunction().normalise());
this.context = context;
iterate(disjunction.conjunctions())
.flatMap(c -> iterate(c.variables())).flatMap(v -> iterate(v.constraints()))
.filter(c -> c.isType() && c.asType().isLabel() && c.asType().asLabel().properLabel().scope().isPresent())
// only validate labels that are used outside of relation constraints - this allows role type aliases in relations
.filter(label -> label.owner().constraining().isEmpty() || iterate(label.owner().constraining()).anyMatch(c -> !(c.isThing() && c.asThing().isRelation())))
.forEachRemaining(c -> conceptMgr.validateNotRoleTypeAlias(c.asType().asLabel().properLabel()));
}
public static Getter create(Reasoner reasoner, ConceptManager conceptMgr, TypeQLGet query) {
return new Getter(reasoner, conceptMgr, query);
}
public static Getter create(Reasoner reasoner, ConceptManager conceptMgr, TypeQLGet query, Context.Query context) {
return new Getter(reasoner, conceptMgr, query, context);
}
public static Getter.Aggregator create(Reasoner reasoner, ConceptManager conceptMgr,
TypeQLGet.Aggregate query, Context.Query context) {
Getter getter = new Getter(reasoner, conceptMgr, query.get());
return new Aggregator(getter, query, conceptMgr, context);
}
public static Getter.Group create(Reasoner reasoner, ConceptManager conceptMgr, TypeQLGet.Group query, Context.Query context) {
Getter getter = new Getter(reasoner, conceptMgr, query.get());
return new Group(getter, query, context);
}
public static Getter.Group.Aggregator create(Reasoner reasoner, ConceptManager conceptMgr,
TypeQLGet.Group.Aggregate query, Context.Query context) {
Getter getter = new Getter(reasoner, conceptMgr, query.group().get());
Group group = new Group(getter, query.group(), context);
return new Group.Aggregator(conceptMgr, group, query);
}
public Disjunction disjunction() {
return disjunction;
}
public FunctionalIterator<? extends ConceptMap> execute() {
return execute(context);
}
public FunctionalIterator<? extends ConceptMap> execute(Context.Query context) {
return execute(ConceptMap.EMPTY, context);
}
FunctionalIterator<? extends ConceptMap> execute(ConceptMap bindings, Context.Query context) {
return reasoner.execute(disjunction, filter, modifiers, context, bindings);
}
public static class Aggregator {
private final Getter getter;
private final ConceptManager conceptMgr;
private final TypeQLGet.Aggregate query;
private final Context.Query context;
public Aggregator(Getter getter, TypeQLGet.Aggregate query, ConceptManager conceptMgr, Context.Query context) {
this.getter = getter;
this.query = query;
this.conceptMgr = conceptMgr;
this.context = context;
this.context.producer(Either.first(EXHAUSTIVE));
}
public Getter getter() {
return getter;
}
public Optional<Value<?>> execute() {
return execute(ConceptMap.EMPTY);
}
public Optional<Value<?>> execute(ConceptMap bindings) {
FunctionalIterator<? extends ConceptMap> answers = getter.execute(bindings, context);
TypeQLToken.Aggregate.Method method = query.method();
TypeQLVariable var = query.var();
return aggregate(conceptMgr, answers, method, var);
}
static Optional<Value<?>> aggregate(ConceptManager conceptMgr, FunctionalIterator<? extends ConceptMap> answers,
TypeQLToken.Aggregate.Method method, TypeQLVariable var) {
return answers.stream().collect(aggregator(conceptMgr, method, var));
}
static Value<?> getValue(ConceptManager conceptMgr, ConceptMap answer, TypeQLVariable var) {
if (var.reference().isNameConcept()) {
Attribute attribute = answer.get(var).asAttribute();
if (attribute.isLong()) return createValue(conceptMgr, attribute.asLong().getValue());
else if (attribute.isDouble()) return createValue(conceptMgr, attribute.asDouble().getValue());
else throw TypeDBException.of(AGGREGATE_ATTRIBUTE_NOT_NUMBER, var);
} else if (var.reference().isNameValue()) {
return answer.get(var).asValue();
} else throw TypeDBException.of(ILLEGAL_STATE);
}
static Value<Long> createValue(ConceptManager conceptMgr, long value) {
try {
return ValueImpl.of(conceptMgr, value);
} catch (TypeDBCheckedException e) {
throw e.toUnchecked();
}
}
static Value<Double> createValue(ConceptManager conceptMgr, double value) {
try {
return ValueImpl.of(conceptMgr, value);
} catch (TypeDBCheckedException e) {
throw e.toUnchecked();
}
}
private static Value<?> sumValue(ConceptManager conceptMgr, Value<?> x, Value<?> y) {
// This method is necessary because Number doesn't support '+' because java!
if (x.isLong() && y.isLong()) return createValue(conceptMgr, x.asLong().value() + y.asLong().value());
else if (x.isLong()) return createValue(conceptMgr, x.asLong().value() + y.asDouble().value());
else if (y.isLong()) return createValue(conceptMgr, x.asDouble().value() + y.asLong().value());
else return createValue(conceptMgr, x.asDouble().value() + y.asDouble().value());
}
static Collector<ConceptMap, ?, Optional<Value<?>>> aggregator(ConceptManager conceptMgr, TypeQLToken.Aggregate.Method method, TypeQLVariable var) {
Collector<ConceptMap, ?, Optional<Value<?>>> aggregator;
switch (method) {
case COUNT:
aggregator = count(conceptMgr);
break;
case MAX:
aggregator = max(conceptMgr, var);
break;
case MEAN:
aggregator = mean(conceptMgr, var);
break;
case MEDIAN:
aggregator = median(conceptMgr, var);
break;
case MIN:
aggregator = min(conceptMgr, var);
break;
case STD:
aggregator = std(conceptMgr, var);
break;
case SUM:
aggregator = sum(conceptMgr, var);
break;
default:
throw TypeDBException.of(UNRECOGNISED_VALUE);
}
return aggregator;
}
static Collector<ConceptMap, ?, Optional<Value<?>>> count(ConceptManager conceptMgr) {
return new Collector<ConceptMap, Accumulator<Long>, Optional<Value<?>>>() {
@Override
public Supplier<Accumulator<Long>> supplier() {
return () -> new Accumulator<>(0L, Long::sum);
}
@Override
public BiConsumer<Accumulator<Long>, ConceptMap> accumulator() {
return (sum, answer) -> sum.accept(1L);
}
@Override
public BinaryOperator<Accumulator<Long>> combiner() {
return (sum1, sum2) -> {
sum1.accept(sum2.value);
return sum1;
};
}
@Override
public Function<Accumulator<Long>, Optional<Value<?>>> finisher() {
return sum -> Optional.of(createValue(conceptMgr, sum.value));
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> max(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, OptionalAccumulator<Value<?>>, Optional<Value<?>>>() {
@Override
public Supplier<OptionalAccumulator<Value<?>>> supplier() {
return () -> new OptionalAccumulator<>(BinaryOperator.maxBy(NumericComparator.natural()));
}
@Override
public BiConsumer<OptionalAccumulator<Value<?>>, ConceptMap> accumulator() {
return (max, answer) -> max.accept(getValue(conceptMgr, answer, var));
}
@Override
public BinaryOperator<OptionalAccumulator<Value<?>>> combiner() {
return (max1, max2) -> {
if (max2.present) max1.accept(max2.value);
return max1;
};
}
@Override
public Function<OptionalAccumulator<Value<?>>, Optional<Value<?>>> finisher() {
return max -> {
if (max.present) return Optional.of(max.value);
else return Optional.empty();
};
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> mean(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, Double[], Optional<Value<?>>>() {
@Override
public Supplier<Double[]> supplier() {
return () -> new Double[]{0.0, 0.0};
}
@Override
public BiConsumer<Double[], ConceptMap> accumulator() {
return (acc, answer) -> {
Value<?> value = getValue(conceptMgr, answer, var);
if (value.isDouble()) acc[0] += value.asDouble().value();
else if (value.isLong()) acc[0] += value.asLong().value();
else throw TypeDBException.of(ILLEGAL_STATE);
acc[1]++;
};
}
@Override
public BinaryOperator<Double[]> combiner() {
return (acc1, acc2) -> {
acc1[0] += acc2[0];
acc1[1] += acc2[1];
return acc1;
};
}
@Override
public Function<Double[], Optional<Value<?>>> finisher() {
return acc -> {
if (acc[1] == 0) return Optional.empty();
else return Optional.of(createValue(conceptMgr, acc[0] / acc[1]));
};
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> median(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, MedianCalculator, Optional<Value<?>>>() {
@Override
public Supplier<MedianCalculator> supplier() {
return MedianCalculator::new;
}
@Override
public BiConsumer<MedianCalculator, ConceptMap> accumulator() {
return (medianFinder, answer) -> medianFinder.accumulate(getValue(conceptMgr, answer, var));
}
@Override
public BinaryOperator<MedianCalculator> combiner() {
return (t, u) -> {
throw TypeDBException.of(ILLEGAL_OPERATION);
};
}
@Override
public Function<MedianCalculator, Optional<Value<?>>> finisher() {
return medianCalculator -> medianCalculator.median(conceptMgr);
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> min(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, OptionalAccumulator<Value<?>>, Optional<Value<?>>>() {
@Override
public Supplier<OptionalAccumulator<Value<?>>> supplier() {
return () -> new OptionalAccumulator<>(BinaryOperator.minBy(NumericComparator.natural()));
}
@Override
public BiConsumer<OptionalAccumulator<Value<?>>, ConceptMap> accumulator() {
return (min, answer) -> min.accept(getValue(conceptMgr, answer, var));
}
@Override
public BinaryOperator<OptionalAccumulator<Value<?>>> combiner() {
return (min1, min2) -> {
if (min2.present) min1.accept(min2.value);
return min1;
};
}
@Override
public Function<OptionalAccumulator<Value<?>>, Optional<Value<?>>> finisher() {
return min -> {
if (min.present) return Optional.of(min.value);
else return Optional.empty();
};
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> std(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, STDCalculator, Optional<Value<?>>>() {
@Override
public Supplier<STDCalculator> supplier() {
return () -> new STDCalculator(conceptMgr);
}
@Override
public BiConsumer<STDCalculator, ConceptMap> accumulator() {
return (acc, answer) -> {
Value<?> value = getValue(conceptMgr, answer, var);
if (value.isDouble()) acc.accumulate(value.asDouble().value());
else if (value.isLong()) acc.accumulate(value.asLong().value());
else throw TypeDBException.of(ILLEGAL_STATE);
};
}
@Override
public BinaryOperator<STDCalculator> combiner() {
return (t, u) -> {
throw TypeDBException.of(ILLEGAL_OPERATION);
};
}
@Override
public Function<STDCalculator, Optional<Value<?>>> finisher() {
return STDCalculator::std;
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
static Collector<ConceptMap, ?, Optional<Value<?>>> sum(ConceptManager conceptMgr, TypeQLVariable var) {
return new Collector<ConceptMap, OptionalAccumulator<Value<?>>, Optional<Value<?>>>() {
@Override
public Supplier<OptionalAccumulator<Value<?>>> supplier() {
return () -> new OptionalAccumulator<>((a, b) -> sumValue(conceptMgr, a, b));
}
@Override
public BiConsumer<OptionalAccumulator<Value<?>>, ConceptMap> accumulator() {
return (sum, answer) -> sum.accept(getValue(conceptMgr, answer, var));
}
@Override
public BinaryOperator<OptionalAccumulator<Value<?>>> combiner() {
return (sum1, sum2) -> {
if (sum2.present) sum1.accept(sum2.value);
return sum1;
};
}
@Override
public Function<OptionalAccumulator<Value<?>>, Optional<Value<?>>> finisher() {
return sum -> {
if (sum.present) return Optional.of(sum.value);
else return Optional.empty();
};
}
@Override
public Set<Characteristics> characteristics() {
return set();
}
};
}
private static class MedianCalculator {
PriorityQueue<Value<?>> maxHeap; //lower half
PriorityQueue<Value<?>> minHeap; //higher half
MedianCalculator() {
maxHeap = new PriorityQueue<>(NumericComparator.natural().reversed());
minHeap = new PriorityQueue<>(NumericComparator.natural());
}
void accumulate(Value<?> numeric) {
maxHeap.offer(numeric);
minHeap.offer(maxHeap.poll());
if (maxHeap.size() < minHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
Optional<Value<?>> median(ConceptManager conceptMgr) {
if (maxHeap.isEmpty() && minHeap.isEmpty()) {
return Optional.empty();
} else if (maxHeap.size() == minHeap.size()) {
Value<?> sum = sumValue(conceptMgr, maxHeap.peek(), minHeap.peek());
if (sum.isDouble()) return Optional.of(createValue(conceptMgr, sum.asDouble().value() / 2));
else if (sum.isLong())
return Optional.of(createValue(conceptMgr, (double) sum.asLong().value() / 2));
else throw TypeDBException.of(ILLEGAL_STATE);
} else if (maxHeap.peek() == null) {
return Optional.empty();
} else {
return Optional.of(maxHeap.peek());
}
}
}
/**
* Online algorithm to calculate unbiased sample standard deviation
* https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
* // TODO: We may find a faster algorithm that does not cost so much as the division in the loop
*/
private static class STDCalculator {
private final ConceptManager conceptMgr;
long n = 0;
double mean = 0d, M2 = 0d;
private STDCalculator(ConceptManager conceptMgr) {
this.conceptMgr = conceptMgr;
}
void accumulate(double value) {
n += 1;
double delta = value - mean;
mean += delta / (double) n;
double delta2 = value - mean;
M2 += delta * delta2;
}
Optional<Value<?>> std() {
if (n < 2) return Optional.empty();
else return Optional.of(createValue(conceptMgr, sqrt(M2 / (double) (n - 1))));
}
}
private static class NumericComparator implements Comparator<Value<?>> {
static NumericComparator natural = new NumericComparator();
public static Comparator<Value<?>> natural() {
return natural;
}
@Override
public int compare(Value<?> a, Value<?> b) {
return compareValue(a, b);
}
private <T, U> int compareValue(Value<T> a, Value<U> b) {
assert (a.isLong() || a.isDouble()) && (b.isLong() || b.isDouble());
if (a.isLong() && b.isLong()) return a.asLong().value().compareTo(b.asLong().value());
else {
Double aValue = (double) a.value();
return aValue.compareTo((double) b.value());
}
}
}
private static class Accumulator<T> implements Consumer<T> {
T value;
private BinaryOperator<T> op;
Accumulator(T init, BinaryOperator<T> op) {
value = init;
this.op = op;
}
@Override
public void accept(T t) {
value = op.apply(value, t);
}
}
private static class OptionalAccumulator<T> implements Consumer<T> {
T value = null;
boolean present = false;
private BinaryOperator<T> op;
OptionalAccumulator(BinaryOperator<T> op) {
this.op = op;
}
@Override
public void accept(T t) {
if (present) {
value = op.apply(value, t);
} else {
value = t;
present = true;
}
}
}
}
public static class Group {
private final Getter getter;
private final TypeQLGet.Group query;
private final Context.Query context;
public Group(Getter getter, TypeQLGet.Group query, Context.Query context) {
this.getter = getter;
this.query = query;
this.context = context;
this.context.producer(Either.first(EXHAUSTIVE));
}
public FunctionalIterator<ConceptMapGroup> execute() {
// TODO: Replace this temporary implementation of TypeQL Match Group query with a native grouping traversal
List<ConceptMapGroup> answerGroups = new ArrayList<>();
getter.execute(context).stream().collect(groupingBy(a -> a.get(query.var())))
.forEach((o, cm) -> answerGroups.add(new ConceptMapGroup(o, cm)));
return iterate(answerGroups);
}
public static class Aggregator {
private final ConceptManager conceptMgr;
private final Group group;
private final TypeQLGet.Group.Aggregate query;
public Aggregator(ConceptManager conceptMgr, Group group, TypeQLGet.Group.Aggregate query) {
this.conceptMgr = conceptMgr;
this.group = group;
this.query = query;
}
public FunctionalIterator<ValueGroup> execute() {
// TODO: Replace this temporary implementation of TypeQL Match Group query with a native grouping traversal
List<ValueGroup> valueGroups = new ArrayList<>();
group.getter.execute(group.context).stream()
.collect(groupingBy(a -> a.get(query.group().var()), aggregator(conceptMgr, query.method(), query.var())))
.forEach((o, n) -> valueGroups.add(new ValueGroup(o, n)));
return iterate(valueGroups);
}
}
}
}
| vaticle/typedb | query/Getter.java |
45,305 | /*
* 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 com.facebook.presto.hive;
import com.facebook.presto.cache.CachingFileSystem;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.BigintType;
import com.facebook.presto.common.type.BooleanType;
import com.facebook.presto.common.type.CharType;
import com.facebook.presto.common.type.DateType;
import com.facebook.presto.common.type.DecimalType;
import com.facebook.presto.common.type.DoubleType;
import com.facebook.presto.common.type.IntegerType;
import com.facebook.presto.common.type.RealType;
import com.facebook.presto.common.type.SmallintType;
import com.facebook.presto.common.type.TimestampType;
import com.facebook.presto.common.type.TinyintType;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.common.type.VarbinaryType;
import com.facebook.presto.common.type.VarcharType;
import com.facebook.presto.hive.RecordFileWriter.ExtendedRecordWriter;
import com.facebook.presto.hive.metastore.Database;
import com.facebook.presto.hive.metastore.MetastoreContext;
import com.facebook.presto.hive.metastore.Partition;
import com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore;
import com.facebook.presto.hive.metastore.Storage;
import com.facebook.presto.hive.s3.PrestoS3FileSystem;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaNotFoundException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.security.ConnectorIdentity;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Shorts;
import com.google.common.primitives.SignedBytes;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.HadoopExtendedFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.viewfs.ViewFileSystem;
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.ProtectMode;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.ql.io.RCFile;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.Serializer;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.ShortWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.ByteWritable;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hive.common.util.ReflectionUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import static com.facebook.presto.common.type.Chars.isCharType;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_DATABASE_LOCATION_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_SERDE_NOT_FOUND;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_DATA_ERROR;
import static com.facebook.presto.hive.HiveSessionProperties.getTemporaryStagingDirectoryPath;
import static com.facebook.presto.hive.ParquetRecordWriterUtil.createParquetWriter;
import static com.facebook.presto.hive.metastore.MetastoreUtil.createDirectory;
import static com.facebook.presto.hive.metastore.MetastoreUtil.getField;
import static com.facebook.presto.hive.metastore.MetastoreUtil.getHiveDecimal;
import static com.facebook.presto.hive.metastore.MetastoreUtil.getMetastoreHeaders;
import static com.facebook.presto.hive.metastore.MetastoreUtil.getProtectMode;
import static com.facebook.presto.hive.metastore.MetastoreUtil.isArrayType;
import static com.facebook.presto.hive.metastore.MetastoreUtil.isMapType;
import static com.facebook.presto.hive.metastore.MetastoreUtil.isRowType;
import static com.facebook.presto.hive.metastore.MetastoreUtil.isUserDefinedTypeEncodingEnabled;
import static com.facebook.presto.hive.metastore.MetastoreUtil.pathExists;
import static com.facebook.presto.hive.metastore.MetastoreUtil.verifyOnline;
import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED;
import static java.lang.Float.intBitsToFloat;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.UUID.randomUUID;
import static java.util.stream.Collectors.toList;
import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.COMPRESSRESULT;
import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaBooleanObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDateObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDoubleObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaFloatObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaIntObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaLongObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaShortObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaTimestampObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableBooleanObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableByteObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableDateObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableDoubleObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableFloatObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableHiveCharObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableIntObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableLongObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableShortObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableStringObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getCharTypeInfo;
import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getVarcharTypeInfo;
import static org.apache.hadoop.mapred.FileOutputFormat.getOutputCompressorClass;
public final class HiveWriteUtils
{
private HiveWriteUtils()
{
}
public static RecordWriter createRecordWriter(Path target, JobConf conf, Properties properties, String outputFormatName, ConnectorSession session)
{
try {
boolean compress = HiveConf.getBoolVar(conf, COMPRESSRESULT);
if (outputFormatName.equals(RCFileOutputFormat.class.getName())) {
return createRcFileWriter(target, conf, properties, compress);
}
if (outputFormatName.equals(MapredParquetOutputFormat.class.getName())) {
return createParquetWriter(target, conf, properties, compress, session);
}
Object writer = Class.forName(outputFormatName).getConstructor().newInstance();
return ((HiveOutputFormat<?, ?>) writer).getHiveRecordWriter(conf, target, Text.class, compress, properties, Reporter.NULL);
}
catch (IOException | ReflectiveOperationException e) {
throw new PrestoException(HIVE_WRITER_DATA_ERROR, e);
}
}
private static RecordWriter createRcFileWriter(Path target, JobConf conf, Properties properties, boolean compress)
throws IOException
{
int columns = properties.getProperty(META_TABLE_COLUMNS).split(",").length;
RCFileOutputFormat.setColumnNumber(conf, columns);
CompressionCodec codec = null;
if (compress) {
codec = ReflectionUtil.newInstance(getOutputCompressorClass(conf, DefaultCodec.class), conf);
}
RCFile.Writer writer = new RCFile.Writer(target.getFileSystem(conf), conf, target, () -> {}, codec);
return new ExtendedRecordWriter()
{
private long length;
@Override
public long getWrittenBytes()
{
return length;
}
@Override
public void write(Writable value)
throws IOException
{
writer.append(value);
length = writer.getLength();
}
@Override
public void close(boolean abort)
throws IOException
{
writer.close();
if (!abort) {
length = target.getFileSystem(conf).getFileStatus(target).getLen();
}
}
};
}
public static Serializer initializeSerializer(Configuration conf, Properties properties, String serializerName)
{
try {
Serializer result = (Serializer) Class.forName(serializerName).getConstructor().newInstance();
result.initialize(conf, properties);
return result;
}
catch (ClassNotFoundException e) {
throw new PrestoException(HIVE_SERDE_NOT_FOUND, "Serializer does not exist: " + serializerName);
}
catch (SerDeException | ReflectiveOperationException e) {
throw new PrestoException(HIVE_WRITER_DATA_ERROR, e);
}
}
public static ObjectInspector getJavaObjectInspector(Type type)
{
if (type.equals(BooleanType.BOOLEAN)) {
return javaBooleanObjectInspector;
}
else if (type.equals(BigintType.BIGINT)) {
return javaLongObjectInspector;
}
else if (type.equals(IntegerType.INTEGER)) {
return javaIntObjectInspector;
}
else if (type.equals(SmallintType.SMALLINT)) {
return javaShortObjectInspector;
}
else if (type.equals(TinyintType.TINYINT)) {
return javaByteObjectInspector;
}
else if (type.equals(RealType.REAL)) {
return javaFloatObjectInspector;
}
else if (type.equals(DoubleType.DOUBLE)) {
return javaDoubleObjectInspector;
}
else if (type instanceof VarcharType) {
return writableStringObjectInspector;
}
else if (type instanceof CharType) {
return writableHiveCharObjectInspector;
}
else if (type.equals(VarbinaryType.VARBINARY)) {
return javaByteArrayObjectInspector;
}
else if (type.equals(DateType.DATE)) {
return javaDateObjectInspector;
}
else if (type.equals(TimestampType.TIMESTAMP)) {
return javaTimestampObjectInspector;
}
else if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
return getPrimitiveJavaObjectInspector(new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale()));
}
else if (isArrayType(type)) {
return ObjectInspectorFactory.getStandardListObjectInspector(getJavaObjectInspector(type.getTypeParameters().get(0)));
}
else if (isMapType(type)) {
ObjectInspector keyObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(0));
ObjectInspector valueObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(1));
return ObjectInspectorFactory.getStandardMapObjectInspector(keyObjectInspector, valueObjectInspector);
}
else if (isRowType(type)) {
return ObjectInspectorFactory.getStandardStructObjectInspector(
type.getTypeSignature().getParameters().stream()
.map(parameter -> parameter.getNamedTypeSignature().getName().get())
.collect(toList()),
type.getTypeParameters().stream()
.map(HiveWriteUtils::getJavaObjectInspector)
.collect(toList()));
}
throw new IllegalArgumentException("unsupported type: " + type);
}
public static void checkPartitionIsWritable(String partitionName, Partition partition)
{
checkWritable(
partition.getSchemaTableName(),
Optional.of(partitionName),
getProtectMode(partition),
partition.getParameters(),
partition.getStorage());
}
public static void checkWritable(
SchemaTableName tableName,
Optional<String> partitionName,
ProtectMode protectMode,
Map<String, String> parameters,
Storage storage)
{
String tablePartitionDescription = "Table '" + tableName + "'";
if (partitionName.isPresent()) {
tablePartitionDescription += " partition '" + partitionName.get() + "'";
}
// verify online
verifyOnline(tableName, partitionName, protectMode, parameters);
// verify not read only
if (protectMode.readOnly) {
throw new HiveReadOnlyException(tableName, partitionName);
}
// verify skew info
if (storage.isSkewed()) {
throw new PrestoException(NOT_SUPPORTED, format("Inserting into bucketed tables with skew is not supported. %s", tablePartitionDescription));
}
}
public static Path getTableDefaultLocation(ConnectorSession session, SemiTransactionalHiveMetastore metastore, HdfsEnvironment hdfsEnvironment, String schemaName, String tableName)
{
MetastoreContext metastoreContext = new MetastoreContext(session.getIdentity(), session.getQueryId(), session.getClientInfo(), session.getSource(), getMetastoreHeaders(session), isUserDefinedTypeEncodingEnabled(session), metastore.getColumnConverterProvider(), session.getWarningCollector(), session.getRuntimeStats());
Optional<String> location = getDatabase(session.getIdentity(), metastoreContext, metastore, schemaName).getLocation();
if (!location.isPresent() || location.get().isEmpty()) {
throw new PrestoException(HIVE_DATABASE_LOCATION_ERROR, format("Database '%s' location is not set", schemaName));
}
HdfsContext context = new HdfsContext(session, schemaName, tableName, location.get(), true);
Path databasePath = new Path(location.get());
if (!isS3FileSystem(context, hdfsEnvironment, databasePath)) {
if (!pathExists(context, hdfsEnvironment, databasePath)) {
throw new PrestoException(HIVE_DATABASE_LOCATION_ERROR, format("Database '%s' location does not exist: %s", schemaName, databasePath));
}
if (!isDirectory(context, hdfsEnvironment, databasePath)) {
throw new PrestoException(HIVE_DATABASE_LOCATION_ERROR, format("Database '%s' location is not a directory: %s", schemaName, databasePath));
}
}
return new Path(databasePath, tableName);
}
private static Database getDatabase(ConnectorIdentity identity, MetastoreContext metastoreContext, SemiTransactionalHiveMetastore metastore, String database)
{
return metastore.getDatabase(metastoreContext, database).orElseThrow(() -> new SchemaNotFoundException(database));
}
public static boolean isS3FileSystem(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path)
{
try {
return getRawFileSystem(hdfsEnvironment.getFileSystem(context, path)) instanceof PrestoS3FileSystem;
}
catch (IOException e) {
throw new PrestoException(HIVE_FILESYSTEM_ERROR, "Failed checking path: " + path, e);
}
}
public static boolean isViewFileSystem(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path)
{
try {
return getRawFileSystem(hdfsEnvironment.getFileSystem(context, path)) instanceof ViewFileSystem;
}
catch (IOException e) {
throw new PrestoException(HIVE_FILESYSTEM_ERROR, "Failed checking path: " + path, e);
}
}
private static FileSystem getRawFileSystem(FileSystem fileSystem)
{
if (fileSystem instanceof HadoopExtendedFileSystem) {
return getRawFileSystem(((HadoopExtendedFileSystem) fileSystem).getRawFileSystem());
}
if (fileSystem instanceof CachingFileSystem) {
return getRawFileSystem(((CachingFileSystem) fileSystem).getDataTier());
}
return fileSystem;
}
private static boolean isDirectory(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path)
{
try {
return hdfsEnvironment.getFileSystem(context, path).isDirectory(path);
}
catch (IOException e) {
throw new PrestoException(HIVE_FILESYSTEM_ERROR, "Failed checking path: " + path, e);
}
}
public static boolean isFileCreatedByQuery(String fileName, String queryId)
{
// For normal files, the queryId is at the beginning of the file name.
// For bucketed files, the queryId is at the end of the file name.
return fileName.startsWith(queryId) || fileName.endsWith(queryId);
}
public static Path createTemporaryPath(ConnectorSession session, HdfsContext context, HdfsEnvironment hdfsEnvironment, Path targetPath)
{
// use a per-user temporary directory to avoid permission problems
String temporaryPrefix = getTemporaryStagingDirectoryPath(session)
.replace("${USER}", context.getIdentity().getUser());
// use relative temporary directory on ViewFS
if (isViewFileSystem(context, hdfsEnvironment, targetPath)) {
if (pathExists(context, hdfsEnvironment, targetPath)) {
temporaryPrefix = ".hive-staging";
}
else {
//use the temporary folder in parent when target path does not exist
temporaryPrefix = "../.hive-staging";
}
}
// create a temporary directory on the same filesystem
Path temporaryRoot = new Path(targetPath, temporaryPrefix);
if (!pathExists(context, hdfsEnvironment, temporaryRoot)) {
createDirectory(context, hdfsEnvironment, temporaryRoot);
}
Path temporaryPath = new Path(temporaryRoot, randomUUID().toString());
createDirectory(context, hdfsEnvironment, temporaryPath);
return temporaryPath;
}
public static boolean isWritableType(HiveType hiveType)
{
return isWritableType(hiveType.getTypeInfo());
}
private static boolean isWritableType(TypeInfo typeInfo)
{
switch (typeInfo.getCategory()) {
case PRIMITIVE:
PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();
return isWritablePrimitiveType(primitiveCategory);
case MAP:
MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo;
return isWritableType(mapTypeInfo.getMapKeyTypeInfo()) && isWritableType(mapTypeInfo.getMapValueTypeInfo());
case LIST:
ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;
return isWritableType(listTypeInfo.getListElementTypeInfo());
case STRUCT:
StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;
return structTypeInfo.getAllStructFieldTypeInfos().stream().allMatch(HiveWriteUtils::isWritableType);
}
return false;
}
private static boolean isWritablePrimitiveType(PrimitiveCategory primitiveCategory)
{
switch (primitiveCategory) {
case BOOLEAN:
case LONG:
case INT:
case SHORT:
case BYTE:
case FLOAT:
case DOUBLE:
case STRING:
case DATE:
case TIMESTAMP:
case BINARY:
case DECIMAL:
case VARCHAR:
case CHAR:
return true;
}
return false;
}
public static List<ObjectInspector> getRowColumnInspectors(List<Type> types)
{
return types.stream()
.map(HiveWriteUtils::getRowColumnInspector)
.collect(toList());
}
public static ObjectInspector getRowColumnInspector(Type type)
{
if (type.equals(BooleanType.BOOLEAN)) {
return writableBooleanObjectInspector;
}
if (type.equals(BigintType.BIGINT)) {
return writableLongObjectInspector;
}
if (type.equals(IntegerType.INTEGER)) {
return writableIntObjectInspector;
}
if (type.equals(SmallintType.SMALLINT)) {
return writableShortObjectInspector;
}
if (type.equals(TinyintType.TINYINT)) {
return writableByteObjectInspector;
}
if (type.equals(RealType.REAL)) {
return writableFloatObjectInspector;
}
if (type.equals(DoubleType.DOUBLE)) {
return writableDoubleObjectInspector;
}
if (type instanceof VarcharType) {
VarcharType varcharType = (VarcharType) type;
int varcharLength = varcharType.getLength();
// VARCHAR columns with the length less than or equal to 65535 are supported natively by Hive
if (varcharLength <= HiveVarchar.MAX_VARCHAR_LENGTH) {
return getPrimitiveWritableObjectInspector(getVarcharTypeInfo(varcharLength));
}
// Unbounded VARCHAR is not supported by Hive.
// Values for such columns must be stored as STRING in Hive
else if (varcharLength == VarcharType.UNBOUNDED_LENGTH) {
return writableStringObjectInspector;
}
}
if (isCharType(type)) {
CharType charType = (CharType) type;
int charLength = charType.getLength();
return getPrimitiveWritableObjectInspector(getCharTypeInfo(charLength));
}
if (type.equals(VarbinaryType.VARBINARY)) {
return writableBinaryObjectInspector;
}
if (type.equals(DateType.DATE)) {
return writableDateObjectInspector;
}
if (type.equals(TimestampType.TIMESTAMP)) {
return writableTimestampObjectInspector;
}
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
return getPrimitiveWritableObjectInspector(new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale()));
}
if (isArrayType(type) || isMapType(type) || isRowType(type)) {
return getJavaObjectInspector(type);
}
throw new IllegalArgumentException("unsupported type: " + type);
}
public static FieldSetter createFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type type)
{
if (type.equals(BooleanType.BOOLEAN)) {
return new BooleanFieldSetter(rowInspector, row, field);
}
if (type.equals(BigintType.BIGINT)) {
return new BigintFieldBuilder(rowInspector, row, field);
}
if (type.equals(IntegerType.INTEGER)) {
return new IntFieldSetter(rowInspector, row, field);
}
if (type.equals(SmallintType.SMALLINT)) {
return new SmallintFieldSetter(rowInspector, row, field);
}
if (type.equals(TinyintType.TINYINT)) {
return new TinyintFieldSetter(rowInspector, row, field);
}
if (type.equals(RealType.REAL)) {
return new FloatFieldSetter(rowInspector, row, field);
}
if (type.equals(DoubleType.DOUBLE)) {
return new DoubleFieldSetter(rowInspector, row, field);
}
if (type instanceof VarcharType) {
return new VarcharFieldSetter(rowInspector, row, field, type);
}
if (type instanceof CharType) {
return new CharFieldSetter(rowInspector, row, field, type);
}
if (type.equals(VarbinaryType.VARBINARY)) {
return new BinaryFieldSetter(rowInspector, row, field);
}
if (type.equals(DateType.DATE)) {
return new DateFieldSetter(rowInspector, row, field);
}
if (type.equals(TimestampType.TIMESTAMP)) {
return new TimestampFieldSetter(rowInspector, row, field);
}
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
return new DecimalFieldSetter(rowInspector, row, field, decimalType);
}
if (isArrayType(type)) {
return new ArrayFieldSetter(rowInspector, row, field, type.getTypeParameters().get(0));
}
if (isMapType(type)) {
return new MapFieldSetter(rowInspector, row, field, type.getTypeParameters().get(0), type.getTypeParameters().get(1));
}
if (isRowType(type)) {
return new RowFieldSetter(rowInspector, row, field, type.getTypeParameters());
}
throw new IllegalArgumentException("unsupported type: " + type);
}
public abstract static class FieldSetter
{
protected final SettableStructObjectInspector rowInspector;
protected final Object row;
protected final StructField field;
protected FieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
this.rowInspector = requireNonNull(rowInspector, "rowInspector is null");
this.row = requireNonNull(row, "row is null");
this.field = requireNonNull(field, "field is null");
}
public abstract void setField(Block block, int position);
}
private static class BooleanFieldSetter
extends FieldSetter
{
private final BooleanWritable value = new BooleanWritable();
public BooleanFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(BooleanType.BOOLEAN.getBoolean(block, position));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class BigintFieldBuilder
extends FieldSetter
{
private final LongWritable value = new LongWritable();
public BigintFieldBuilder(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(BigintType.BIGINT.getLong(block, position));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class IntFieldSetter
extends FieldSetter
{
private final IntWritable value = new IntWritable();
public IntFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(toIntExact(IntegerType.INTEGER.getLong(block, position)));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class SmallintFieldSetter
extends FieldSetter
{
private final ShortWritable value = new ShortWritable();
public SmallintFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(Shorts.checkedCast(SmallintType.SMALLINT.getLong(block, position)));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class TinyintFieldSetter
extends FieldSetter
{
private final ByteWritable value = new ByteWritable();
public TinyintFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(SignedBytes.checkedCast(TinyintType.TINYINT.getLong(block, position)));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class DoubleFieldSetter
extends FieldSetter
{
private final DoubleWritable value = new DoubleWritable();
public DoubleFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(DoubleType.DOUBLE.getDouble(block, position));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class FloatFieldSetter
extends FieldSetter
{
private final FloatWritable value = new FloatWritable();
public FloatFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(intBitsToFloat((int) RealType.REAL.getLong(block, position)));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class VarcharFieldSetter
extends FieldSetter
{
private final Text value = new Text();
private final Type type;
public VarcharFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type type)
{
super(rowInspector, row, field);
this.type = type;
}
@Override
public void setField(Block block, int position)
{
value.set(type.getSlice(block, position).getBytes());
rowInspector.setStructFieldData(row, field, value);
}
}
private static class CharFieldSetter
extends FieldSetter
{
private final Text value = new Text();
private final Type type;
public CharFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type type)
{
super(rowInspector, row, field);
this.type = type;
}
@Override
public void setField(Block block, int position)
{
value.set(type.getSlice(block, position).getBytes());
rowInspector.setStructFieldData(row, field, value);
}
}
private static class BinaryFieldSetter
extends FieldSetter
{
private final BytesWritable value = new BytesWritable();
public BinaryFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
byte[] bytes = VarbinaryType.VARBINARY.getSlice(block, position).getBytes();
value.set(bytes, 0, bytes.length);
rowInspector.setStructFieldData(row, field, value);
}
}
private static class DateFieldSetter
extends FieldSetter
{
private final DateWritable value = new DateWritable();
public DateFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
value.set(toIntExact(DateType.DATE.getLong(block, position)));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class TimestampFieldSetter
extends FieldSetter
{
private final TimestampWritable value = new TimestampWritable();
public TimestampFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field)
{
super(rowInspector, row, field);
}
@Override
public void setField(Block block, int position)
{
long millisUtc = TimestampType.TIMESTAMP.getLong(block, position);
value.setTime(millisUtc);
rowInspector.setStructFieldData(row, field, value);
}
}
private static class DecimalFieldSetter
extends FieldSetter
{
private final HiveDecimalWritable value = new HiveDecimalWritable();
private final DecimalType decimalType;
public DecimalFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, DecimalType decimalType)
{
super(rowInspector, row, field);
this.decimalType = decimalType;
}
@Override
public void setField(Block block, int position)
{
value.set(getHiveDecimal(decimalType, block, position));
rowInspector.setStructFieldData(row, field, value);
}
}
private static class ArrayFieldSetter
extends FieldSetter
{
private final Type elementType;
public ArrayFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type elementType)
{
super(rowInspector, row, field);
this.elementType = requireNonNull(elementType, "elementType is null");
}
@Override
public void setField(Block block, int position)
{
Block arrayBlock = block.getBlock(position);
List<Object> list = new ArrayList<>(arrayBlock.getPositionCount());
for (int i = 0; i < arrayBlock.getPositionCount(); i++) {
Object element = getField(elementType, arrayBlock, i);
list.add(element);
}
rowInspector.setStructFieldData(row, field, list);
}
}
private static class MapFieldSetter
extends FieldSetter
{
private final Type keyType;
private final Type valueType;
public MapFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type keyType, Type valueType)
{
super(rowInspector, row, field);
this.keyType = requireNonNull(keyType, "keyType is null");
this.valueType = requireNonNull(valueType, "valueType is null");
}
@Override
public void setField(Block block, int position)
{
Block mapBlock = block.getBlock(position);
Map<Object, Object> map = new HashMap<>(mapBlock.getPositionCount() * 2);
for (int i = 0; i < mapBlock.getPositionCount(); i += 2) {
Object key = getField(keyType, mapBlock, i);
Object value = getField(valueType, mapBlock, i + 1);
map.put(key, value);
}
rowInspector.setStructFieldData(row, field, map);
}
}
private static class RowFieldSetter
extends FieldSetter
{
private final List<Type> fieldTypes;
public RowFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, List<Type> fieldTypes)
{
super(rowInspector, row, field);
this.fieldTypes = ImmutableList.copyOf(fieldTypes);
}
@Override
public void setField(Block block, int position)
{
Block rowBlock = block.getBlock(position);
// TODO reuse row object and use FieldSetters, like we do at the top level
// Ideally, we'd use the same recursive structure starting from the top, but
// this requires modeling row types in the same way we model table rows
// (multiple blocks vs all fields packed in a single block)
List<Object> value = new ArrayList<>(fieldTypes.size());
for (int i = 0; i < fieldTypes.size(); i++) {
Object element = getField(fieldTypes.get(i), rowBlock, i);
value.add(element);
}
rowInspector.setStructFieldData(row, field, value);
}
}
}
| prestodb/presto | presto-hive/src/main/java/com/facebook/presto/hive/HiveWriteUtils.java |
45,306 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.opengl;
import java.awt.Component;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import com.jogamp.common.util.IOUtil;
import com.jogamp.common.util.IOUtil.ClassResources;
import com.jogamp.nativewindow.NativeSurface;
import com.jogamp.nativewindow.ScalableSurface;
import com.jogamp.nativewindow.util.Dimension;
import com.jogamp.nativewindow.util.PixelFormat;
import com.jogamp.nativewindow.util.PixelRectangle;
import com.jogamp.opengl.GLAnimatorControl;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.GLProfile;
import com.jogamp.nativewindow.MutableGraphicsConfiguration;
import com.jogamp.nativewindow.WindowClosingProtocol;
import com.jogamp.newt.Display;
import com.jogamp.newt.Display.PointerIcon;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.Screen;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.event.InputEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PSurface;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
public class PSurfaceJOGL implements PSurface {
/** Selected GL profile */
public static GLProfile profile;
public PJOGL pgl;
protected GLWindow window;
protected FPSAnimator animator;
protected Rectangle screenRect;
private Thread drawExceptionHandler;
protected PApplet sketch;
protected PGraphics graphics;
protected int sketchWidth0;
protected int sketchHeight0;
protected int sketchWidth;
protected int sketchHeight;
protected Display display;
protected Screen screen;
protected Rectangle displayRect;
protected Throwable drawException;
private final Object drawExceptionMutex = new Object();
protected NewtCanvasAWT canvas;
protected int windowScaleFactor;
protected float[] currentPixelScale = {0, 0};
protected boolean external = false;
public PSurfaceJOGL(PGraphics graphics) {
this.graphics = graphics;
this.pgl = (PJOGL) ((PGraphicsOpenGL)graphics).pgl;
}
public void initOffscreen(PApplet sketch) {
this.sketch = sketch;
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
if (window != null) {
canvas = new NewtCanvasAWT(window);
canvas.setBounds(0, 0, window.getWidth(), window.getHeight());
canvas.setFocusable(true);
}
}
public void initFrame(PApplet sketch) {
this.sketch = sketch;
initIcons();
initDisplay();
initGL();
initWindow();
initListeners();
initAnimator();
}
public Object getNative() {
return window;
}
protected void initDisplay() {
display = NewtFactory.createDisplay(null);
display.addReference();
screen = NewtFactory.createScreen(display, 0);
screen.addReference();
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] awtDevices = environment.getScreenDevices();
GraphicsDevice awtDisplayDevice = null;
int displayNum = sketch.sketchDisplay();
if (displayNum > 0) { // if -1, use the default device
if (displayNum <= awtDevices.length) {
awtDisplayDevice = awtDevices[displayNum-1];
} else {
System.err.format("Display %d does not exist, " +
"using the default display instead.%n", displayNum);
for (int i = 0; i < awtDevices.length; i++) {
System.err.format("Display %d is %s%n", i+1, awtDevices[i]);
}
}
} else if (0 < awtDevices.length) {
awtDisplayDevice = awtDevices[0];
}
if (awtDisplayDevice == null) {
awtDisplayDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
displayRect = awtDisplayDevice.getDefaultConfiguration().getBounds();
}
protected void initGL() {
// System.out.println("*******************************");
if (profile == null) {
if (PJOGL.profile == 1) {
try {
profile = GLProfile.getGL2ES1();
} catch (GLException ex) {
profile = GLProfile.getMaxFixedFunc(true);
}
} else if (PJOGL.profile == 2) {
try {
profile = GLProfile.getGL2ES2();
// workaround for https://jogamp.org/bugzilla/show_bug.cgi?id=1347
if (!profile.isHardwareRasterizer()) {
GLProfile hardware = GLProfile.getMaxProgrammable(true);
if (hardware.isGL2ES2()) {
profile = hardware;
}
}
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
} else if (PJOGL.profile == 3) {
try {
profile = GLProfile.getGL2GL3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL3()) {
PGraphics.showWarning("Requested profile GL3 but is not available, got: " + profile);
}
} else if (PJOGL.profile == 4) {
try {
profile = GLProfile.getGL4ES3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL4()) {
PGraphics.showWarning("Requested profile GL4 but is not available, got: " + profile);
}
} else throw new RuntimeException(PGL.UNSUPPORTED_GLPROF_ERROR);
}
// Setting up the desired capabilities;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
// caps.setPBuffer(false);
// caps.setFBO(false);
// pgl.reqNumSamples = PGL.smoothToSamples(graphics.smooth);
caps.setSampleBuffers(true);
caps.setNumSamples(PGL.smoothToSamples(graphics.smooth));
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
pgl.setCaps(caps);
}
protected void initWindow() {
window = GLWindow.create(screen, pgl.getCaps());
// Make sure that we pass the window close through to exit(), otherwise
// we're likely to have OpenGL try to shut down halfway through rendering
// a frame. Particularly problematic for complex/slow apps.
// https://github.com/processing/processing/issues/4690
window.setDefaultCloseOperation(WindowClosingProtocol.WindowClosingMode.DO_NOTHING_ON_CLOSE);
// if (displayDevice == null) {
//
//
// } else {
// window = GLWindow.create(displayDevice.getScreen(), pgl.getCaps());
// }
windowScaleFactor = PApplet.platform == PConstants.MACOSX ?
1 : sketch.pixelDensity;
boolean spanDisplays = sketch.sketchDisplay() == PConstants.SPAN;
screenRect = spanDisplays ?
new Rectangle(screen.getX(), screen.getY(), screen.getWidth(), screen.getHeight()) :
new Rectangle((int) displayRect.getX(), (int) displayRect.getY(),
(int) displayRect.getWidth(),
(int) displayRect.getHeight());
// Set the displayWidth/Height variables inside PApplet, so that they're
// usable and can even be returned by the sketchWidth()/Height() methods.
sketch.displayWidth = screenRect.width;
sketch.displayHeight = screenRect.height;
sketchWidth0 = sketch.sketchWidth();
sketchHeight0 = sketch.sketchHeight();
/*
// Trying to fix
// https://github.com/processing/processing/issues/3401
if (sketch.displayWidth < sketch.width ||
sketch.displayHeight < sketch.height) {
int w = sketch.width;
int h = sketch.height;
if (sketch.displayWidth < w) {
w = sketch.displayWidth;
}
if (sketch.displayHeight < h) {
h = sketch.displayHeight;
}
// sketch.setSize(w, h - 22 - 22);
// graphics.setSize(w, h - 22 - 22);
System.err.println("setting width/height to " + w + " " + h);
}
*/
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
// System.out.println("init: " + sketchWidth + " " + sketchHeight);
boolean fullScreen = sketch.sketchFullScreen();
// Removing the section below because sometimes people want to do the
// full screen size in a window, and it also breaks insideSettings().
// With 3.x, fullScreen() is so easy, that it's just better that way.
// https://github.com/processing/processing/issues/3545
/*
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == sketchWidth &&
screenRect.height == sketchHeight) {
fullScreen = true;
sketch.fullScreen();
}
*/
if (fullScreen || spanDisplays) {
sketchWidth = screenRect.width / windowScaleFactor;
sketchHeight = screenRect.height / windowScaleFactor;
}
sketch.setSize(sketchWidth, sketchHeight);
float[] reqSurfacePixelScale;
if (graphics.is2X() && PApplet.platform == PConstants.MACOSX) {
// Retina
reqSurfacePixelScale = new float[] { ScalableSurface.AUTOMAX_PIXELSCALE,
ScalableSurface.AUTOMAX_PIXELSCALE };
} else {
// Non-retina
reqSurfacePixelScale = new float[] { ScalableSurface.IDENTITY_PIXELSCALE,
ScalableSurface.IDENTITY_PIXELSCALE };
}
window.setSurfaceScale(reqSurfacePixelScale);
window.setSize(sketchWidth * windowScaleFactor, sketchHeight * windowScaleFactor);
window.setResizable(false);
setSize(sketchWidth, sketchHeight);
if (fullScreen) {
PApplet.hideMenuBar();
if (spanDisplays) {
window.setFullscreen(screen.getMonitorDevices());
} else {
window.setUndecorated(true);
window.setTopLevelPosition((int) displayRect.getX(), (int) displayRect.getY());
window.setTopLevelSize((int) displayRect.getWidth(), (int) displayRect.getHeight());
}
}
}
protected void initListeners() {
NEWTMouseListener mouseListener = new NEWTMouseListener();
window.addMouseListener(mouseListener);
NEWTKeyListener keyListener = new NEWTKeyListener();
window.addKeyListener(keyListener);
NEWTWindowListener winListener = new NEWTWindowListener();
window.addWindowListener(winListener);
DrawListener drawlistener = new DrawListener();
window.addGLEventListener(drawlistener);
}
protected void initAnimator() {
if (PApplet.platform == PConstants.WINDOWS) {
// Force Windows to keep timer resolution high by
// sleeping for time which is not a multiple of 10 ms.
// See section "Clocks and Timers on Windows":
// https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
Thread highResTimerThread = new Thread(() -> {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ignore) { }
}, "HighResTimerThread");
highResTimerThread.setDaemon(true);
highResTimerThread.start();
}
animator = new FPSAnimator(window, 60);
drawException = null;
animator.setUncaughtExceptionHandler(new GLAnimatorControl.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final GLAnimatorControl animator,
final GLAutoDrawable drawable,
final Throwable cause) {
synchronized (drawExceptionMutex) {
drawException = cause;
drawExceptionMutex.notify();
}
}
});
drawExceptionHandler = new Thread(new Runnable() {
public void run() {
synchronized (drawExceptionMutex) {
try {
while (drawException == null) {
drawExceptionMutex.wait();
}
// System.err.println("Caught exception: " + drawException.getMessage());
if (drawException != null) {
Throwable cause = drawException.getCause();
if (cause instanceof ThreadDeath) {
// System.out.println("caught ThreadDeath");
// throw (ThreadDeath)cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof UnsatisfiedLinkError) {
throw new UnsatisfiedLinkError(cause.getMessage());
} else if (cause == null) {
throw new RuntimeException(drawException.getMessage());
} else {
throw new RuntimeException(cause);
}
}
} catch (InterruptedException e) {
return;
}
}
}
});
drawExceptionHandler.start();
}
@Override
public void setTitle(final String title) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setTitle(title);
}
});
}
@Override
public void setVisible(final boolean visible) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setVisible(visible);
}
});
}
@Override
public void setResizable(final boolean resizable) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setResizable(resizable);
}
});
}
public void setIcon(PImage icon) {
PGraphics.showWarning("Window icons for OpenGL sketches can only be set in settings()\n" +
"using PJOGL.setIcon(filename).");
}
@Override
public void setAlwaysOnTop(final boolean always) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setAlwaysOnTop(always);
}
});
}
protected void initIcons() {
IOUtil.ClassResources res = null;
if (PJOGL.icons == null || PJOGL.icons.length == 0) {
// Default Processing icons
final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
String[] iconImages = new String[sizes.length];
for (int i = 0; i < sizes.length; i++) {
iconImages[i] = "/icon/icon-" + sizes[i] + ".png";
}
res = new ClassResources(iconImages,
PApplet.class.getClassLoader(),
PApplet.class);
} else {
// Loading custom icons from user-provided files.
String[] iconImages = new String[PJOGL.icons.length];
for (int i = 0; i < PJOGL.icons.length; i++) {
iconImages[i] = resourceFilename(PJOGL.icons[i]);
}
res = new ClassResources(iconImages,
sketch.getClass().getClassLoader(),
sketch.getClass());
}
NewtFactory.setWindowIcons(res);
}
@SuppressWarnings("resource")
private String resourceFilename(String filename) {
// The code below comes from PApplet.createInputRaw() with a few adaptations
InputStream stream = null;
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(sketch.dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = sketch.sketchFile(filename);
}
if (file.exists() && !file.isDirectory()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
stream = new FileInputStream(file);
if (stream != null) {
stream.close();
return file.getCanonicalPath();
}
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
ClassLoader cl = sketch.getClass().getClassLoader();
try {
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return "data/" + filename;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return filename;
}
}
} catch (IOException e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
String path = sketch.dataPath(filename);
stream = new FileInputStream(path);
if (stream != null) {
stream.close();
return path;
}
} catch (IOException e2) { }
try {
String path = sketch.sketchPath(filename);
stream = new FileInputStream(path);
if (stream != null) {
stream.close();
return path;
}
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) {
stream.close();
return filename;
}
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return "";
}
@Override
public void placeWindow(int[] location, int[] editorLocation) {
if (sketch.sketchFullScreen()) {
return;
}
int x = window.getX() - window.getInsets().getLeftWidth();
int y = window.getY() - window.getInsets().getTopHeight();
int w = window.getWidth() + window.getInsets().getTotalWidth();
int h = window.getHeight() + window.getInsets().getTotalHeight();
if (location != null) {
// System.err.println("place window at " + location[0] + ", " + location[1]);
window.setTopLevelPosition(location[0], location[1]);
} else if (editorLocation != null) {
// System.err.println("place window at editor location " + editorLocation[0] + ", " + editorLocation[1]);
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - w > 10) {
// if it fits to the left of the window
window.setTopLevelPosition(locationX - w, locationY);
} else { // doesn't fit
/*
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + w > sketch.displayWidth - 33) ||
(locationY + h > sketch.displayHeight - 33)) {
// otherwise center on screen
*/
locationX = (sketch.displayWidth - w) / 2;
locationY = (sketch.displayHeight - h) / 2;
/*
}
*/
window.setTopLevelPosition(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
window.setTopLevelPosition(screenRect.x + (screenRect.width - sketchWidth) / 2,
screenRect.y + (screenRect.height - sketchHeight) / 2);
}
Point frameLoc = new Point(x, y);
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
window.setTopLevelPosition(frameLoc.x, 30);
}
}
public void placePresent(int stopColor) {
float scale = getPixelScale();
pgl.initPresentMode(0.5f * (screenRect.width/scale - sketchWidth),
0.5f * (screenRect.height/scale - sketchHeight), stopColor);
PApplet.hideMenuBar();
window.setUndecorated(true);
window.setTopLevelPosition((int) displayRect.getX(), (int) displayRect.getY());
window.setTopLevelSize((int) displayRect.getWidth(), (int) displayRect.getHeight());
}
public void setupExternalMessages() {
external = true;
}
public void startThread() {
if (animator != null) {
animator.start();
}
}
public void pauseThread() {
if (animator != null) {
animator.pause();
}
}
public void resumeThread() {
if (animator != null) {
animator.resume();
}
}
public boolean stopThread() {
if (drawExceptionHandler != null) {
drawExceptionHandler.interrupt();
drawExceptionHandler = null;
}
if (animator != null) {
return animator.stop();
} else {
return false;
}
}
public boolean isStopped() {
if (animator != null) {
return !animator.isAnimating();
} else {
return true;
}
}
public void setLocation(final int x, final int y) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setTopLevelPosition(x, y);
}
});
}
public void setSize(int wide, int high) {
if (pgl.presentMode()) return;
// When the surface is set to resizable via surface.setResizable(true),
// a crash may occur if the user sets the window to size zero.
// https://github.com/processing/processing/issues/5052
if (high <= 0) {
high = 1;
}
if (wide <= 0) {
wide = 1;
}
boolean changed = sketch.width != wide || sketch.height != high;
sketchWidth = wide;
sketchHeight = high;
sketch.setSize(wide, high);
graphics.setSize(wide, high);
if (changed) {
window.setSize(wide * windowScaleFactor, high * windowScaleFactor);
}
}
public float getPixelScale() {
if (graphics.pixelDensity == 1) {
return 1;
}
if (PApplet.platform == PConstants.MACOSX) {
return getCurrentPixelScale();
}
return 2;
}
private float getCurrentPixelScale() {
// Even if the graphics are retina, the user might have moved the window
// into a non-retina monitor, so we need to check
window.getCurrentSurfaceScale(currentPixelScale);
return currentPixelScale[0];
}
public Component getComponent() {
return canvas;
}
public void setSmooth(int level) {
pgl.reqNumSamples = level;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
caps.setSampleBuffers(true);
caps.setNumSamples(pgl.reqNumSamples);
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
NativeSurface target = window.getNativeSurface();
MutableGraphicsConfiguration config = (MutableGraphicsConfiguration) target.getGraphicsConfiguration();
config.setChosenCapabilities(caps);
}
public void setFrameRate(float fps) {
if (fps < 1) {
PGraphics.showWarning(
"The OpenGL renderer cannot have a frame rate lower than 1.\n" +
"Your sketch will run at 1 frame per second.");
fps = 1;
} else if (fps > 1000) {
PGraphics.showWarning(
"The OpenGL renderer cannot have a frame rate higher than 1000.\n" +
"Your sketch will run at 1000 frames per second.");
fps = 1000;
}
if (animator != null) {
animator.stop();
animator.setFPS((int)fps);
pgl.setFps(fps);
animator.start();
}
}
public void requestFocus() {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.requestFocus();
}
});
}
class DrawListener implements GLEventListener {
public void display(GLAutoDrawable drawable) {
if (display.getEDTUtil().isCurrentThreadEDT()) {
// For some reason, the first two frames of the animator are run on the
// EDT, skipping rendering Processing's frame in that case.
return;
}
if (sketch.frameCount == 0) {
if (sketchWidth < sketchWidth0 || sketchHeight < sketchHeight0) {
PGraphics.showWarning("The sketch has been automatically resized to fit the screen resolution");
}
// System.out.println("display: " + window.getWidth() + " "+ window.getHeight() + " - " + sketchWidth + " " + sketchHeight);
requestFocus();
}
if (!sketch.finished) {
pgl.getGL(drawable);
int pframeCount = sketch.frameCount;
sketch.handleDraw();
if (pframeCount == sketch.frameCount || sketch.finished) {
// This hack allows the FBO layer to be swapped normally even if
// the sketch is no looping or finished because it does not call draw(),
// otherwise background artifacts may occur (depending on the hardware/drivers).
pgl.beginRender();
pgl.endRender(sketch.sketchWindowColor());
}
PGraphicsOpenGL.completeFinishedPixelTransfers();
}
if (sketch.exitCalled()) {
PGraphicsOpenGL.completeAllPixelTransfers();
sketch.dispose(); // calls stopThread(), which stops the animator.
sketch.exitActual();
}
}
public void dispose(GLAutoDrawable drawable) {
// sketch.dispose();
}
public void init(GLAutoDrawable drawable) {
pgl.getGL(drawable);
pgl.init(drawable);
sketch.start();
int c = graphics.backgroundColor;
pgl.clearColor(((c >> 16) & 0xff) / 255f,
((c >> 8) & 0xff) / 255f,
((c >> 0) & 0xff) / 255f,
((c >> 24) & 0xff) / 255f);
pgl.clear(PGL.COLOR_BUFFER_BIT);
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
pgl.resetFBOLayer();
pgl.getGL(drawable);
float scale = PApplet.platform == PConstants.MACOSX ?
getCurrentPixelScale() : getPixelScale();
setSize((int) (w / scale), (int) (h / scale));
}
}
protected class NEWTWindowListener implements com.jogamp.newt.event.WindowListener {
public NEWTWindowListener() {
super();
}
@Override
public void windowGainedFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = true;
sketch.focusGained();
}
@Override
public void windowLostFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = false;
sketch.focusLost();
}
@Override
public void windowDestroyNotify(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowDestroyed(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowMoved(com.jogamp.newt.event.WindowEvent arg0) {
if (external) {
sketch.frameMoved(window.getX(), window.getY());
}
}
@Override
public void windowRepaint(com.jogamp.newt.event.WindowUpdateEvent arg0) {
}
@Override
public void windowResized(com.jogamp.newt.event.WindowEvent arg0) {
}
}
// NEWT mouse listener
protected class NEWTMouseListener extends com.jogamp.newt.event.MouseAdapter {
public NEWTMouseListener() {
super();
}
@Override
public void mousePressed(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.PRESS);
}
@Override
public void mouseReleased(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.RELEASE);
}
@Override
public void mouseClicked(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.CLICK);
}
@Override
public void mouseDragged(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.DRAG);
}
@Override
public void mouseMoved(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.MOVE);
}
@Override
public void mouseWheelMoved(com.jogamp.newt.event.MouseEvent e) {
nativeMouseEvent(e, MouseEvent.WHEEL);
}
@Override
public void mouseEntered(com.jogamp.newt.event.MouseEvent e) {
// System.out.println("enter");
nativeMouseEvent(e, MouseEvent.ENTER);
}
@Override
public void mouseExited(com.jogamp.newt.event.MouseEvent e) {
// System.out.println("exit");
nativeMouseEvent(e, MouseEvent.EXIT);
}
}
// NEWT key listener
protected class NEWTKeyListener extends com.jogamp.newt.event.KeyAdapter {
public NEWTKeyListener() {
super();
}
@Override
public void keyPressed(com.jogamp.newt.event.KeyEvent e) {
nativeKeyEvent(e, KeyEvent.PRESS);
}
@Override
public void keyReleased(com.jogamp.newt.event.KeyEvent e) {
nativeKeyEvent(e, KeyEvent.RELEASE);
}
public void keyTyped(com.jogamp.newt.event.KeyEvent e) {
nativeKeyEvent(e, KeyEvent.TYPE);
}
}
protected void nativeMouseEvent(com.jogamp.newt.event.MouseEvent nativeEvent,
int peAction) {
int modifiers = nativeEvent.getModifiers();
int peModifiers = modifiers &
(InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK |
InputEvent.META_MASK |
InputEvent.ALT_MASK);
int peButton = 0;
switch (nativeEvent.getButton()) {
case com.jogamp.newt.event.MouseEvent.BUTTON1:
peButton = PConstants.LEFT;
break;
case com.jogamp.newt.event.MouseEvent.BUTTON2:
peButton = PConstants.CENTER;
break;
case com.jogamp.newt.event.MouseEvent.BUTTON3:
peButton = PConstants.RIGHT;
break;
}
int peCount = 0;
if (peAction == MouseEvent.WHEEL) {
// Invert wheel rotation count so it matches JAVA2D's
// https://github.com/processing/processing/issues/3840
peCount = -(nativeEvent.isShiftDown() ? (int)nativeEvent.getRotation()[0]:
(int)nativeEvent.getRotation()[1]);
} else {
peCount = nativeEvent.getClickCount();
}
int scale;
if (PApplet.platform == PConstants.MACOSX) {
scale = (int) getCurrentPixelScale();
} else {
scale = (int) getPixelScale();
}
int sx = nativeEvent.getX() / scale;
int sy = nativeEvent.getY() / scale;
int mx = sx;
int my = sy;
if (pgl.presentMode()) {
mx -= (int)pgl.presentX;
my -= (int)pgl.presentY;
if (peAction == KeyEvent.RELEASE &&
pgl.insideStopButton(sx, sy - screenRect.height / windowScaleFactor)) {
sketch.exit();
}
if (mx < 0 || sketchWidth < mx || my < 0 || sketchHeight < my) {
return;
}
}
MouseEvent me = new MouseEvent(nativeEvent, nativeEvent.getWhen(),
peAction, peModifiers,
mx, my,
peButton,
peCount);
sketch.postEvent(me);
}
protected void nativeKeyEvent(com.jogamp.newt.event.KeyEvent nativeEvent,
int peAction) {
int peModifiers = nativeEvent.getModifiers() &
(InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK |
InputEvent.META_MASK |
InputEvent.ALT_MASK);
short code = nativeEvent.getKeyCode();
char keyChar;
int keyCode;
if (isPCodedKey(code)) {
keyCode = mapToPConst(code);
keyChar = PConstants.CODED;
} else if (isHackyKey(code)) {
// we can return only one char for ENTER, let it be \n everywhere
keyCode = code == com.jogamp.newt.event.KeyEvent.VK_ENTER ?
PConstants.ENTER : code;
keyChar = hackToChar(code, nativeEvent.getKeyChar());
} else {
keyCode = code;
keyChar = nativeEvent.getKeyChar();
}
// From http://jogamp.org/deployment/v2.1.0/javadoc/jogl/javadoc/com/jogamp/newt/event/KeyEvent.html
// public final short getKeySymbol()
// Returns the virtual key symbol reflecting the current keyboard layout.
// public final short getKeyCode()
// Returns the virtual key code using a fixed mapping to the US keyboard layout.
// In contrast to key symbol, key code uses a fixed US keyboard layout and therefore is keyboard layout independent.
// E.g. virtual key code VK_Y denotes the same physical key regardless whether keyboard layout QWERTY or QWERTZ is active. The key symbol of the former is VK_Y, where the latter produces VK_Y.
KeyEvent ke = new KeyEvent(nativeEvent, nativeEvent.getWhen(),
peAction, peModifiers,
keyChar,
keyCode,
nativeEvent.isAutoRepeat());
sketch.postEvent(ke);
if (!isPCodedKey(code) && !isHackyKey(code)) {
if (peAction == KeyEvent.PRESS) {
// Create key typed event
// TODO: combine dead keys with the following key
KeyEvent tke = new KeyEvent(nativeEvent, nativeEvent.getWhen(),
KeyEvent.TYPE, peModifiers,
keyChar,
0,
nativeEvent.isAutoRepeat());
sketch.postEvent(tke);
}
}
}
private static boolean isPCodedKey(short code) {
return code == com.jogamp.newt.event.KeyEvent.VK_UP ||
code == com.jogamp.newt.event.KeyEvent.VK_DOWN ||
code == com.jogamp.newt.event.KeyEvent.VK_LEFT ||
code == com.jogamp.newt.event.KeyEvent.VK_RIGHT ||
code == com.jogamp.newt.event.KeyEvent.VK_ALT ||
code == com.jogamp.newt.event.KeyEvent.VK_CONTROL ||
code == com.jogamp.newt.event.KeyEvent.VK_SHIFT ||
code == com.jogamp.newt.event.KeyEvent.VK_WINDOWS;
}
// Why do we need this mapping?
// Relevant discussion and links here:
// http://forum.jogamp.org/Newt-wrong-keycode-for-key-td4033690.html#a4033697
// (I don't think this is a complete solution).
private static int mapToPConst(short code) {
switch (code) {
case com.jogamp.newt.event.KeyEvent.VK_UP:
return PConstants.UP;
case com.jogamp.newt.event.KeyEvent.VK_DOWN:
return PConstants.DOWN;
case com.jogamp.newt.event.KeyEvent.VK_LEFT:
return PConstants.LEFT;
case com.jogamp.newt.event.KeyEvent.VK_RIGHT:
return PConstants.RIGHT;
case com.jogamp.newt.event.KeyEvent.VK_ALT:
return PConstants.ALT;
case com.jogamp.newt.event.KeyEvent.VK_CONTROL:
return PConstants.CONTROL;
case com.jogamp.newt.event.KeyEvent.VK_SHIFT:
return PConstants.SHIFT;
case com.jogamp.newt.event.KeyEvent.VK_WINDOWS:
return java.awt.event.KeyEvent.VK_META;
default:
return code;
}
}
private static boolean isHackyKey(short code) {
switch (code) {
case com.jogamp.newt.event.KeyEvent.VK_BACK_SPACE:
case com.jogamp.newt.event.KeyEvent.VK_TAB:
case com.jogamp.newt.event.KeyEvent.VK_ENTER:
case com.jogamp.newt.event.KeyEvent.VK_ESCAPE:
case com.jogamp.newt.event.KeyEvent.VK_DELETE:
return true;
}
return false;
}
private static char hackToChar(short code, char def) {
switch (code) {
case com.jogamp.newt.event.KeyEvent.VK_BACK_SPACE:
return PConstants.BACKSPACE;
case com.jogamp.newt.event.KeyEvent.VK_TAB:
return PConstants.TAB;
case com.jogamp.newt.event.KeyEvent.VK_ENTER:
return PConstants.ENTER;
case com.jogamp.newt.event.KeyEvent.VK_ESCAPE:
return PConstants.ESC;
case com.jogamp.newt.event.KeyEvent.VK_DELETE:
return PConstants.DELETE;
}
return def;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
class CursorInfo {
PImage image;
int x, y;
CursorInfo(PImage image, int x, int y) {
this.image = image;
this.x = x;
this.y = y;
}
void set() {
setCursor(image, x, y);
}
}
static Map<Integer, CursorInfo> cursors = new HashMap<>();
static Map<Integer, String> cursorNames = new HashMap<>();
static {
cursorNames.put(PConstants.ARROW, "arrow");
cursorNames.put(PConstants.CROSS, "cross");
cursorNames.put(PConstants.WAIT, "wait");
cursorNames.put(PConstants.MOVE, "move");
cursorNames.put(PConstants.HAND, "hand");
cursorNames.put(PConstants.TEXT, "text");
}
public void setCursor(int kind) {
if (!cursorNames.containsKey(kind)) {
PGraphics.showWarning("Unknown cursor type: " + kind);
return;
}
CursorInfo cursor = cursors.get(kind);
if (cursor == null) {
String name = cursorNames.get(kind);
if (name != null) {
ImageIcon icon =
new ImageIcon(getClass().getResource("cursors/" + name + ".png"));
PImage img = new PImage(icon.getImage());
// Most cursors just use the center as the hotspot...
int x = img.width / 2;
int y = img.height / 2;
// ...others are more specific
if (kind == PConstants.ARROW) {
x = 10; y = 7;
} else if (kind == PConstants.HAND) {
x = 12; y = 8;
} else if (kind == PConstants.TEXT) {
x = 16; y = 22;
}
cursor = new CursorInfo(img, x, y);
cursors.put(kind, cursor);
}
}
if (cursor != null) {
cursor.set();
} else {
PGraphics.showWarning("Cannot load cursor type: " + kind);
}
}
public void setCursor(PImage image, int hotspotX, int hotspotY) {
Display disp = window.getScreen().getDisplay();
BufferedImage bimg = (BufferedImage)image.getNative();
DataBufferInt dbuf = (DataBufferInt)bimg.getData().getDataBuffer();
int[] ipix = dbuf.getData();
ByteBuffer pixels = ByteBuffer.allocate(ipix.length * 4);
pixels.asIntBuffer().put(ipix);
PixelFormat format = PixelFormat.ARGB8888;
final Dimension size = new Dimension(bimg.getWidth(), bimg.getHeight());
PixelRectangle pixelrect = new PixelRectangle.GenericPixelRect(format, size, 0, false, pixels);
final PointerIcon pi = disp.createPointerIcon(pixelrect, hotspotX, hotspotY);
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setPointerVisible(true);
window.setPointerIcon(pi);
}
});
}
public void showCursor() {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setPointerVisible(true);
}
});
}
public void hideCursor() {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setPointerVisible(false);
}
});
}
}
| processing/processing | core/src/processing/opengl/PSurfaceJOGL.java |
45,307 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.packages;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Interner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.bugreport.BugReport;
import com.google.devtools.build.lib.cmdline.BazelModuleContext;
import com.google.devtools.build.lib.cmdline.BazelModuleContext.LoadGraphVisitor;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.cmdline.TargetPattern;
import com.google.devtools.build.lib.collect.CollectionUtils;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.packages.Package.Builder.PackageSettings;
import com.google.devtools.build.lib.packages.WorkspaceFileValue.WorkspaceFileKey;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.PackageLoading;
import com.google.devtools.build.lib.server.FailureDetails.PackageLoading.Code;
import com.google.devtools.build.lib.skyframe.serialization.DeserializationContext;
import com.google.devtools.build.lib.skyframe.serialization.ObjectCodec;
import com.google.devtools.build.lib.skyframe.serialization.SerializationContext;
import com.google.devtools.build.lib.skyframe.serialization.SerializationException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Semaphore;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Module;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.eval.SymbolGenerator;
import net.starlark.java.syntax.Location;
/**
* A package, which is a container of {@link Rule}s, each of which contains a dictionary of named
* attributes.
*
* <p>Package instances are intended to be immutable and for all practical purposes can be treated
* as such. Note, however, that some member variables exposed via the public interface are not
* strictly immutable, so until their types are guaranteed immutable we're not applying the
* {@code @Immutable} annotation here.
*
* <p>This class should not be extended - it's only non-final for mocking!
*
* <p>When changing this class, make sure to make corresponding changes to serialization!
*/
@SuppressWarnings("JavaLangClash")
public class Package {
private final Metadata metadata;
/**
* The "workspace name" of packages generated by Bzlmod to contain repo rules.
*
* <p>Normally, packages containing repo rules are differentiated from packages containing build
* rules by the {@link PackageIdentifier}: The singular repo-rule-containing package is {@code
* //external}. However, in Bzlmod, packages containing repo rules need to have meaningful {@link
* PackageIdentifier}s, so there needs to be some other way to distinguish them from
* build-rule-containing packages. We use the following magic string as the "workspace name" for
* repo-rule-containing packages generated by Bzlmod.
*
* @see #isRepoRulePackage()
*/
private static final String DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES = "__dummy_workspace_bzlmod";
/** Sentinel value for package overhead being empty. */
private static final long PACKAGE_OVERHEAD_UNSET = -1;
/**
* The collection of all targets defined in this package, indexed by name.
*
* <p>Note that a target and a macro may share the same name.
*/
private ImmutableSortedMap<String, Target> targets;
/**
* The collection of all symbolic macro instances defined in this package, indexed by name.
*
* <p>Note that a target and a macro may share the same name.
*/
// TODO(#19922): Enforce that macro namespaces are "exclusive", meaning that target names may only
// suffix a macro name when the target is created (transitively) within the macro.
private ImmutableSortedMap<String, MacroInstance> macros;
public PackageArgs getPackageArgs() {
return metadata.packageArgs;
}
/**
* How to enforce config_setting visibility settings.
*
* <p>This is a temporary setting in service of https://github.com/bazelbuild/bazel/issues/12669.
* After enough depot cleanup, config_setting will have the same visibility enforcement as all
* other rules.
*/
public enum ConfigSettingVisibilityPolicy {
/** Don't enforce visibility for any config_setting. */
LEGACY_OFF,
/** Honor explicit visibility settings on config_setting, else use //visibility:public. */
DEFAULT_PUBLIC,
/** Enforce config_setting visibility exactly the same as all other rules. */
DEFAULT_STANDARD
}
/**
* True iff this package's BUILD files contained lexical or grammatical errors, or experienced
* errors during evaluation, or semantic errors during the construction of any rule.
*
* <p>Note: A package containing errors does not necessarily prevent a build; if all the rules
* needed for a given build were constructed prior to the first error, the build may proceed.
*/
private boolean containsErrors;
/**
* The first detailed error encountered during this package's construction and evaluation, or
* {@code null} if there were no such errors or all its errors lacked details.
*/
@Nullable private FailureDetail failureDetail;
/**
* The map from each repository to that repository's remappings map. This is only used in the
* //external package, it is an empty map for all other packages. For example, an entry of {"@foo"
* : {"@x", "@y"}} indicates that, within repository foo, "@x" should be remapped to "@y".
*/
private ImmutableMap<RepositoryName, ImmutableMap<String, RepositoryName>>
externalPackageRepositoryMappings;
/**
* A rough approximation of the memory and general accounting costs associated with a loaded
* package. A value of -1 means it is unset. Stored as a long to take up less memory per pkg.
*/
private long packageOverhead = PACKAGE_OVERHEAD_UNSET;
/** Returns package overhead as configured by the configured {@link PackageOverheadEstimator}. */
public OptionalLong getPackageOverhead() {
return packageOverhead == PACKAGE_OVERHEAD_UNSET
? OptionalLong.empty()
: OptionalLong.of(packageOverhead);
}
/** Sets package overhead as configured by the configured {@link PackageOverheadEstimator}. */
void setPackageOverhead(OptionalLong packageOverhead) {
this.packageOverhead =
packageOverhead.isPresent() ? packageOverhead.getAsLong() : PACKAGE_OVERHEAD_UNSET;
}
private ImmutableList<TargetPattern> registeredExecutionPlatforms;
private ImmutableList<TargetPattern> registeredToolchains;
private OptionalInt firstWorkspaceSuffixRegisteredToolchain;
private long computationSteps;
/** Returns the number of Starlark computation steps executed by this BUILD file. */
public long getComputationSteps() {
return computationSteps;
}
/**
* Constructs a new (incomplete) Package instance. Intended only for use by {@link
* Package.Builder}.
*
* <p>Packages and Targets refer to one another. Therefore, the builder needs to have a Package
* instance on-hand before it can associate any targets with the package. Certain Metadata fields
* like the package's name must be known before that point, while other fields are filled in when
* the builder calls {@link Package#finishInit}.
*/
// TODO(#19922): Better separate fields that must be known a priori from those determined through
// BUILD evaluation.
private Package(Metadata metadata) {
this.metadata = metadata;
}
/** Returns this package's identifier. */
public PackageIdentifier getPackageIdentifier() {
return metadata.packageIdentifier;
}
/**
* Whether this package should contain only repo rules (returns {@code true}) or only build rules
* (returns {@code false}).
*/
private boolean isRepoRulePackage() {
return metadata.packageIdentifier.equals(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER)
|| metadata.workspaceName.equals(DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES);
}
/**
* Returns the repository mapping for the requested external repository.
*
* @throws UnsupportedOperationException if called from a package other than the //external
* package
*/
public ImmutableMap<String, RepositoryName> getRepositoryMapping(RepositoryName repository) {
if (!isRepoRulePackage()) {
throw new UnsupportedOperationException(
"Can only access the external package repository"
+ "mappings from the //external package");
}
return externalPackageRepositoryMappings.getOrDefault(repository, ImmutableMap.of());
}
/** Get the repository mapping for this package. */
public RepositoryMapping getRepositoryMapping() {
return metadata.repositoryMapping;
}
/**
* Returns the full map of repository mappings collected so far.
*
* @throws UnsupportedOperationException if called from a package other than the //external
* package
*/
ImmutableMap<RepositoryName, ImmutableMap<String, RepositoryName>>
getExternalPackageRepositoryMappings() {
if (!isRepoRulePackage()) {
throw new UnsupportedOperationException(
"Can only access the external package repository"
+ "mappings from the //external package");
}
return this.externalPackageRepositoryMappings;
}
/**
* Returns the source root (a directory) beneath which this package's BUILD file was found, or
* {@link Optional#empty} if this package was derived from a workspace file.
*
* <p>Assumes invariant: If non-empty, {@code
* getSourceRoot().get().getRelative(packageId.getSourceRoot()).equals(getPackageDirectory())}
*/
public Optional<Root> getSourceRoot() {
return metadata.sourceRoot;
}
private static Root getSourceRoot(RootedPath buildFileRootedPath, PathFragment packageFragment) {
PathFragment packageDirectory = buildFileRootedPath.getRootRelativePath().getParentDirectory();
if (packageFragment.equals(packageDirectory)) {
// Fast path: BUILD file path and package name are the same, don't create an extra root.
return buildFileRootedPath.getRoot();
}
PathFragment current = buildFileRootedPath.asPath().asFragment().getParentDirectory();
for (int i = 0, len = packageFragment.segmentCount(); i < len && current != null; i++) {
current = current.getParentDirectory();
}
if (current == null || current.isEmpty()) {
// This is never really expected to work. The check below in #finishInit should fail.
return buildFileRootedPath.getRoot();
}
// Note that current is an absolute path.
return Root.fromPath(buildFileRootedPath.getRoot().getRelative(current));
}
/**
* Completes the initialization of this package. Only after this method may a package by shared
* publicly.
*/
private void finishInit(Builder builder) {
String baseName = metadata.filename.getRootRelativePath().getBaseName();
this.containsErrors |= builder.containsErrors;
if (metadata.directLoads == null && metadata.transitiveLoads == null) {
Preconditions.checkState(containsErrors, "Loads not set for error-free package");
builder.setLoads(ImmutableList.of());
}
if (isWorkspaceFile(baseName) || isModuleDotBazelFile(baseName)) {
Preconditions.checkState(isRepoRulePackage());
this.metadata.sourceRoot = Optional.empty();
} else {
Root sourceRoot =
getSourceRoot(metadata.filename, metadata.packageIdentifier.getSourceRoot());
if (sourceRoot.asPath() == null
|| !sourceRoot
.getRelative(metadata.packageIdentifier.getSourceRoot())
.equals(metadata.packageDirectory)) {
throw new IllegalArgumentException(
"Invalid BUILD file name for package '"
+ metadata.packageIdentifier
+ "': "
+ metadata.filename
+ " (in source "
+ sourceRoot
+ " with packageDirectory "
+ metadata.packageDirectory
+ " and package identifier source root "
+ metadata.packageIdentifier.getSourceRoot()
+ ")");
}
this.metadata.sourceRoot = Optional.of(sourceRoot);
}
this.metadata.makeEnv = ImmutableMap.copyOf(builder.makeEnv);
this.targets = ImmutableSortedMap.copyOf(builder.targets);
this.macros = ImmutableSortedMap.copyOf(builder.macros);
this.failureDetail = builder.getFailureDetail();
this.registeredExecutionPlatforms = ImmutableList.copyOf(builder.registeredExecutionPlatforms);
this.registeredToolchains = ImmutableList.copyOf(builder.registeredToolchains);
this.firstWorkspaceSuffixRegisteredToolchain = builder.firstWorkspaceSuffixRegisteredToolchain;
ImmutableMap.Builder<RepositoryName, ImmutableMap<String, RepositoryName>>
repositoryMappingsBuilder = ImmutableMap.builder();
if (!builder.externalPackageRepositoryMappings.isEmpty() && !builder.isRepoRulePackage()) {
// 'repo_mapping' should only be used in the //external package, i.e. should only appear
// in WORKSPACE files. Currently, if someone tries to use 'repo_mapping' in a BUILD rule, they
// will get a "no such attribute" error. This check is to protect against a 'repo_mapping'
// attribute being added to a rule in the future.
throw new IllegalArgumentException(
"'repo_mapping' may only be used in the //external package");
}
builder.externalPackageRepositoryMappings.forEach(
(k, v) -> repositoryMappingsBuilder.put(k, ImmutableMap.copyOf(v)));
this.externalPackageRepositoryMappings = repositoryMappingsBuilder.buildOrThrow();
setPackageOverhead(builder.packageOverheadEstimator.estimatePackageOverhead(this));
}
private static boolean isWorkspaceFile(String baseFileName) {
return baseFileName.equals(LabelConstants.WORKSPACE_DOT_BAZEL_FILE_NAME.getPathString())
|| baseFileName.equals(LabelConstants.WORKSPACE_FILE_NAME.getPathString());
}
private static boolean isModuleDotBazelFile(String baseFileName) {
return baseFileName.equals(LabelConstants.MODULE_DOT_BAZEL_FILE_NAME.getPathString());
}
public Metadata getMetadata() {
return metadata;
}
/**
* Returns a list of Starlark files transitively loaded by this package.
*
* <p>If transitive loads are not {@linkplain PackageSettings#precomputeTransitiveLoads
* precomputed}, performs a traversal over the load graph to compute them.
*
* <p>If only the count of transitively loaded files is needed, use {@link
* #countTransitivelyLoadedStarlarkFiles}. For a customized online visitation, use {@link
* #visitLoadGraph}.
*/
public ImmutableList<Label> getOrComputeTransitivelyLoadedStarlarkFiles() {
// TODO(bazel-team): Seems like a code smell that Metadata fields are being mutated here,
// possibly after package construction is complete.
return metadata.transitiveLoads != null
? metadata.transitiveLoads
: computeTransitiveLoads(metadata.directLoads);
}
/**
* Counts the number Starlark files transitively loaded by this package.
*
* <p>If transitive loads are not {@linkplain PackageSettings#precomputeTransitiveLoads
* precomputed}, performs a traversal over the load graph to count them.
*/
public int countTransitivelyLoadedStarlarkFiles() {
if (metadata.transitiveLoads != null) {
return metadata.transitiveLoads.size();
}
Set<Label> loads = new HashSet<>();
visitLoadGraph(loads::add);
return loads.size();
}
/**
* Performs an online visitation of the load graph rooted at this package.
*
* <p>If transitive loads were {@linkplain PackageSettings#precomputeTransitiveLoads precomputed},
* each file is passed to {@link LoadGraphVisitor#visit} once regardless of its return value.
*/
public <E1 extends Exception, E2 extends Exception> void visitLoadGraph(
LoadGraphVisitor<E1, E2> visitor) throws E1, E2 {
if (metadata.transitiveLoads != null) {
for (Label load : metadata.transitiveLoads) {
visitor.visit(load);
}
} else {
BazelModuleContext.visitLoadGraphRecursively(metadata.directLoads, visitor);
}
}
private static ImmutableList<Label> computeTransitiveLoads(Iterable<Module> directLoads) {
Set<Label> loads = new LinkedHashSet<>();
BazelModuleContext.visitLoadGraphRecursively(directLoads, loads::add);
return ImmutableList.copyOf(loads);
}
/**
* Returns the filename of the BUILD file which defines this package. The parent directory of the
* BUILD file is the package directory.
*/
public RootedPath getFilename() {
return metadata.filename;
}
/** Returns the directory containing the package's BUILD file. */
public Path getPackageDirectory() {
return metadata.packageDirectory;
}
/**
* Returns the name of this package. If this build is using external repositories then this name
* may not be unique!
*/
public String getName() {
return metadata.getName();
}
/** Like {@link #getName}, but has type {@code PathFragment}. */
public PathFragment getNameFragment() {
return metadata.getNameFragment();
}
/** Returns all make variables for a given platform. */
public ImmutableMap<String, String> getMakeEnvironment() {
return metadata.makeEnv;
}
/**
* Returns the label of this package's BUILD file.
*
* <p>Typically <code>getBuildFileLabel().getName().equals("BUILD")</code> -- though not
* necessarily: data in a subdirectory of a test package may use a different filename to avoid
* inadvertently creating a new package.
*/
public Label getBuildFileLabel() {
return metadata.buildFile.getLabel();
}
/** Returns the InputFile target for this package's BUILD file. */
public InputFile getBuildFile() {
return metadata.buildFile;
}
/**
* Returns true if errors were encountered during evaluation of this package. (The package may be
* incomplete and its contents should not be relied upon for critical operations. However, any
* Rules belonging to the package are guaranteed to be intact, unless their <code>containsErrors()
* </code> flag is set.)
*/
public boolean containsErrors() {
return containsErrors;
}
/**
* If {@code pkg.containsErrors()}, sends an errorful "package contains errors" {@link Event}
* (augmented with {@code pkg.getFailureDetail()}, if present) to the given {@link EventHandler}.
*/
public static void maybeAddPackageContainsErrorsEventToHandler(
Package pkg, EventHandler eventHandler) {
if (pkg.containsErrors()) {
eventHandler.handle(
Event.error(
String.format(
"package contains errors: %s%s",
pkg.getNameFragment(),
pkg.getFailureDetail() != null
? ": " + pkg.getFailureDetail().getMessage()
: "")));
}
}
// TODO(bazel-team): Seems like we shouldn't permit this mutation on an already-initialized
// Package. Is it possible for this to be called today after initialization?
void setContainsErrors() {
containsErrors = true;
}
/**
* Returns the first {@link FailureDetail} describing one of the package's errors, or {@code null}
* if it has no errors or all its errors lack details.
*/
@Nullable
public FailureDetail getFailureDetail() {
return failureDetail;
}
/**
* Returns a {@link FailureDetail} attributing a target error to the package's {@link
* FailureDetail}, or a generic {@link Code#TARGET_MISSING} failure detail if the package has
* none.
*
* <p>May only be called when {@link #containsErrors()} is true and with a target whose package is
* this one.
*/
public FailureDetail contextualizeFailureDetailForTarget(Target target) {
Preconditions.checkState(
target.getPackage().metadata.packageIdentifier.equals(metadata.packageIdentifier),
"contextualizeFailureDetailForTarget called for target not in package. target=%s,"
+ " package=%s",
target,
this);
Preconditions.checkState(
containsErrors,
"contextualizeFailureDetailForTarget called for package not in error. target=%s",
target);
String prefix =
"Target '" + target.getLabel() + "' contains an error and its package is in error";
if (failureDetail == null) {
return FailureDetail.newBuilder()
.setMessage(prefix)
.setPackageLoading(PackageLoading.newBuilder().setCode(Code.TARGET_MISSING))
.build();
}
return failureDetail.toBuilder().setMessage(prefix + ": " + failureDetail.getMessage()).build();
}
/** Returns an (immutable, ordered) view of all the targets belonging to this package. */
public ImmutableSortedMap<String, Target> getTargets() {
return targets;
}
/** Common getTargets implementation, accessible by {@link Package.Builder}. */
private static Set<Target> getTargets(BiMap<String, Target> targetMap) {
return targetMap.values();
}
/**
* Returns a (read-only, ordered) iterable of all the targets belonging to this package which are
* instances of the specified class.
*/
public <T extends Target> Iterable<T> getTargets(Class<T> targetClass) {
return getTargets(targets, targetClass);
}
/**
* Common getTargets implementation, accessible by both {@link Package} and {@link
* Package.Builder}.
*/
private static <T extends Target> Iterable<T> getTargets(
Map<String, Target> targetMap, Class<T> targetClass) {
return Iterables.filter(targetMap.values(), targetClass);
}
/**
* Returns the rule that corresponds to a particular BUILD target name. Useful for walking through
* the dependency graph of a target. Fails if the target is not a Rule.
*/
public Rule getRule(String targetName) {
return (Rule) targets.get(targetName);
}
/** Returns this package's workspace name. */
public String getWorkspaceName() {
return metadata.workspaceName;
}
/**
* Returns the target (a member of this package) whose name is "targetName". First rules are
* searched, then output files, then input files. The target name must be valid, as defined by
* {@code LabelValidator#validateTargetName}.
*
* @throws NoSuchTargetException if the specified target was not found.
*/
public Target getTarget(String targetName) throws NoSuchTargetException {
Target target = targets.get(targetName);
if (target != null) {
return target;
}
Label label;
try {
label = Label.create(metadata.packageIdentifier, targetName);
} catch (LabelSyntaxException e) {
throw new IllegalArgumentException(targetName, e);
}
if (metadata.succinctTargetNotFoundErrors) {
throw new NoSuchTargetException(
label, String.format("target '%s' not declared in package '%s'", targetName, getName()));
} else {
String alternateTargetSuggestion = getAlternateTargetSuggestion(targetName);
throw new NoSuchTargetException(
label,
String.format(
"target '%s' not declared in package '%s' defined by %s%s",
targetName,
getName(),
metadata.filename.asPath().getPathString(),
alternateTargetSuggestion));
}
}
private String getAlternateTargetSuggestion(String targetName) {
// If there's a file on the disk that's not mentioned in the BUILD file,
// produce a more informative error. NOTE! this code path is only executed
// on failure, which is (relatively) very rare. In the common case no
// stat(2) is executed.
Path filename = metadata.packageDirectory.getRelative(targetName);
if (!PathFragment.isNormalized(targetName) || "*".equals(targetName)) {
// Don't check for file existence if the target name is not normalized
// because the error message would be confusing and wrong. If the
// targetName is "foo/bar/.", and there is a directory "foo/bar", it
// doesn't mean that "//pkg:foo/bar/." is a valid label.
// Also don't check if the target name is a single * character since
// it's invalid on Windows.
return "";
} else if (filename.isDirectory()) {
return "; however, a source directory of this name exists. (Perhaps add "
+ "'exports_files([\""
+ targetName
+ "\"])' to "
+ getName()
+ "/BUILD, or define a "
+ "filegroup?)";
} else if (filename.exists()) {
return "; however, a source file of this name exists. (Perhaps add "
+ "'exports_files([\""
+ targetName
+ "\"])' to "
+ getName()
+ "/BUILD?)";
} else {
return TargetSuggester.suggestTargets(targetName, targets.keySet());
}
}
/** Returns all symbolic macros defined in the package. */
// TODO(#19922): Clarify this comment to indicate whether the macros have already been expanded
// by the point the Package has been built. The answer's probably "yes". In that case, this
// accessor is still useful for introspecting e.g. by `bazel query`.
public ImmutableMap<String, MacroInstance> getMacros() {
return macros;
}
/**
* How to enforce visibility on <code>config_setting</code> See {@link
* ConfigSettingVisibilityPolicy} for details.
*/
public ConfigSettingVisibilityPolicy getConfigSettingVisibilityPolicy() {
return metadata.configSettingVisibilityPolicy;
}
public ImmutableList<TargetPattern> getRegisteredExecutionPlatforms() {
return registeredExecutionPlatforms;
}
public ImmutableList<TargetPattern> getRegisteredToolchains() {
return registeredToolchains;
}
public ImmutableList<TargetPattern> getUserRegisteredToolchains() {
return getRegisteredToolchains()
.subList(
0, firstWorkspaceSuffixRegisteredToolchain.orElse(getRegisteredToolchains().size()));
}
public ImmutableList<TargetPattern> getWorkspaceSuffixRegisteredToolchains() {
return getRegisteredToolchains()
.subList(
firstWorkspaceSuffixRegisteredToolchain.orElse(getRegisteredToolchains().size()),
getRegisteredToolchains().size());
}
OptionalInt getFirstWorkspaceSuffixRegisteredToolchain() {
return firstWorkspaceSuffixRegisteredToolchain;
}
@Override
public String toString() {
return "Package("
+ getName()
+ ")="
+ (targets != null ? getTargets(Rule.class) : "initializing...");
}
/**
* Dumps the package for debugging. Do not depend on the exact format/contents of this debugging
* output.
*/
public void dump(PrintStream out) {
out.println(" Package " + getName() + " (" + metadata.filename.asPath() + ")");
// Rules:
out.println(" Rules");
for (Rule rule : getTargets(Rule.class)) {
out.println(" " + rule.getTargetKind() + " " + rule.getLabel());
for (Attribute attr : rule.getAttributes()) {
for (Object possibleValue :
AggregatingAttributeMapper.of(rule).visitAttribute(attr.getName(), attr.getType())) {
out.println(" " + attr.getName() + " = " + possibleValue);
}
}
}
// Files:
out.println(" Files");
for (FileTarget file : getTargets(FileTarget.class)) {
out.print(" " + file.getTargetKind() + " " + file.getLabel());
if (file instanceof OutputFile) {
out.println(" (generated by " + ((OutputFile) file).getGeneratingRule().getLabel() + ")");
} else {
out.println();
}
}
}
/**
* Returns a new {@link Builder} suitable for constructing an ordinary package (i.e. not one for
* WORKSPACE or bzlmod).
*/
public static Builder newPackageBuilder(
PackageSettings packageSettings,
PackageIdentifier id,
RootedPath filename,
String workspaceName,
Optional<String> associatedModuleName,
Optional<String> associatedModuleVersion,
boolean noImplicitFileExport,
RepositoryMapping repositoryMapping,
@Nullable Semaphore cpuBoundSemaphore,
PackageOverheadEstimator packageOverheadEstimator,
@Nullable ImmutableMap<Location, String> generatorMap,
// TODO(bazel-team): See Builder() constructor comment about use of null for this param.
@Nullable ConfigSettingVisibilityPolicy configSettingVisibilityPolicy,
@Nullable Globber globber) {
return new Builder(
BazelStarlarkContext.Phase.LOADING,
SymbolGenerator.create(id),
packageSettings,
id,
filename,
workspaceName,
associatedModuleName,
associatedModuleVersion,
noImplicitFileExport,
repositoryMapping,
cpuBoundSemaphore,
packageOverheadEstimator,
generatorMap,
configSettingVisibilityPolicy,
globber);
}
public static Builder newExternalPackageBuilder(
PackageSettings packageSettings,
WorkspaceFileKey workspaceFileKey,
String workspaceName,
RepositoryMapping mainRepoMapping,
boolean noImplicitFileExport,
PackageOverheadEstimator packageOverheadEstimator) {
return new Builder(
BazelStarlarkContext.Phase.WORKSPACE,
// The SymbolGenerator is based on workspaceFileKey rather than a package id or path,
// in order to distinguish different chunks of the same WORKSPACE file.
SymbolGenerator.create(workspaceFileKey),
packageSettings,
LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER,
/* filename= */ workspaceFileKey.getPath(),
workspaceName,
/* associatedModuleName= */ Optional.empty(),
/* associatedModuleVersion= */ Optional.empty(),
noImplicitFileExport,
/* repositoryMapping= */ mainRepoMapping,
/* cpuBoundSemaphore= */ null,
packageOverheadEstimator,
/* generatorMap= */ null,
/* configSettingVisibilityPolicy= */ null,
/* globber= */ null);
}
public static Builder newExternalPackageBuilderForBzlmod(
RootedPath moduleFilePath,
boolean noImplicitFileExport,
PackageIdentifier basePackageId,
RepositoryMapping repoMapping) {
return new Builder(
BazelStarlarkContext.Phase.LOADING,
SymbolGenerator.create(basePackageId),
PackageSettings.DEFAULTS,
basePackageId,
/* filename= */ moduleFilePath,
DUMMY_WORKSPACE_NAME_FOR_BZLMOD_PACKAGES,
/* associatedModuleName= */ Optional.empty(),
/* associatedModuleVersion= */ Optional.empty(),
noImplicitFileExport,
repoMapping,
/* cpuBoundSemaphore= */ null,
PackageOverheadEstimator.NOOP_ESTIMATOR,
/* generatorMap= */ null,
/* configSettingVisibilityPolicy= */ null,
/* globber= */ null)
.setLoads(ImmutableList.of());
}
/**
* Returns an error {@link Event} with {@link Location} and {@link DetailedExitCode} properties.
*/
public static Event error(Location location, String message, Code code) {
Event error = Event.error(location, message);
return error.withProperty(DetailedExitCode.class, createDetailedCode(message, code));
}
private static DetailedExitCode createDetailedCode(String errorMessage, Code code) {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(errorMessage)
.setPackageLoading(PackageLoading.newBuilder().setCode(code))
.build());
}
/**
* A builder for {@link Package} objects. Only intended to be used by {@link PackageFactory} and
* {@link com.google.devtools.build.lib.skyframe.PackageFunction}.
*/
public static class Builder extends TargetDefinitionContext {
/**
* A bundle of options affecting package construction, that is not specific to any particular
* package.
*/
public interface PackageSettings {
/**
* Returns whether or not extra detail should be added to {@link NoSuchTargetException}s
* thrown from {@link #getTarget}. Useful for toning down verbosity in situations where it can
* be less helpful.
*/
default boolean succinctTargetNotFoundErrors() {
return false;
}
/**
* Determines whether to precompute a list of transitively loaded starlark files while
* building packages.
*
* <p>Typically, direct loads are stored as a {@code ImmutableList<Module>}. This is
* sufficient to reconstruct the full load graph by recursively traversing {@link
* BazelModuleContext#loads}. If the package is going to be serialized, however, it may make
* more sense to precompute a flat list containing the labels of all transitively loaded bzl
* files since {@link Module} is costly to serialize.
*
* <p>If this returns {@code true}, transitive loads are stored as an {@code
* ImmutableList<Label>} and direct loads are not stored.
*/
default boolean precomputeTransitiveLoads() {
return false;
}
PackageSettings DEFAULTS = new PackageSettings() {};
}
private final SymbolGenerator<?> symbolGenerator;
/**
* The output instance for this builder. Needs to be instantiated and available with name info
* throughout initialization. All other settings are applied during {@link #build}. See {@link
* Package#Package} and {@link Package#finishInit} for details.
*/
private final Package pkg;
private final boolean precomputeTransitiveLoads;
private final boolean noImplicitFileExport;
// The map from each repository to that repository's remappings map.
// This is only used in the //external package, it is an empty map for all other packages.
private final HashMap<RepositoryName, HashMap<String, RepositoryName>>
externalPackageRepositoryMappings = new HashMap<>();
/** Converts label literals to Label objects within this package. */
private final LabelConverter labelConverter;
/** Estimates the package overhead of this package. */
private final PackageOverheadEstimator packageOverheadEstimator;
/**
* Semaphore held by the Skyframe thread when performing CPU work.
*
* <p>This should be released when performing I/O.
*/
@Nullable // Only non-null when inside PackageFunction.compute and the semaphore is enabled.
private final Semaphore cpuBoundSemaphore;
// TreeMap so that the iteration order of variables is consistent regardless of insertion order
// (which may change due to serialization). This is useful so that the serialized representation
// is deterministic.
private final TreeMap<String, String> makeEnv = new TreeMap<>();
private final StoredEventHandler localEventHandler = new StoredEventHandler();
@Nullable private String ioExceptionMessage = null;
@Nullable private IOException ioException = null;
@Nullable private DetailedExitCode ioExceptionDetailedExitCode = null;
// TODO(#19922): Consider having separate containsErrors fields on Metadata and Package. In that
// case, this field is replaced by the one on Metadata.
private boolean containsErrors = false;
// A package's FailureDetail field derives from the events on its Builder's event handler.
// During package deserialization, those events are unavailable, because those events aren't
// serialized [*]. Its FailureDetail value is serialized, however. During deserialization, that
// value is assigned here, so that it can be assigned to the deserialized package.
//
// Likewise, during workspace part assembly, errors from parent parts should propagate to their
// children.
//
// [*] Not in the context of the package, anyway. Skyframe values containing a package may
// serialize events emitted during its construction/evaluation.
@Nullable private FailureDetail failureDetailOverride = null;
// Used by glob(). Null for contexts where glob() is disallowed, including WORKSPACE files and
// some tests.
@Nullable private final Globber globber;
private final Map<Label, EnvironmentGroup> environmentGroups = new HashMap<>();
// All targets added to the package. We use SnapshottableBiMap to help track insertion order of
// Rule targets, for use by native.existing_rules().
private BiMap<String, Target> targets =
new SnapshottableBiMap<>(target -> target instanceof Rule);
// All instances of symbolic macros created during package construction.
private final Map<String, MacroInstance> macros = new LinkedHashMap<>();
/**
* A stack of currently executing symbolic macros, outermost first.
*
* <p>Certain APIs are only available when this stack is empty (i.e. not in any symbolic macro).
* See user documentation on {@code macro()} ({@link StarlarkRuleFunctionsApi#macro}).
*/
private final List<MacroInstance> macroStack = new ArrayList<>();
private enum NameConflictCheckingPolicy {
UNKNOWN,
NOT_GUARANTEED,
ENABLED;
}
/**
* Whether to do all validation checks for name clashes among targets, macros, and output file
* prefixes.
*
* <p>The {@code NOT_GUARANTEED} value should only be used when the package data has already
* been validated, e.g. in package deserialization.
*
* <p>Setting it to {@code NOT_GUARANTEED} does not necessarily turn off *all* checking, just
* some of the more expensive ones. Do not rely on being able to violate these checks.
*/
private NameConflictCheckingPolicy nameConflictCheckingPolicy =
NameConflictCheckingPolicy.UNKNOWN;
/**
* Stores labels for each rule so that we don't have to call the costly {@link Rule#getLabels}
* twice (once for {@link #checkForInputOutputConflicts} and once for {@link #beforeBuild}).
*
* <p>This field is null if name conflict checking is disabled. It is also null after the
* package is built.
*/
@Nullable private Map<Rule, List<Label>> ruleLabels = new HashMap<>();
/**
* The collection of the prefixes of every output file. Maps each prefix to an arbitrary output
* file having that prefix. Used for error reporting.
*
* <p>This field is null if name conflict checking is disabled. It is also null after the
* package is built. The content of the map is manipulated only in {@link #checkRuleAndOutputs}.
*/
@Nullable private Map<String, OutputFile> outputFilePrefixes = new HashMap<>();
private final List<TargetPattern> registeredExecutionPlatforms = new ArrayList<>();
private final List<TargetPattern> registeredToolchains = new ArrayList<>();
/**
* Tracks the index within {@link #registeredToolchains} of the first toolchain registered from
* the WORKSPACE suffixes rather than the WORKSPACE file (if any).
*
* <p>This is needed to distinguish between these toolchains during resolution: toolchains
* registered in WORKSPACE have precedence over those defined in non-root Bazel modules, which
* in turn have precedence over those from the WORKSPACE suffixes.
*/
private OptionalInt firstWorkspaceSuffixRegisteredToolchain = OptionalInt.empty();
/** True iff the "package" function has already been called in this package. */
private boolean packageFunctionUsed;
private final Interner<ImmutableList<?>> listInterner = new ThreadCompatibleInterner<>();
private final ImmutableMap<Location, String> generatorMap;
private final TestSuiteImplicitTestsAccumulator testSuiteImplicitTestsAccumulator =
new TestSuiteImplicitTestsAccumulator();
/** Returns the "generator_name" to use for a given call site location in a BUILD file. */
@Nullable
String getGeneratorNameByLocation(Location loc) {
return generatorMap.get(loc);
}
/**
* Returns the value to use for {@code test_suite}s' {@code $implicit_tests} attribute, as-is,
* when the {@code test_suite} doesn't specify an explicit, non-empty {@code tests} value. The
* returned list is mutated by the package-building process - it may be observed to be empty or
* incomplete before package loading is complete. When package loading is complete it will
* contain the label of each non-manual test matching the provided tags in the package, in label
* order.
*
* <p>This method <b>MUST</b> be called before the package is built - otherwise the requested
* implicit tests won't be accumulated.
*/
List<Label> getTestSuiteImplicitTestsRef(List<String> tags) {
return testSuiteImplicitTestsAccumulator.getTestSuiteImplicitTestsRefForTags(tags);
}
@ThreadCompatible
private static final class ThreadCompatibleInterner<T> implements Interner<T> {
private final Map<T, T> interns = new HashMap<>();
@Override
public T intern(T sample) {
T existing = interns.putIfAbsent(sample, sample);
return firstNonNull(existing, sample);
}
}
private boolean alreadyBuilt = false;
private Builder(
BazelStarlarkContext.Phase phase,
SymbolGenerator<?> symbolGenerator,
PackageSettings packageSettings,
PackageIdentifier id,
RootedPath filename,
String workspaceName,
Optional<String> associatedModuleName,
Optional<String> associatedModuleVersion,
boolean noImplicitFileExport,
RepositoryMapping repositoryMapping,
@Nullable Semaphore cpuBoundSemaphore,
PackageOverheadEstimator packageOverheadEstimator,
@Nullable ImmutableMap<Location, String> generatorMap,
// TODO(bazel-team): Config policy is an enum, what is null supposed to mean?
// Maybe convert null -> LEGACY_OFF, assuming that's the correct default.
@Nullable ConfigSettingVisibilityPolicy configSettingVisibilityPolicy,
@Nullable Globber globber) {
super(phase);
this.symbolGenerator = symbolGenerator;
Metadata metadata = new Metadata();
metadata.packageIdentifier = Preconditions.checkNotNull(id);
metadata.filename = filename;
metadata.packageDirectory = filename.asPath().getParentDirectory();
try {
metadata.buildFileLabel = Label.create(id, filename.getRootRelativePath().getBaseName());
} catch (LabelSyntaxException e) {
// This can't actually happen.
throw new AssertionError("Package BUILD file has an illegal name: " + filename, e);
}
metadata.workspaceName = Preconditions.checkNotNull(workspaceName);
metadata.repositoryMapping = Preconditions.checkNotNull(repositoryMapping);
metadata.associatedModuleName = Preconditions.checkNotNull(associatedModuleName);
metadata.associatedModuleVersion = Preconditions.checkNotNull(associatedModuleVersion);
metadata.succinctTargetNotFoundErrors = packageSettings.succinctTargetNotFoundErrors();
metadata.configSettingVisibilityPolicy = configSettingVisibilityPolicy;
this.pkg = new Package(metadata);
this.precomputeTransitiveLoads = packageSettings.precomputeTransitiveLoads();
this.noImplicitFileExport = noImplicitFileExport;
this.labelConverter = new LabelConverter(id, repositoryMapping);
if (pkg.getName().startsWith("javatests/")) {
mergePackageArgsFrom(PackageArgs.builder().setDefaultTestOnly(true));
}
this.cpuBoundSemaphore = cpuBoundSemaphore;
this.packageOverheadEstimator = packageOverheadEstimator;
this.generatorMap = (generatorMap == null) ? ImmutableMap.of() : generatorMap;
this.globber = globber;
// Add target for the BUILD file itself.
// (This may be overridden by an exports_file declaration.)
addInputFile(
new InputFile(
pkg, metadata.buildFileLabel, Location.fromFile(filename.asPath().toString())));
}
SymbolGenerator<?> getSymbolGenerator() {
return symbolGenerator;
}
/** Retrieves this object from a Starlark thread. Returns null if not present. */
@Nullable
public static Builder fromOrNull(StarlarkThread thread) {
BazelStarlarkContext ctx = thread.getThreadLocal(BazelStarlarkContext.class);
return (ctx instanceof Builder) ? (Builder) ctx : null;
}
/**
* Retrieves this object from a Starlark thread. If not present, throws {@code EvalException}
* with an error message indicating that {@code what} can't be used in this Starlark
* environment.
*/
@CanIgnoreReturnValue
public static Builder fromOrFail(StarlarkThread thread, String what) throws EvalException {
@Nullable BazelStarlarkContext ctx = thread.getThreadLocal(BazelStarlarkContext.class);
if (!(ctx instanceof Builder)) {
// This error message might be a little misleading for APIs that can be called from either
// BUILD or WORKSPACE threads. In that case, we expect the calling API will do a separate
// check that we're in a WORKSPACE thread and emit an appropriate message before calling
// fromOrFail().
throw Starlark.errorf(
"%s can only be used while evaluating a BUILD file and its macros", what);
}
return (Builder) ctx;
}
/**
* Same as {@link #fromOrFail}, but also throws {@link EvalException} if we're currently
* executing a symbolic macro implementation.
*
* <p>Use this method when implementing APIs that should not be accessible from symbolic macros,
* such as {@code glob()} or {@code package()}.
*
* <p>This method succeeds when called from a legacy macro (that is not itself called from any
* symbolic macro).
*/
@CanIgnoreReturnValue
public static Builder fromOrFailDisallowingSymbolicMacros(StarlarkThread thread, String what)
throws EvalException {
@Nullable BazelStarlarkContext ctx = thread.getThreadLocal(BazelStarlarkContext.class);
if (ctx instanceof Builder builder) {
if (builder.macroStack.isEmpty()) {
return builder;
}
}
boolean macrosEnabled =
thread
.getSemantics()
.getBool(BuildLanguageOptions.EXPERIMENTAL_ENABLE_FIRST_CLASS_MACROS);
// As in fromOrFail() above, some APIs can be used from either BUILD or WORKSPACE threads,
// so this error message might be misleading (e.g. if a symbolic macro attempts to call a
// feature available in WORKSPACE). But that type of misuse seems unlikely, and WORKSPACE is
// going away soon anyway, so we won't tweak the message for it.
throw Starlark.errorf(
macrosEnabled
? "%s can only be used while evaluating a BUILD file or legacy macro"
: "%s can only be used while evaluating a BUILD file and its macros",
what);
}
PackageIdentifier getPackageIdentifier() {
return pkg.getPackageIdentifier();
}
/**
* Determine whether this package should contain build rules (returns {@code false}) or repo
* rules (returns {@code true}).
*/
boolean isRepoRulePackage() {
return pkg.isRepoRulePackage();
}
String getPackageWorkspaceName() {
return pkg.getWorkspaceName();
}
/**
* Returns the name of the Bzlmod module associated with the repo this package is in. If this
* package is not from a Bzlmod repo, this is empty. For repos generated by module extensions,
* this is the name of the module hosting the extension.
*/
Optional<String> getAssociatedModuleName() {
return pkg.metadata.associatedModuleName;
}
/**
* Returns the version of the Bzlmod module associated with the repo this package is in. If this
* package is not from a Bzlmod repo, this is empty. For repos generated by module extensions,
* this is the version of the module hosting the extension.
*/
Optional<String> getAssociatedModuleVersion() {
return pkg.metadata.associatedModuleVersion;
}
/**
* Updates the externalPackageRepositoryMappings entry for {@code repoWithin}. Adds new entry
* from {@code localName} to {@code mappedName} in {@code repoWithin}'s map.
*
* @param repoWithin the RepositoryName within which the mapping should apply
* @param localName the name that actually appears in the WORKSPACE and BUILD files in the
* {@code repoWithin} repository
* @param mappedName the RepositoryName by which localName should be referenced
*/
@CanIgnoreReturnValue
Builder addRepositoryMappingEntry(
RepositoryName repoWithin, String localName, RepositoryName mappedName) {
HashMap<String, RepositoryName> mapping =
externalPackageRepositoryMappings.computeIfAbsent(
repoWithin, (RepositoryName k) -> new HashMap<>());
mapping.put(localName, mappedName);
return this;
}
/** Adds all the mappings from a given {@link Package}. */
@CanIgnoreReturnValue
Builder addRepositoryMappings(Package aPackage) {
ImmutableMap<RepositoryName, ImmutableMap<String, RepositoryName>> repositoryMappings =
aPackage.externalPackageRepositoryMappings;
for (Map.Entry<RepositoryName, ImmutableMap<String, RepositoryName>> repositoryName :
repositoryMappings.entrySet()) {
for (Map.Entry<String, RepositoryName> repositoryNameRepositoryNameEntry :
repositoryName.getValue().entrySet()) {
addRepositoryMappingEntry(
repositoryName.getKey(),
repositoryNameRepositoryNameEntry.getKey(),
repositoryNameRepositoryNameEntry.getValue());
}
}
return this;
}
public LabelConverter getLabelConverter() {
return labelConverter;
}
Interner<ImmutableList<?>> getListInterner() {
return listInterner;
}
public Label getBuildFileLabel() {
return pkg.metadata.buildFileLabel;
}
/**
* Return a read-only copy of the name mapping of external repositories for a given repository.
* Reading that mapping directly from the builder allows to also take mappings into account that
* are only discovered while constructing the external package (e.g., the mapping of the name of
* the main workspace to the canonical main name '@').
*/
RepositoryMapping getRepositoryMappingFor(RepositoryName name) {
Map<String, RepositoryName> mapping = externalPackageRepositoryMappings.get(name);
if (mapping == null) {
return RepositoryMapping.ALWAYS_FALLBACK;
} else {
return RepositoryMapping.createAllowingFallback(mapping);
}
}
RootedPath getFilename() {
return pkg.metadata.filename;
}
/** Returns the {@link StoredEventHandler} associated with this builder. */
public StoredEventHandler getLocalEventHandler() {
return localEventHandler;
}
@CanIgnoreReturnValue
public Builder setMakeVariable(String name, String value) {
makeEnv.put(name, value);
return this;
}
@CanIgnoreReturnValue
public Builder mergePackageArgsFrom(PackageArgs packageArgs) {
pkg.metadata.packageArgs = pkg.metadata.packageArgs.mergeWith(packageArgs);
return this;
}
@CanIgnoreReturnValue
public Builder mergePackageArgsFrom(PackageArgs.Builder builder) {
return mergePackageArgsFrom(builder.build());
}
/** Called partial b/c in builder and thus subject to mutation and updates */
public PackageArgs getPartialPackageArgs() {
return pkg.metadata.packageArgs;
}
/** Uses the workspace name from {@code //external} to set this package's workspace name. */
// TODO(#19922): Seems like this is only used for WORKSPACE logic (`workspace()` callable), but
// it clashes with the notion that, for BUILD files, the workspace name should be supplied to
// the Builder constructor and not mutated during evaluation. Either put up with this until we
// delete WORKSPACE logic, or else separate the `workspace()` callable's mutation from this
// metadata field.
@CanIgnoreReturnValue
@VisibleForTesting
public Builder setWorkspaceName(String workspaceName) {
pkg.metadata.workspaceName = workspaceName;
return this;
}
/** Returns whether the "package" function has been called yet */
boolean isPackageFunctionUsed() {
return packageFunctionUsed;
}
void setPackageFunctionUsed() {
packageFunctionUsed = true;
}
/** Sets the number of Starlark computation steps executed by this BUILD file. */
void setComputationSteps(long n) {
pkg.computationSteps = n;
}
Builder setIOException(IOException e, String message, DetailedExitCode detailedExitCode) {
this.ioException = e;
this.ioExceptionMessage = message;
this.ioExceptionDetailedExitCode = detailedExitCode;
return setContainsErrors();
}
/**
* Declares that errors were encountering while loading this package. If called, {@link
* #addEvent} or {@link #addEvents} should already have been called with an {@link Event} of
* type {@link EventKind#ERROR} that includes a {@link FailureDetail}.
*/
// TODO(bazel-team): For simplicity it would be nice to replace this with
// getLocalEventHandler().hasErrors(), since that would prevent the kind of inconsistency where
// we have reported an ERROR event but not called setContainsErrors(), or vice versa.
@CanIgnoreReturnValue
public Builder setContainsErrors() {
// TODO(bazel-team): Maybe do Preconditions.checkState(localEventHandler.hasErrors()).
// Maybe even assert that it has a FailureDetail, though that's a linear scan unless we
// customize the event handler.
containsErrors = true;
return this;
}
public boolean containsErrors() {
return containsErrors;
}
void setFailureDetailOverride(FailureDetail failureDetail) {
failureDetailOverride = failureDetail;
}
@Nullable
FailureDetail getFailureDetail() {
if (failureDetailOverride != null) {
return failureDetailOverride;
}
List<Event> undetailedEvents = null;
for (Event event : localEventHandler.getEvents()) {
if (event.getKind() != EventKind.ERROR) {
continue;
}
DetailedExitCode detailedExitCode = event.getProperty(DetailedExitCode.class);
if (detailedExitCode != null && detailedExitCode.getFailureDetail() != null) {
return detailedExitCode.getFailureDetail();
}
if (containsErrors) {
if (undetailedEvents == null) {
undetailedEvents = new ArrayList<>();
}
undetailedEvents.add(event);
}
}
if (undetailedEvents != null) {
BugReport.sendNonFatalBugReport(
new IllegalStateException("Package has undetailed error from " + undetailedEvents));
}
return null;
}
// TODO(#19922): Require this to be set before BUILD evaluation.
@CanIgnoreReturnValue
public Builder setLoads(Iterable<Module> directLoads) {
checkLoadsNotSet();
if (precomputeTransitiveLoads) {
pkg.metadata.transitiveLoads = computeTransitiveLoads(directLoads);
} else {
pkg.metadata.directLoads = ImmutableList.copyOf(directLoads);
}
return this;
}
@CanIgnoreReturnValue
Builder setTransitiveLoadsForDeserialization(ImmutableList<Label> transitiveLoads) {
checkLoadsNotSet();
pkg.metadata.transitiveLoads = Preconditions.checkNotNull(transitiveLoads);
return this;
}
private void checkLoadsNotSet() {
Preconditions.checkState(
pkg.metadata.directLoads == null,
"Direct loads already set: %s",
pkg.metadata.directLoads);
Preconditions.checkState(
pkg.metadata.transitiveLoads == null,
"Transitive loads already set: %s",
pkg.metadata.transitiveLoads);
}
/**
* Returns the {@link Globber} used to implement {@code glob()} functionality during BUILD
* evaluation. Null for contexts where globbing is not possible, including WORKSPACE files and
* some tests.
*/
@Nullable
public Globber getGlobber() {
return globber;
}
/**
* Creates a new {@link Rule} {@code r} where {@code r.getPackage()} is the {@link Package}
* associated with this {@link Builder}.
*
* <p>The created {@link Rule} will have no output files and therefore will be in an invalid
* state.
*/
Rule createRule(
Label label, RuleClass ruleClass, List<StarlarkThread.CallStackEntry> callstack) {
return createRule(
label,
ruleClass,
callstack.isEmpty() ? Location.BUILTIN : callstack.get(0).location,
CallStack.compactInterior(callstack));
}
Rule createRule(
Label label,
RuleClass ruleClass,
Location location,
@Nullable CallStack.Node interiorCallStack) {
return new Rule(pkg, label, ruleClass, location, interiorCallStack);
}
@Nullable
Target getTarget(String name) {
return targets.get(name);
}
/**
* Replaces a target in the {@link Package} under construction with a new target with the same
* name and belonging to the same package.
*
* <p>Requires that {@link #disableNameConflictChecking} was not called.
*
* <p>A hack needed for {@link WorkspaceFactoryHelper}.
*/
void replaceTarget(Target newTarget) {
ensureNameConflictChecking();
Preconditions.checkArgument(
targets.containsKey(newTarget.getName()),
"No existing target with name '%s' in the targets map",
newTarget.getName());
Preconditions.checkArgument(
newTarget.getPackage() == pkg, // pointer comparison since we're constructing `pkg`
"Replacement target belongs to package '%s', expected '%s'",
newTarget.getPackage(),
pkg);
Target oldTarget = targets.put(newTarget.getName(), newTarget);
if (newTarget instanceof Rule) {
List<Label> ruleLabelsForOldTarget = ruleLabels.remove(oldTarget);
if (ruleLabelsForOldTarget != null) {
ruleLabels.put((Rule) newTarget, ruleLabelsForOldTarget);
}
}
}
public Set<Target> getTargets() {
return Package.getTargets(targets);
}
/**
* Returns a lightweight snapshot view of the names of all rule targets belonging to this
* package at the time of this call.
*
* @throws IllegalStateException if this method is called after {@link #beforeBuild} has been
* called.
*/
Map<String, Rule> getRulesSnapshotView() {
if (targets instanceof SnapshottableBiMap<?, ?>) {
return Maps.transformValues(
((SnapshottableBiMap<String, Target>) targets).getTrackedSnapshot(),
target -> (Rule) target);
} else {
throw new IllegalStateException(
"getRulesSnapshotView() cannot be used after beforeBuild() has been called");
}
}
/**
* Returns an {@link Iterable} of all the rule instance targets belonging to this package.
*
* <p>The returned {@link Iterable} will be deterministically ordered, in the order the rule
* instance targets were instantiated.
*/
private Iterable<Rule> getRules() {
return Package.getTargets(targets, Rule.class);
}
/**
* Creates an input file target in this package with the specified name, if it does not yet
* exist.
*
* <p>This operation is idempotent.
*
* @param targetName name of the input file. This must be a valid target name as defined by
* {@link com.google.devtools.build.lib.cmdline.LabelValidator#validateTargetName}.
* @return the newly-created {@code InputFile}, or the old one if it already existed.
* @throws NameConflictException if the name was already taken by another target that is not an
* input file
* @throws IllegalArgumentException if the name is not a valid label
*/
InputFile createInputFile(String targetName, Location location) throws NameConflictException {
Target existing = targets.get(targetName);
if (existing instanceof InputFile) {
return (InputFile) existing; // idempotent
}
InputFile inputFile;
try {
inputFile = new InputFile(pkg, createLabel(targetName), location);
} catch (LabelSyntaxException e) {
throw new IllegalArgumentException(
"FileTarget in package " + pkg.getName() + " has illegal name: " + targetName, e);
}
checkTargetName(inputFile);
addInputFile(inputFile);
return inputFile;
}
/**
* Sets the visibility and license for an input file. The input file must already exist as a
* member of this package.
*
* @throws IllegalArgumentException if the input file doesn't exist in this package's target
* map.
*/
void setVisibilityAndLicense(InputFile inputFile, RuleVisibility visibility, License license) {
String filename = inputFile.getName();
Target cacheInstance = targets.get(filename);
if (!(cacheInstance instanceof InputFile)) {
throw new IllegalArgumentException(
"Can't set visibility for nonexistent FileTarget "
+ filename
+ " in package "
+ pkg.getName()
+ ".");
}
if (!((InputFile) cacheInstance).isVisibilitySpecified()
|| cacheInstance.getVisibility() != visibility
|| !Objects.equals(cacheInstance.getLicense(), license)) {
targets.put(
filename,
new VisibilityLicenseSpecifiedInputFile(
pkg, cacheInstance.getLabel(), cacheInstance.getLocation(), visibility, license));
}
}
/**
* Creates a label for a target inside this package.
*
* @throws LabelSyntaxException if the {@code targetName} is invalid
*/
Label createLabel(String targetName) throws LabelSyntaxException {
return Label.create(pkg.getPackageIdentifier(), targetName);
}
/** Adds a package group to the package. */
void addPackageGroup(
String name,
Collection<String> packages,
Collection<Label> includes,
boolean allowPublicPrivate,
boolean repoRootMeansCurrentRepo,
EventHandler eventHandler,
Location location)
throws NameConflictException, LabelSyntaxException {
PackageGroup group =
new PackageGroup(
createLabel(name),
pkg,
packages,
includes,
allowPublicPrivate,
repoRootMeansCurrentRepo,
eventHandler,
location);
checkTargetName(group);
targets.put(group.getName(), group);
if (group.containsErrors()) {
setContainsErrors();
}
}
/**
* Returns true if any labels in the given list appear multiple times, reporting an appropriate
* error message if so.
*
* <p>TODO(bazel-team): apply this to all build functions (maybe automatically?), possibly
* integrate with RuleClass.checkForDuplicateLabels.
*/
private static boolean hasDuplicateLabels(
List<Label> labels,
String owner,
String attrName,
Location location,
EventHandler eventHandler) {
Set<Label> dupes = CollectionUtils.duplicatedElementsOf(labels);
for (Label dupe : dupes) {
eventHandler.handle(
error(
location,
String.format(
"label '%s' is duplicated in the '%s' list of '%s'", dupe, attrName, owner),
Code.DUPLICATE_LABEL));
}
return !dupes.isEmpty();
}
/** Adds an environment group to the package. Not valid within symbolic macros. */
void addEnvironmentGroup(
String name,
List<Label> environments,
List<Label> defaults,
EventHandler eventHandler,
Location location)
throws NameConflictException, LabelSyntaxException {
Preconditions.checkState(macroStack.isEmpty());
if (hasDuplicateLabels(environments, name, "environments", location, eventHandler)
|| hasDuplicateLabels(defaults, name, "defaults", location, eventHandler)) {
setContainsErrors();
return;
}
EnvironmentGroup group =
new EnvironmentGroup(createLabel(name), pkg, environments, defaults, location);
checkTargetName(group);
targets.put(group.getName(), group);
// Invariant: once group is inserted into targets, it must also:
// (a) be inserted into environmentGroups, or
// (b) have its group.processMemberEnvironments called.
// Otherwise it will remain uninitialized,
// causing crashes when it is later toString-ed.
for (Event error : group.validateMembership()) {
eventHandler.handle(error);
setContainsErrors();
}
// For each declared environment, make sure it doesn't also belong to some other group.
for (Label environment : group.getEnvironments()) {
EnvironmentGroup otherGroup = environmentGroups.get(environment);
if (otherGroup != null) {
eventHandler.handle(
error(
location,
String.format(
"environment %s belongs to both %s and %s",
environment, group.getLabel(), otherGroup.getLabel()),
Code.ENVIRONMENT_IN_MULTIPLE_GROUPS));
setContainsErrors();
// Ensure the orphan gets (trivially) initialized.
group.processMemberEnvironments(ImmutableMap.of());
} else {
environmentGroups.put(environment, group);
}
}
}
/**
* Turns off (some) conflict checking for name clashes between targets, macros, and output file
* prefixes. (It is not guaranteed to disable all checks, since it is intended as an
* optimization and not for semantic effect.)
*
* <p>This should only be done for data that has already been validated, e.g. during package
* deserialization. Do not call this unless you know what you're doing.
*
* <p>This method must be called prior to {@link #addRuleUnchecked}. It may not be called,
* neither before nor after, a call to {@link #addRule} or {@link #replaceTarget}.
*/
@CanIgnoreReturnValue
Builder disableNameConflictChecking() {
Preconditions.checkState(nameConflictCheckingPolicy == NameConflictCheckingPolicy.UNKNOWN);
this.nameConflictCheckingPolicy = NameConflictCheckingPolicy.NOT_GUARANTEED;
this.ruleLabels = null;
this.outputFilePrefixes = null;
return this;
}
private void ensureNameConflictChecking() {
Preconditions.checkState(
nameConflictCheckingPolicy != NameConflictCheckingPolicy.NOT_GUARANTEED);
this.nameConflictCheckingPolicy = NameConflictCheckingPolicy.ENABLED;
}
/**
* Adds a rule and its outputs to the targets map, and propagates the error bit from the rule to
* the package.
*/
private void addRuleInternal(Rule rule) {
Preconditions.checkArgument(rule.getPackage() == pkg);
for (OutputFile outputFile : rule.getOutputFiles()) {
targets.put(outputFile.getName(), outputFile);
}
targets.put(rule.getName(), rule);
if (rule.containsErrors()) {
this.setContainsErrors();
}
}
/**
* Adds a rule without certain validation checks. Requires that {@link
* #disableNameConflictChecking} was already called.
*/
void addRuleUnchecked(Rule rule) {
Preconditions.checkState(
nameConflictCheckingPolicy == NameConflictCheckingPolicy.NOT_GUARANTEED);
addRuleInternal(rule);
}
/**
* Adds a rule, subject to the usual validation checks. Requires that {@link
* #disableNameConflictChecking} was not called.
*/
void addRule(Rule rule) throws NameConflictException {
ensureNameConflictChecking();
List<Label> labels = rule.getLabels();
checkRuleAndOutputs(rule, labels);
addRuleInternal(rule);
ruleLabels.put(rule, labels);
}
/** Adds a symbolic macro instance to the package. */
public void addMacro(MacroInstance macro) throws NameConflictException {
checkMacroName(macro);
macros.put(macro.getName(), macro);
}
/** Pushes a macro instance onto the stack of currently executing symbolic macros. */
public void pushMacro(MacroInstance macro) {
macroStack.add(macro);
}
/** Pops the stack of currently executing symbolic macros. */
public MacroInstance popMacro() {
return macroStack.remove(macroStack.size() - 1);
}
void addRegisteredExecutionPlatforms(List<TargetPattern> platforms) {
this.registeredExecutionPlatforms.addAll(platforms);
}
void addRegisteredToolchains(List<TargetPattern> toolchains, boolean forWorkspaceSuffix) {
if (forWorkspaceSuffix && firstWorkspaceSuffixRegisteredToolchain.isEmpty()) {
firstWorkspaceSuffixRegisteredToolchain = OptionalInt.of(registeredToolchains.size());
}
this.registeredToolchains.addAll(toolchains);
}
void setFirstWorkspaceSuffixRegisteredToolchain(
OptionalInt firstWorkspaceSuffixRegisteredToolchain) {
this.firstWorkspaceSuffixRegisteredToolchain = firstWorkspaceSuffixRegisteredToolchain;
}
@CanIgnoreReturnValue
private Builder beforeBuild(boolean discoverAssumedInputFiles) throws NoSuchPackageException {
if (ioException != null) {
throw new NoSuchPackageException(
getPackageIdentifier(), ioExceptionMessage, ioException, ioExceptionDetailedExitCode);
}
// SnapshottableBiMap does not allow removing targets (in order to efficiently track rule
// insertion order). However, we *do* need to support removal of targets in
// PackageFunction.handleLabelsCrossingSubpackagesAndPropagateInconsistentFilesystemExceptions
// which is called *between* calls to beforeBuild and finishBuild. We thus repoint the targets
// map to the SnapshottableBiMap's underlying bimap and thus stop tracking insertion order.
// After this point, snapshots of targets should no longer be used, and any further
// getRulesSnapshotView calls will throw.
if (targets instanceof SnapshottableBiMap<?, ?>) {
targets = ((SnapshottableBiMap<String, Target>) targets).getUnderlyingBiMap();
}
// We create an InputFile corresponding to the BUILD file in Builder's constructor. However,
// the visibility of this target may be overridden with an exports_files directive, so we wait
// until now to obtain the current instance from the targets map.
pkg.metadata.buildFile =
(InputFile)
Preconditions.checkNotNull(targets.get(pkg.metadata.buildFileLabel.getName()));
// TODO(bazel-team): We run testSuiteImplicitTestsAccumulator here in beforeBuild(), but what
// if one of the accumulated tests is later removed in PackageFunction, between the call to
// buildPartial() and finishBuild(), due to a label-crossing-subpackage-boundary error? Seems
// like that would mean a test_suite is referencing a Target that's been deleted from its
// Package.
// Clear tests before discovering them again in order to keep this method idempotent -
// otherwise we may double-count tests if we're called twice due to a skyframe restart, etc.
testSuiteImplicitTestsAccumulator.clearAccumulatedTests();
Map<String, InputFile> newInputFiles = new HashMap<>();
for (Rule rule : getRules()) {
if (discoverAssumedInputFiles) {
// All labels mentioned by a rule that refer to an unknown target in the current package
// are assumed to be InputFiles, so let's create them. We add them to a temporary map
// to avoid concurrent modification to this.targets while iterating (via getRules()).
List<Label> labels = (ruleLabels != null) ? ruleLabels.get(rule) : rule.getLabels();
for (Label label : labels) {
if (label.getPackageIdentifier().equals(pkg.getPackageIdentifier())
&& !targets.containsKey(label.getName())
// The existence of a macro by the same name blocks implicit creation of an input
// file. This is because we plan on allowing macros to be passed as inputs to other
// macros, and don't want this usage to be implicitly conflated with an unrelated
// input file by the same name (e.g., if the macro's label makes its way into a
// target definition by mistake, we want that to be treated as an unknown target
// rather than a missing input file).
// TODO(#19922): Update this comment when said behavior is implemented.
&& !macros.containsKey(label.getName())
&& !newInputFiles.containsKey(label.getName())) {
Location loc = rule.getLocation();
newInputFiles.put(
label.getName(),
noImplicitFileExport
? new PrivateVisibilityInputFile(pkg, label, loc)
: new InputFile(pkg, label, loc));
}
}
}
testSuiteImplicitTestsAccumulator.processRule(rule);
}
// Make sure all accumulated values are sorted for determinism.
testSuiteImplicitTestsAccumulator.sortTests();
for (InputFile file : newInputFiles.values()) {
addInputFile(file);
}
return this;
}
/** Intended for use by {@link com.google.devtools.build.lib.skyframe.PackageFunction} only. */
// TODO(bazel-team): It seems like the motivation for this method (added in cl/74794332) is to
// allow PackageFunction to delete targets that are found to violate the
// label-crossing-subpackage-boundaries check. Is there a simpler way to express this idea that
// doesn't make package-building a multi-stage process?
public Builder buildPartial() throws NoSuchPackageException {
if (alreadyBuilt) {
return this;
}
return beforeBuild(/* discoverAssumedInputFiles= */ true);
}
/** Intended for use by {@link com.google.devtools.build.lib.skyframe.PackageFunction} only. */
public Package finishBuild() {
if (alreadyBuilt) {
return pkg;
}
// Freeze targets and distributions.
for (Rule rule : getRules()) {
rule.freeze();
}
ruleLabels = null;
outputFilePrefixes = null;
targets = Maps.unmodifiableBiMap(targets);
// Now all targets have been loaded, so we validate the group's member environments.
for (EnvironmentGroup envGroup : ImmutableSet.copyOf(environmentGroups.values())) {
List<Event> errors = envGroup.processMemberEnvironments(targets);
if (!errors.isEmpty()) {
Event.replayEventsOn(localEventHandler, errors);
// TODO(bazel-team): Can't we automatically infer containsError from the presence of
// ERRORs on our handler?
setContainsErrors();
}
}
// Build the package.
pkg.finishInit(this);
alreadyBuilt = true;
return pkg;
}
public Package build() throws NoSuchPackageException {
return build(/* discoverAssumedInputFiles= */ true);
}
/**
* Build the package, optionally adding any labels in the package not already associated with a
* target as an input file.
*/
Package build(boolean discoverAssumedInputFiles) throws NoSuchPackageException {
if (alreadyBuilt) {
return pkg;
}
beforeBuild(discoverAssumedInputFiles);
return finishBuild();
}
/**
* Adds an input file to this package.
*
* <p>There must not already be a target with the same name (i.e., this is not idempotent).
*/
private void addInputFile(InputFile inputFile) {
Target prev = targets.put(inputFile.getLabel().getName(), inputFile);
Preconditions.checkState(prev == null);
}
/**
* Precondition check for {@link #addRule} (to be called before the rule and its outputs are in
* the targets map). Verifies that:
*
* <ul>
* <li>The added rule's name, and the names of its output files, are not the same as the name
* of any target already declared in the package.
* <li>The added rule's output files list does not contain the same name twice.
* <li>The added rule does not have an input file and an output file that share the same name.
* <li>For each of the added rule's output files, no directory prefix of that file matches the
* name of another output file in the package; and conversely, the file is not itself a
* prefix for another output file. (This check statefully mutates the {@code
* outputFilePrefixes} field.)
* </ul>
*/
// TODO(bazel-team): We verify that all prefixes of output files are distinct from other output
// file names, but not that they're distinct from other target names in the package. What
// happens if you define an input file "abc" and output file "abc/xyz"?
private void checkRuleAndOutputs(Rule rule, List<Label> labels) throws NameConflictException {
Preconditions.checkNotNull(outputFilePrefixes); // ensured by addRule's precondition
// Check the name of the new rule itself.
String ruleName = rule.getName();
checkTargetName(rule);
ImmutableList<OutputFile> outputFiles = rule.getOutputFiles();
Map<String, OutputFile> outputFilesByName =
Maps.newHashMapWithExpectedSize(outputFiles.size());
// Check the new rule's output files, both for direct conflicts and prefix conflicts.
for (OutputFile outputFile : outputFiles) {
String outputFileName = outputFile.getName();
// Check for duplicate within a single rule. (Can't use checkTargetName since this rule's
// outputs aren't in the target map yet.)
if (outputFilesByName.put(outputFileName, outputFile) != null) {
throw new NameConflictException(
String.format(
"rule '%s' has more than one generated file named '%s'",
ruleName, outputFileName));
}
// Check for conflict with any other already added target.
checkTargetName(outputFile);
// TODO(bazel-team): We also need to check for a conflict between an output file and its own
// rule, which is not yet in the targets map.
// Check if this output file is the prefix of an already existing one.
if (outputFilePrefixes.containsKey(outputFileName)) {
throw overlappingOutputFilePrefixes(outputFile, outputFilePrefixes.get(outputFileName));
}
// Check if a prefix of this output file matches an already existing one.
PathFragment outputFileFragment = PathFragment.create(outputFileName);
int segmentCount = outputFileFragment.segmentCount();
for (int i = 1; i < segmentCount; i++) {
String prefix = outputFileFragment.subFragment(0, i).toString();
if (outputFilesByName.containsKey(prefix)) {
throw overlappingOutputFilePrefixes(outputFile, outputFilesByName.get(prefix));
}
if (targets.get(prefix) instanceof OutputFile) {
throw overlappingOutputFilePrefixes(outputFile, (OutputFile) targets.get(prefix));
}
// Store in persistent map, for checking when adding future rules.
outputFilePrefixes.putIfAbsent(prefix, outputFile);
}
}
// Check for the same file appearing as both an input and output of the new rule.
PackageIdentifier packageIdentifier = rule.getLabel().getPackageIdentifier();
for (Label inputLabel : labels) {
if (packageIdentifier.equals(inputLabel.getPackageIdentifier())
&& outputFilesByName.containsKey(inputLabel.getName())) {
throw new NameConflictException(
String.format(
"rule '%s' has file '%s' as both an input and an output",
ruleName, inputLabel.getName()));
}
}
}
/**
* Throws {@link NameConflictException} if the given name of a declared object inside a symbolic
* macro (i.e., a target or a submacro) does not follow the required prefix-based naming
* convention.
*
* <p>A macro "foo" may define targets and submacros that have the name "foo" (the macro's "main
* target") or "foo_BAR" where BAR is a non-empty string. The macro may not define the name
* "foo_", or names that do not have "foo" as a prefix.
*/
private void checkDeclaredNameValidForMacro(
String what, String declaredName, String enclosingMacroName) throws NameConflictException {
if (declaredName.equals(enclosingMacroName)) {
return;
} else if (declaredName.startsWith(enclosingMacroName)) {
String suffix = declaredName.substring(enclosingMacroName.length());
// 0-length suffix handled above.
if (suffix.length() > 2 && suffix.startsWith("_")) {
return;
}
}
throw new NameConflictException(
String.format(
"""
macro '%s' cannot declare %s named '%s'. Name must be the same as the \
macro's name or a suffix of the macro's name plus '_'.""",
enclosingMacroName, what, declaredName));
}
/**
* Throws {@link NameConflictException} if the given target's name can't be added, either
* because of a conflict or because of a violation of symbolic macro naming rules (if
* applicable).
*/
private void checkTargetName(Target added) throws NameConflictException {
checkForExistingTargetName(added);
if (!macroStack.isEmpty()) {
String enclosingMacroName = Iterables.getLast(macroStack).getName();
checkDeclaredNameValidForMacro("target", added.getName(), enclosingMacroName);
}
}
/**
* Throws {@link NameConflictException} if the given target's name matches that of an existing
* target in the package.
*/
private void checkForExistingTargetName(Target added) throws NameConflictException {
Target existing = targets.get(added.getName());
if (existing == null) {
return;
}
String subject = String.format("%s '%s'", added.getTargetKind(), added.getName());
if (added instanceof OutputFile addedOutput) {
subject += String.format(" in rule '%s'", addedOutput.getGeneratingRule().getName());
}
String object =
existing instanceof OutputFile existingOutput
? String.format(
"generated file from rule '%s'", existingOutput.getGeneratingRule().getName())
: existing.getTargetKind();
object += ", defined at " + existing.getLocation();
throw new NameConflictException(
String.format("%s conflicts with existing %s", subject, object));
}
/**
* Throws {@link NameConflictException} if the given macro's name can't be added, either because
* of a conflict or because of a violation of symbolic macro naming rules (if applicable).
*/
private void checkMacroName(MacroInstance added) throws NameConflictException {
checkForExistingMacroName(added);
if (!macroStack.isEmpty()) {
String enclosingMacroName = Iterables.getLast(macroStack).getName();
checkDeclaredNameValidForMacro("submacro", added.getName(), enclosingMacroName);
}
}
/**
* Throws {@link NameConflictException} if the given macro's name matches that of an existing
* macro in the package.
*/
private void checkForExistingMacroName(MacroInstance added) throws NameConflictException {
MacroInstance existing = macros.get(added.getName());
if (existing == null) {
return;
}
// TODO(#19922): Add definition location info for the existing object, like we have in the
// case for rules.
throw new NameConflictException(
String.format("macro '%s' conflicts with existing macro", added.getName()));
}
/**
* Returns a {@link NameConflictException} about two output files clashing (i.e., due to one
* being a prefix of the other)
*/
private static NameConflictException overlappingOutputFilePrefixes(
OutputFile added, OutputFile existing) {
if (added.getGeneratingRule() == existing.getGeneratingRule()) {
return new NameConflictException(
String.format(
"rule '%s' has conflicting output files '%s' and '%s'",
added.getGeneratingRule().getName(), added.getName(), existing.getName()));
} else {
return new NameConflictException(
String.format(
"output file '%s' of rule '%s' conflicts with output file '%s' of rule '%s'",
added.getName(),
added.getGeneratingRule().getName(),
existing.getName(),
existing.getGeneratingRule().getName()));
}
}
@Nullable
public Semaphore getCpuBoundSemaphore() {
return cpuBoundSemaphore;
}
}
/**
* A collection of data about a package that does not require evaluating the whole package.
*
* <p>In particular, this does not contain any target information. It does contain data known
* prior to BUILD file evaluation, data mutated by BUILD file evaluation, and data computed
* immediately after BUILD file evaluation.
*
* <p>This object is supplied to symbolic macro expansion.
*/
public static final class Metadata {
private Metadata() {}
// Fields that are known before the beginning of BUILD file execution
private PackageIdentifier packageIdentifier;
/**
* Returns the package identifier for this package.
*
* <p>This is a suffix of {@code getFilename().getParentDirectory()}.
*/
public PackageIdentifier getPackageIdentifier() {
return packageIdentifier;
}
/**
* Returns the name of this package. If this build is using external repositories then this name
* may not be unique!
*/
public String getName() {
return packageIdentifier.getPackageFragment().getPathString();
}
/** Like {@link #getName}, but has type {@code PathFragment}. */
public PathFragment getNameFragment() {
return packageIdentifier.getPackageFragment();
}
private RootedPath filename;
/** Returns the filename of this package's BUILD file. */
public RootedPath getFilename() {
return filename;
}
private Path packageDirectory;
/**
* Returns the directory in which this package's BUILD file resides. All InputFile members of
* the packages are located relative to this directory.
*/
public Path getPackageDirectory() {
return packageDirectory;
}
private Label buildFileLabel;
/** Returns the label of this package's BUILD file. */
public Label getBuildFileLabel() {
return buildFileLabel;
}
private String workspaceName;
/**
* Returns the name of the workspace this package is in. Used as a prefix for the runfiles
* directory. This can be set in the WORKSPACE file. This must be a valid target name.
*/
public String getWorkspaceName() {
return workspaceName;
}
private RepositoryMapping repositoryMapping;
/**
* Returns the map of repository reassignments for BUILD packages. This will be empty for
* packages within the main workspace.
*/
public RepositoryMapping getRepositoryMapping() {
return repositoryMapping;
}
/**
* The name of the Bzlmod module associated with the repo this package is in. If this package is
* not from a Bzlmod repo, this is empty. For repos generated by module extensions, this is the
* name of the module hosting the extension.
*/
private Optional<String> associatedModuleName;
/**
* The version of the Bzlmod module associated with the repo this package is in. If this package
* is not from a Bzlmod repo, this is empty. For repos generated by module extensions, this is
* the version of the module hosting the extension.
*/
private Optional<String> associatedModuleVersion;
private ConfigSettingVisibilityPolicy configSettingVisibilityPolicy;
/** Returns the visibility enforcement policy for {@code config_setting}. */
public ConfigSettingVisibilityPolicy getConfigSettingVisibilityPolicy() {
return configSettingVisibilityPolicy;
}
// These two fields are mutually exclusive. Which one is set depends on
// PackageSettings#precomputeTransitiveLoads.
@Nullable private ImmutableList<Module> directLoads;
@Nullable private ImmutableList<Label> transitiveLoads;
/** Governs the error message behavior of {@link Package#getTarget}. */
// TODO(bazel-team): Arguably, this could be replaced by a boolean param to getTarget(), or some
// separate action taken by the caller. But there's a lot of call sites that would need
// updating.
private boolean succinctTargetNotFoundErrors;
// Fields that are updated during BUILD file execution.
private PackageArgs packageArgs = PackageArgs.DEFAULT;
/**
* Returns the collection of package-level attributes set by the {@code package()} callable and
* similar methods. May be modified during BUILD file execution.
*/
public PackageArgs getPackageArgs() {
return packageArgs;
}
// Fields that are only set after BUILD file execution (but before symbolic macro expansion).
private InputFile buildFile;
/**
* Returns the InputFile target corresponding to this package's BUILD file.
*
* <p>This may change during BUILD file execution as a result of exports_files changing the
* BUILD file's visibility.
*/
public InputFile getBuildFile() {
return buildFile;
}
private Optional<Root> sourceRoot;
/**
* Returns the root of the source tree in which this package was found. It is an invariant that
* {@code sourceRoot.getRelative(packageId.getSourceRoot()).equals(packageDirectory)}. Returns
* {@link Optional#empty} if this {@link Package} is derived from a WORKSPACE file.
*/
public Optional<Root> getSourceRoot() {
return sourceRoot;
}
private ImmutableMap<String, String> makeEnv;
/**
* Returns the "Make" environment of this package, containing package-local definitions of
* "Make" variables.
*/
public ImmutableMap<String, String> getMakeEnvironment() {
return makeEnv;
}
}
/** Package codec implementation. */
@VisibleForTesting
static final class PackageCodec implements ObjectCodec<Package> {
@Override
public Class<Package> getEncodedClass() {
return Package.class;
}
@Override
public void serialize(SerializationContext context, Package input, CodedOutputStream codedOut)
throws IOException, SerializationException {
context.checkClassExplicitlyAllowed(Package.class, input);
PackageCodecDependencies codecDeps = context.getDependency(PackageCodecDependencies.class);
codecDeps.getPackageSerializer().serialize(context, input, codedOut);
}
@Override
public Package deserialize(DeserializationContext context, CodedInputStream codedIn)
throws SerializationException, IOException {
PackageCodecDependencies codecDeps = context.getDependency(PackageCodecDependencies.class);
return codecDeps.getPackageSerializer().deserialize(context, codedIn);
}
}
}
| bazelbuild/bazel | src/main/java/com/google/devtools/build/lib/packages/Package.java |
45,308 | package com.github.binarywang.wxpay.bean.request;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.*;
import me.chanjar.weixin.common.annotation.Required;
import java.util.Map;
/**
* @author chenliang
* created on 2021-08-02 5:18 下午
* <pre>
* 支付中签约入参
* </pre>
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Builder(builderMethodName = "newBuilder")
@NoArgsConstructor
@AllArgsConstructor
@XStreamAlias("xml")
public class WxPayEntrustRequest extends BaseWxPayRequest {
/**
* <pre>
* 签约商户号
* contract_mchid
* 是
* String(32)
* 1200009811
* 签约商户号,必须与mch_id一致
* </pre>
*/
@Required
@XStreamAlias("contract_mchid")
private String contractMchId;
/**
* <pre>
* 签约APPID
* contract_appid
* 是
* String(32)
* wxcbda96de0b165486
* 签约公众号,必须与APPID一致
* </pre>
*/
@Required
@XStreamAlias("contract_appid")
private String contractAppId;
/**
* <pre>
* 商户订单号
* out_trade_no
* 是
* String(32)
* 123456
* 商户系统内部的订单号,32字符内,可包含字母
* </pre>
*/
@Required
@XStreamAlias("out_trade_no")
private String outTradeNo;
/**
* <pre>
* 设备号
* device_info
* 否
* String(32)
* 013467007045764
* 终端设备号,若为PC网页或公众号内则传WEB
* </pre>
*/
@XStreamAlias("device_info")
private String deviceInfo;
/**
* <pre>
* 商品描述
* body
* 是
* String(128)
* ipad mini 16G 白色
* 商品支付单简要描述
* </pre>
*/
@Required
@XStreamAlias("body")
private String body;
/**
* <pre>
* 商品详情
* detail
* 否
* String(8192)
* ipad mini 16G 白色
* 商品名称明细列表
* </pre>
*/
@XStreamAlias("detail")
private String detail;
/**
* <pre>
* 附加数据
* attach
* 否
* String(127)
* online/dev/dev1
* 商家数据包
* </pre>
*/
@XStreamAlias("attach")
private String attach;
/**
* <pre>
* 回调通知url
* notify_url
* 是
* String(256)
* https://weixin.qq.com
* 回调通知地址
* </pre>
*/
@Required
@XStreamAlias("notify_url")
private String notifyUrl;
/**
* <pre>
* 总金额
* total_fee
* 是
* int
* 888
* 订单总金额,单位分
* </pre>
*/
@Required
@XStreamAlias("total_fee")
private Integer totalFee;
/**
* <pre>
* 终端ip
* spbill_create_ip
* 是
* String(16)
* 127.0.0.1
* 用户的客户端IP
* </pre>
*/
@Required
@XStreamAlias("spbill_create_ip")
private String spbillCreateIp;
/**
* <pre>
* 交易起始时间
* time_start
* 否
* String(14)
* 20201025171529
* 订单生成时间,格式yyyyMMddHHmmss
* </pre>
*/
@XStreamAlias("time_start")
private String timeStart;
/**
* <pre>
* 交易结束时间
* time_expire
* 否
* String(14)
* 20201025171529
* 订单失效时间,格式yyyyMMddHHmmss
* </pre>
*/
@XStreamAlias("time_expire")
private String timeExpire;
/**
* <pre>
* 商品标记
* goods_tag
* 否
* String(32)
* wxg
* 商品标记,代金券或立减优惠功能参数
* </pre>
*/
@XStreamAlias("goods_tag")
private String goodsTag;
/**
* <pre>
* 交易类型
* trade_type
* 是
* String(16)
* JSAPI
* JSAPI,MWEB
* </pre>
*/
@Required
@XStreamAlias("trade_type")
private String tradeType;
/**
* <pre>
* 商品ID
* product_id
* 否
* String(32)
* 12234355463434643
* 二维码支付必传,二维码中包含商品ID
* </pre>
*/
@XStreamAlias("product_id")
private String productId;
/**
* <pre>
* 指定支付方式
* limit_pay
* 否
* String(32)
* no_credit
* no_credit--指定不能使用信用卡支付
* </pre>
*/
@XStreamAlias("limit_pay")
private String limitPay;
/**
* <pre>
* 用户表示
* openid
* 否
* String(128)
* oUpF4sdsidj3Jds89
* tradetype=JSAPI 则必传
* </pre>
*/
@XStreamAlias("openid")
private String openId;
/**
* <pre>
* 协议模板ID
* plan_id
* 是
* String(28)
* 12535
* 协议模板ID,分为首次签约,支付中签约,重新签约
* </pre>
*/
@Required
@XStreamAlias("plan_id")
private String planId;
/**
* <pre>
* 签约协议号
* contract_code
* 是
* String(32)
* 100000
* 商户侧签约协议号,由商户生成,只能是数字,大小写字母组成
* </pre>
*/
@Required
@XStreamAlias("contract_code")
private String contractCode;
/**
* <pre>
* 请求序列号
* request_serial
* 是
* int(64)
* 1000
* 商户请求签约时的序列号,要求唯一性,禁止使用0开头的,用户排序,纯数字
* </pre>
*/
@Required
@XStreamAlias("request_serial")
private Long requestSerial;
/**
* <pre>
* 用户账户展示名称
* contract_display_account
* 是
* string(32)
* 微信代扣
* 签约用户的名称,用户页面展示,不支持符号表情
* </pre>
*/
@Required
@XStreamAlias("contract_display_account")
private String contractDisplayAccount;
/**
* <pre>
* 签约信息通知URL
* contract_notify_url
* 是
* string(32)
* https://yoursite.com
* 签约信息回调通知URL
* </pre>
*/
@Required
@XStreamAlias("contract_notify_url")
private String contractNotifyUrl;
/**
* <pre>
* 商户测的用户标识
* contract_outerid
* 否
* string(32)
* 陈*(12000002)
* 用于多账户签约,值与contract_display_account相同即可,同一模板下唯一
* </pre>
*/
@XStreamAlias("contract_outerid")
private String contractOuterId;
@Override
protected void checkConstraints() throws WxPayException {
}
@Override
protected void storeMap(Map<String, String> map) {
map.put("contract_mchid", contractMchId);
map.put("contract_appid", contractAppId);
map.put("out_trade_no", outTradeNo);
map.put("device_info", deviceInfo);
map.put("body", body);
map.put("detail", detail);
map.put("attach", attach);
map.put("notify_url", notifyUrl);
map.put("total_fee", totalFee.toString());
map.put("spbill_create_ip", spbillCreateIp);
map.put("time_start", timeStart);
map.put("time_expire", timeExpire);
map.put("goods_tag", goodsTag);
map.put("trade_type", tradeType);
map.put("product_id", productId);
map.put("limit_pay", limitPay);
map.put("openid", openId);
map.put("plan_id", planId);
map.put("contract_code", contractCode);
map.put("request_serial", requestSerial.toString());
map.put("contract_display_account", contractDisplayAccount);
map.put("contract_notify_url", contractNotifyUrl);
map.put("contract_outerid", contractOuterId);
}
}
| Wechat-Group/WxJava | weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayEntrustRequest.java |
45,309 | /*
* Created on May 18, 2004
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2005 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/08/03 Revamped upgrade for 1.3.2
// ZAP: 2011/10/05 Write backup file to user dir
// ZAP: 2011/11/15 Changed to use ZapXmlConfiguration, to enforce the same
// character encoding when reading/writing configurations. Changed to use the
// correct file when an error occurs during the load of the configuration file.
// Removed the calls XMLConfiguration.load() as they are not needed, the
// XMLConfiguration constructor used already does that.
// ZAP: 2011/11/20 Support for extension factory
// ZAP: 2012/03/03 Added ZAP homepage
// ZAP: 2012/03/15 Removed a @SuppressWarnings annotation from the method
// copyAllProperties.
// ZAP: 2012/03/17 Issue 282 ZAP and PAROS team constants
// ZAP: 2012/05/02 Added method createInstance and changed the method
// getInstance to use it.
// ZAP: 2012/05/03 Changed the Patterns used to detect the O.S. to be final.
// ZAP: 2012/06/15 Issue 312 Increase the maximum number of scanning threads allowed
// ZAP: 2012/07/13 Added variable for maximum number of threads used in scan (MAX_THREADS_PER_SCAN)
// ZAP: 2012/10/15 Issue 397: Support weekly builds
// ZAP: 2012/10/17 Issue 393: Added more online links from menu
// ZAP: 2012/11/15 Issue 416: Normalise how multiple related options are managed
// throughout ZAP and enhance the usability of some options.
// ZAP: 2012/11/20 Issue 419: Restructure jar loading code
// ZAP: 2012/12/08 Issue 428: Changed to use I18N for messages, to support the marketplace
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/04/14 Issue 610: Replace the use of the String class for available/default "Forced
// Browse" files
// ZAP: 2013/04/15 Issue 632: Manual Request Editor dialogue (HTTP) configurations not saved
// correctly
// ZAP: 2013/12/03 Issue 933: Automatically determine install dir
// ZAP: 2013/12/13 Issue 919: Support for multiple language vulnerability files.
// ZAP: 2014/04/11 Issue 1148: ZAP 2.3.0 does not launch after upgrading in some situations
// ZAP: 2014/07/15 Issue 1265: Context import and export
// ZAP: 2014/08/14 Issue 1300: Add-ons show incorrect language when English is selected on non
// English locale
// ZAP: 2014/11/11 Issue 1406: Move online menu items to an add-on
// ZAP: 2015/01/04 Issue 1388: Not all translated files are updated when "zaplang" package is
// imported
// ZAP: 2014/01/04 Issue 1394: Import vulnerabilities.xml files when updating the translated
// resources
// ZAP: 2014/01/04 Issue 1458: Change home/installation dir paths to be always absolute
// ZAP: 2015/03/10 Issue 653: Handle updates on Kali better
// ZAP: 2015/03/30 Issue 1582: Enablers for low memory option
// ZAP: 2015/04/12 Remove "installation" fuzzers dir, no longer in use
// ZAP: 2015/08/01 Remove code duplication in catch of exceptions, use installation directory in
// default config file
// ZAP: 2015/11/11 Issue 2045: Dont copy old configs if -dir option used
// ZAP: 2015/11/26 Issue 2084: Warn users if they are probably using out of date versions
// ZAP: 2016/02/17 Convert extensions' options to not use extensions' names as XML element names
// ZAP: 2016/05/12 Use dev/weekly dir for plugin downloads when copying the existing 'release'
// config file
// ZAP: 2016/06/07 Remove commented constants and statement that had no (actual) effect, add doc to
// a constant and init other
// ZAP: 2016/06/07 Use filter directory in ZAP's home directory
// ZAP: 2016/06/13 Migrate config option "proxy.modifyAcceptEncoding"
// ZAP: 2016/07/07 Convert passive scanners options to new structure
// ZAP: 2016/09/22 JavaDoc tweaks
// ZAP: 2016/11/17 Issue 2701 Support Factory Reset
// ZAP: 2017/05/04 Issue 3440: Log Exception when overwriting a config file
// ZAP: 2017/12/26 Remove class methods no longer used.
// ZAP: 2018/01/03 No longer create filter dir and deprecate FOLDER_FILTER constant.
// Exit immediately if not able to create the home dir.
// ZAP: 2018/01/04 Clear SNI Terminator options when updating from older ZAP versions.
// ZAP: 2018/01/05 Prevent use of install dir as home dir.
// ZAP: 2018/02/14 Remove unnecessary boxing / unboxing
// ZAP: 2018/03/16 Use equalsIgnoreCase (Issue 4327).
// ZAP: 2018/04/16 Keep backup of malformed config file.
// ZAP: 2018/06/13 Correct install dir detection from JAR.
// ZAP: 2018/06/29 Allow to check if in dev mode.
// ZAP: 2018/07/19 Fallback to bundled config.xml and log4j.properties.
// ZAP: 2019/03/14 Move and correct update of old options.
// ZAP: 2019/04/01 Refactored to reduce code-duplication.
// ZAP: 2019/05/10 Apply installer config options on update.
// Fix exceptions during config update.
// ZAP: 2019/05/14 Added silent option
// ZAP: 2019/05/17 Update cert option to boolean.
// ZAP: 2019/05/29 Update Jericho log configuration.
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/06/07 Update current version.
// ZAP: 2019/09/16 Deprecate ZAP_HOMEPAGE and ZAP_EXTENSIONS_PAGE.
// ZAP: 2019/11/07 Removed constants related to accepting the license.
// ZAP: 2020/01/02 Updated config version and default user agent
// ZAP: 2020/01/06 Set latest version to default config.
// ZAP: 2020/01/10 Correct the MailTo autoTagScanner regex pattern when upgrading from 2.8 or
// earlier.
// ZAP: 2020/04/22 Check ControlOverrides when determining the locale.
// ZAP: 2020/09/17 Correct the Syntax Highlighting markoccurrences config key name when upgrading
// from 2.9 or earlier.
// ZAP: 2020/10/07 Changes for Log4j 2 migration.
// ZAP: 2020/11/02 Do not backup old Log4j config if already present.
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/09/15 Added support for detecting containers
// ZAP: 2021/09/21 Added support for detecting snapcraft
// ZAP: 2021/10/01 Added support for detecting WebSwing
// ZAP: 2021/10/06 Update user agent when upgrading from 2.10
// ZAP: 2022/02/03 Removed deprecated FILE_CONFIG_DEFAULT and VULNS_BASE
// ZAP: 2022/02/25 Remove options that are no longer needed.
// ZAP: 2022/05/20 Remove usage of ConnectionParam.
// ZAP: 2022/09/21 Use format specifiers instead of concatenation when logging.
// ZAP: 2022/12/22 Issue 7663: Default threads based on number of processors.
// ZAP: 2023/01/10 Tidy up logger.
// ZAP: 2023/08/07 Rename home dir in Windows and update program name.
// ZAP: 2023/08/21 Deprecate vulnerabilities constants.
// ZAP: 2023/08/28 Update paths in config file to match the renamed home dir.
// ZAP: 2023/09/14 Lock home directory.
// ZAP: 2024/04/25 Add new autoTagScanner regex patterns when upgrading from 2.14 or earlier.
package org.parosproxy.paros;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.ConversionException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.parosproxy.paros.extension.option.OptionsParamView;
import org.parosproxy.paros.model.FileCopier;
import org.parosproxy.paros.model.Model;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.control.AddOnLoader;
import org.zaproxy.zap.control.ControlOverrides;
import org.zaproxy.zap.extension.autoupdate.OptionsParamCheckForUpdates;
import org.zaproxy.zap.utils.I18N;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
public final class Constant {
// ZAP: rebrand
public static final String PROGRAM_NAME = "ZAP";
public static final String PROGRAM_NAME_SHORT = "ZAP";
/**
* @deprecated (2.9.0) Do not use, it will be removed.
*/
@Deprecated public static final String ZAP_HOMEPAGE = "http://www.owasp.org/index.php/ZAP";
/**
* @deprecated (2.9.0) Do not use, it will be removed.
*/
@Deprecated
public static final String ZAP_EXTENSIONS_PAGE = "https://github.com/zaproxy/zap-extensions";
public static final String ZAP_TEAM = "ZAP Dev Team";
public static final String PAROS_TEAM = "Chinotec Technologies";
// ************************************************************
// the config.xml MUST be set to be the same as the version_tag
// otherwise the config.xml will be overwritten everytime.
// ************************************************************
private static final String DEV_VERSION = "Dev Build";
public static final String ALPHA_VERSION = "alpha";
public static final String BETA_VERSION = "beta";
private static final String VERSION_ELEMENT = "version";
// Accessible for tests
static final long VERSION_TAG = 20015000;
// Old version numbers - for upgrade
private static final long V_2_14_0_TAG = 20014000;
private static final long V_2_12_0_TAG = 20012000;
private static final long V_2_11_1_TAG = 20011001;
private static final long V_2_9_0_TAG = 2009000;
private static final long V_2_8_0_TAG = 2008000;
private static final long V_2_7_0_TAG = 2007000;
private static final long V_2_5_0_TAG = 2005000;
private static final long V_2_4_3_TAG = 2004003;
private static final long V_2_3_1_TAG = 2003001;
private static final long V_2_2_2_TAG = 2002002;
private static final long V_2_2_0_TAG = 2002000;
private static final long V_2_1_0_TAG = 2001000;
private static final long V_2_0_0_TAG = 2000000;
private static final long V_1_4_1_TAG = 1004001;
private static final long V_1_3_1_TAG = 1003001;
private static final long V_1_3_0_TAG = 1003000;
private static final long V_1_2_1_TAG = 1002001;
private static final long V_1_2_0_TAG = 1002000;
private static final long V_1_1_0_TAG = 1001000;
private static final long V_1_0_0_TAG = 1000000;
private static final long V_PAROS_TAG = 30020013;
// ************************************************************
// note the above
// ************************************************************
// These are no longer final - version is now loaded from the manifest file
public static String PROGRAM_VERSION = DEV_VERSION;
public static String PROGRAM_TITLE = PROGRAM_NAME + " " + PROGRAM_VERSION;
public static final String SYSTEM_PAROS_USER_LOG = "zap.user.log";
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
public static final String FILE_CONFIG_NAME = "config.xml";
public static final String FOLDER_PLUGIN = "plugin";
/**
* The name of the directory for filter related files (the path should be built using {@link
* #getZapHome()} as the parent directory).
*
* @deprecated (2.8.0) Should not be used, the filter functionality is deprecated (replaced by
* scripts and Replacer add-on).
* @since 1.0.0
*/
@Deprecated public static final String FOLDER_FILTER = "filter";
/**
* The name of the directory where the (file) sessions are saved by default.
*
* @since 1.0.0
*/
public static final String FOLDER_SESSION_DEFAULT = "session";
public static final String DBNAME_TEMPLATE =
"db" + System.getProperty("file.separator") + "zapdb";
/**
* Prefix (file name) of Messages.properties files.
*
* @see #MESSAGES_EXTENSION
*/
public static final String MESSAGES_PREFIX = "Messages";
/**
* Extension (with dot) of Messages.properties files.
*
* @see #MESSAGES_PREFIX
* @since 2.4.0
*/
public static final String MESSAGES_EXTENSION = ".properties";
public static final String DBNAME_UNTITLED_DEFAULT =
FOLDER_SESSION_DEFAULT + System.getProperty("file.separator") + "untitled";
public String FILE_CONFIG = FILE_CONFIG_NAME;
public String FOLDER_SESSION = FOLDER_SESSION_DEFAULT;
public String DBNAME_UNTITLED =
FOLDER_SESSION + System.getProperty("file.separator") + "untitled";
public static final String FILE_PROGRAM_SPLASH = "resource/zap128x128.png";
// Accelerator keys - Default: Windows
public static String ACCELERATOR_UNDO = "control Z";
public static String ACCELERATOR_REDO = "control Y";
public static String ACCELERATOR_TRIGGER_KEY = "Control";
private static Constant instance = null;
public static final int MAX_HOST_CONNECTION = 15;
@Deprecated // No longer limit in the UI
public static final int MAX_THREADS_PER_SCAN = 50;
// ZAP: Dont announce ourselves
// public static final String USER_AGENT = PROGRAM_NAME + "/" + PROGRAM_VERSION;
public static final String USER_AGENT = "";
private static String staticEyeCatcher = "0W45pz4p";
private static final String USER_CONTEXTS_DIR = "contexts";
private static final String USER_POLICIES_DIR = "policies";
private static final String ZAP_CONTAINER_FILE = "/zap/container";
private static final String FLATPAK_FILE = "/.flatpak-info";
public static final String FLATPAK_NAME = "flatpak";
private static final String SNAP_FILE = "meta/snap.yaml";
public static final String SNAP_NAME = "snapcraft";
private static final String HOME_ENVVAR = "HOME";
public static final String WEBSWING_NAME = "webswing";
//
// Home dir for ZAP, i.e. where the config file is. Can be set on cmdline, otherwise will be set
// to default loc
private static String zapHome = null;
// Default home dir for 'full' releases - used for copying full conf file when dev/daily release
// run for the first time
// and also for the JVM options config file
private static String zapStd = null;
// Install dir for ZAP, but default will be cwd
private static String zapInstall = null;
private static Boolean onKali = null;
private static Boolean onBackBox = null;
private static Boolean inContainer = null;
private static String containerName;
private static Boolean lowMemoryOption = null;
// ZAP: Added i18n
public static I18N messages = null;
/**
* The system's locale (as determined by the JVM at startup, {@code Locale#getDefault()}).
*
* <p>The locale is kept here because the default locale is later overridden with the user's
* chosen locale/language.
*
* @see Locale#getDefault()
*/
private static final Locale SYSTEMS_LOCALE = Locale.getDefault();
/** The path to bundled (in zap.jar) config.xml file. */
private static final String PATH_BUNDLED_CONFIG_XML =
"/org/zaproxy/zap/resources/" + FILE_CONFIG_NAME;
/**
* Name of directory that contains the (source and translated) resource files.
*
* @see #MESSAGES_PREFIX
* @see #VULNERABILITIES_PREFIX
*/
public static final String LANG_DIR = "lang";
/**
* Prefix (file name) of vulnerabilities.xml files.
*
* @see #VULNERABILITIES_EXTENSION
* @deprecated (2.14.0) The vulnerabilities were moved to Common Library add-on.
* @since 2.4.0
*/
@Deprecated(since = "2.14.0", forRemoval = true)
public static final String VULNERABILITIES_PREFIX = "vulnerabilities";
/**
* Extension (with dot) of vulnerabilities.xml files.
*
* @see #VULNERABILITIES_PREFIX
* @deprecated (2.14.0) The vulnerabilities were moved to Common Library add-on.
* @since 2.4.0
*/
@Deprecated(since = "2.14.0", forRemoval = true)
public static final String VULNERABILITIES_EXTENSION = ".xml";
/**
* Flag that indicates whether or not the "dev mode" is enabled.
*
* @see #isDevMode()
*/
private static boolean devMode;
private static boolean silent;
// ZAP: Added dirbuster dir
public String DIRBUSTER_DIR = "dirbuster";
public String DIRBUSTER_CUSTOM_DIR = DIRBUSTER_DIR;
public String FUZZER_DIR = "fuzzers";
public static String FOLDER_LOCAL_PLUGIN = FOLDER_PLUGIN;
public static final URL OK_FLAG_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/072.png"); // Green
public static final URL INFO_FLAG_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/073.png"); // Blue
public static final URL LOW_FLAG_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/074.png"); // Yellow
public static final URL MED_FLAG_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/076.png"); // Orange
public static final URL HIGH_FLAG_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/071.png"); // Red
public static final URL BLANK_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/blank.png");
public static final URL SPIDER_IMAGE_URL =
Constant.class.getResource("/resource/icon/10/spider.png");
private static final Logger LOGGER = LogManager.getLogger(Constant.class);
private FileChannel homeLockFileChannel;
private FileLock homeLock;
public static String getEyeCatcher() {
return staticEyeCatcher;
}
public static void setEyeCatcher(String eyeCatcher) {
staticEyeCatcher = eyeCatcher;
}
public Constant() {
this(null);
}
private Constant(ControlOverrides overrides) {
initializeFilesAndDirectories(overrides);
setAcceleratorKeys();
}
public static String getDefaultHomeDirectory(boolean incDevOption) {
if (zapStd == null) {
zapStd = getUserHome();
if (isLinux()) {
// Linux: Hidden Zap directory in the user's home directory
zapStd += FILE_SEPARATOR + "." + PROGRAM_NAME_SHORT;
} else if (isMacOsX()) {
// Mac Os X: Support for writing the configuration into the users Library
zapStd +=
FILE_SEPARATOR
+ "Library"
+ FILE_SEPARATOR
+ "Application Support"
+ FILE_SEPARATOR
+ PROGRAM_NAME_SHORT;
} else {
// Windows: Zap directory in the user's home directory
zapStd += FILE_SEPARATOR + PROGRAM_NAME_SHORT;
}
}
if (incDevOption) {
if (isDevMode() || isDailyBuild()) {
// Default to a different home dir to prevent messing up full releases
return zapStd + "_D";
}
}
return zapStd;
}
/**
* Gets the user home.
*
* <p>It is returned the system property {@code user.home} if defined otherwise the current
* directory (i.e. {@code "."}).
*
* @return the user home, or the current directory.
*/
private static String getUserHome() {
String home = System.getProperty("user.home");
if (home == null) {
return ".";
}
return home;
}
public void copyDefaultConfigs(File f, boolean forceReset)
throws IOException, ConfigurationException {
FileCopier copier = new FileCopier();
File oldf;
if (isDevMode() || isDailyBuild()) {
// try standard location
oldf = new File(getDefaultHomeDirectory(false) + FILE_SEPARATOR + FILE_CONFIG_NAME);
} else {
// try old location
oldf = new File(zapHome + FILE_SEPARATOR + "zap" + FILE_SEPARATOR + FILE_CONFIG_NAME);
}
if (!forceReset
&& oldf.exists()
&& Paths.get(zapHome).equals(Paths.get(getDefaultHomeDirectory(true)))) {
// Dont copy old configs if forcedReset or they've specified a non std directory
LOGGER.info("Copying defaults from {} to {}", oldf.getAbsolutePath(), FILE_CONFIG);
copier.copy(oldf, f);
if (isDevMode() || isDailyBuild()) {
ZapXmlConfiguration newConfig = new ZapXmlConfiguration(f);
newConfig.setProperty(
OptionsParamCheckForUpdates.DOWNLOAD_DIR, Constant.FOLDER_LOCAL_PLUGIN);
newConfig.save();
}
} else {
LOGGER.info("Copying default configuration to {}", FILE_CONFIG);
copyDefaultConfigFile();
}
}
private void copyDefaultConfigFile() throws IOException {
Path configFile = Paths.get(FILE_CONFIG);
copyFileToHome(configFile, "xml/" + FILE_CONFIG_NAME, PATH_BUNDLED_CONFIG_XML);
try {
setLatestVersion(new ZapXmlConfiguration(configFile.toFile()));
} catch (ConfigurationException e) {
throw new IOException("Failed to set the latest version:", e);
}
}
/**
* Sets the latest version ({@link #VERSION_TAG}) to the given configuration and then saves it.
*
* @param config the configuration to change
* @throws ConfigurationException if an error occurred while saving the configuration.
*/
private static void setLatestVersion(XMLConfiguration config) throws ConfigurationException {
config.setProperty(VERSION_ELEMENT, VERSION_TAG);
config.save();
}
private static void copyFileToHome(
Path targetFile, String sourceFilePath, String fallbackResource) throws IOException {
Path defaultConfig = Paths.get(getZapInstall(), sourceFilePath);
if (Files.exists(defaultConfig)) {
Files.copy(defaultConfig, targetFile, StandardCopyOption.REPLACE_EXISTING);
} else {
try (InputStream is = Constant.class.getResourceAsStream(fallbackResource)) {
if (is == null) {
throw new IOException("Bundled resource not found: " + fallbackResource);
}
Files.copy(is, targetFile, StandardCopyOption.REPLACE_EXISTING);
}
}
}
private static URL getUrlDefaultConfigFile() {
Path path = getPathDefaultConfigFile();
if (Files.exists(path)) {
try {
return path.toUri().toURL();
} catch (MalformedURLException e) {
LOGGER.debug("Failed to convert file system path:", e);
}
}
return Constant.class.getResource(PATH_BUNDLED_CONFIG_XML);
}
public void initializeFilesAndDirectories() {
initializeFilesAndDirectories(null);
}
private void initializeFilesAndDirectories(ControlOverrides overrides) {
FileCopier copier = new FileCopier();
File f = null;
// Set up the version from the manifest
PROGRAM_VERSION = getVersionFromManifest();
PROGRAM_TITLE = PROGRAM_NAME + " " + PROGRAM_VERSION;
if (zapHome == null) {
renameOldWindowsHome();
zapHome = getDefaultHomeDirectory(true);
}
zapHome = getAbsolutePath(zapHome);
f = new File(zapHome);
FILE_CONFIG = zapHome + FILE_CONFIG;
FOLDER_SESSION = zapHome + FOLDER_SESSION;
DBNAME_UNTITLED = zapHome + DBNAME_UNTITLED;
DIRBUSTER_CUSTOM_DIR = zapHome + DIRBUSTER_DIR;
FUZZER_DIR = zapHome + FUZZER_DIR;
FOLDER_LOCAL_PLUGIN = zapHome + FOLDER_PLUGIN;
try {
System.setProperty(SYSTEM_PAROS_USER_LOG, zapHome);
if (!f.isDirectory()) {
if (f.exists()) {
System.err.println("The home path is not a directory: " + zapHome);
System.exit(1);
}
if (!f.mkdir()) {
System.err.println("Unable to create home directory: " + zapHome);
System.err.println("Is the path correct and there's write permission?");
System.exit(1);
}
} else if (!f.canWrite()) {
System.err.println("The home path is not writable: " + zapHome);
System.exit(1);
} else {
Path installDir = Paths.get(getZapInstall()).toRealPath();
if (installDir.equals(Paths.get(zapHome).toRealPath())) {
System.err.println(
"The install dir should not be used as home dir: " + installDir);
System.exit(1);
}
}
if (!acquireHomeLock()) {
System.exit(1);
}
setUpLogging();
f = new File(FILE_CONFIG);
if (!f.isFile()) {
this.copyDefaultConfigs(f, false);
}
f = new File(FOLDER_SESSION);
if (!f.isDirectory()) {
LOGGER.info("Creating directory {}", FOLDER_SESSION);
if (!f.mkdir()) {
// ZAP: report failure to create directory
System.out.println("Failed to create directory " + f.getAbsolutePath());
}
}
f = new File(DIRBUSTER_CUSTOM_DIR);
if (!f.isDirectory()) {
LOGGER.info("Creating directory {}", DIRBUSTER_CUSTOM_DIR);
if (!f.mkdir()) {
// ZAP: report failure to create directory
System.out.println("Failed to create directory " + f.getAbsolutePath());
}
}
f = new File(FUZZER_DIR);
if (!f.isDirectory()) {
LOGGER.info("Creating directory {}", FUZZER_DIR);
if (!f.mkdir()) {
// ZAP: report failure to create directory
System.out.println("Failed to create directory " + f.getAbsolutePath());
}
}
f = new File(FOLDER_LOCAL_PLUGIN);
if (!f.isDirectory()) {
LOGGER.info("Creating directory {}", FOLDER_LOCAL_PLUGIN);
if (!f.mkdir()) {
// ZAP: report failure to create directory
System.out.println("Failed to create directory " + f.getAbsolutePath());
}
}
} catch (Exception e) {
System.err.println("Unable to initialize home directory! " + e.getMessage());
e.printStackTrace(System.err);
System.exit(1);
}
// Upgrade actions
try {
try {
// ZAP: Changed to use ZapXmlConfiguration, to enforce the same character encoding
// when reading/writing configurations.
XMLConfiguration config = new ZapXmlConfiguration(FILE_CONFIG);
config.setAutoSave(false);
long ver = config.getLong(VERSION_ELEMENT);
if (ver == VERSION_TAG) {
// Nothing to do
} else if (isDevMode() || isDailyBuild()) {
// Nothing to do
} else {
// Backup the old one
LOGGER.info("Backing up config file to {}.bak", FILE_CONFIG);
f = new File(FILE_CONFIG);
try {
copier.copy(f, new File(FILE_CONFIG + ".bak"));
} catch (IOException e) {
String msg =
"Failed to backup config file "
+ FILE_CONFIG
+ " to "
+ FILE_CONFIG
+ ".bak "
+ e.getMessage();
System.err.println(msg);
LOGGER.error(msg, e);
}
if (ver == V_PAROS_TAG) {
upgradeFrom1_1_0(config);
upgradeFrom1_2_0(config);
}
if (ver <= V_1_0_0_TAG) {
// Nothing to do
}
if (ver <= V_1_1_0_TAG) {
upgradeFrom1_1_0(config);
}
if (ver <= V_1_2_0_TAG) {
upgradeFrom1_2_0(config);
}
if (ver <= V_1_2_1_TAG) {
// Nothing to do
}
if (ver <= V_1_3_0_TAG) {
// Nothing to do
}
if (ver <= V_1_3_1_TAG) {
// Nothing to do
}
if (ver <= V_1_4_1_TAG) {
upgradeFrom1_4_1(config);
}
if (ver <= V_2_0_0_TAG) {
upgradeFrom2_0_0(config);
}
if (ver <= V_2_1_0_TAG) {
// Nothing to do
}
if (ver <= V_2_2_0_TAG) {
upgradeFrom2_2_0(config);
}
if (ver <= V_2_2_2_TAG) {
upgradeFrom2_2_2(config);
}
if (ver <= V_2_3_1_TAG) {
upgradeFrom2_3_1(config);
}
if (ver <= V_2_4_3_TAG) {
upgradeFrom2_4_3(config);
}
if (ver <= V_2_5_0_TAG) {
upgradeFrom2_5_0(config);
}
if (ver <= V_2_7_0_TAG) {
upgradeFrom2_7_0(config);
}
if (ver <= V_2_8_0_TAG) {
upgradeFrom2_8_0(config);
}
if (ver <= V_2_9_0_TAG) {
upgradeFrom2_9_0(config);
}
if (ver <= V_2_11_1_TAG) {
upgradeFrom2_11_1(config);
}
if (ver <= V_2_12_0_TAG) {
upgradeFrom2_12(config);
}
if (ver <= V_2_14_0_TAG) {
upgradeFrom2_14_0(config);
}
// Execute always to pick installer choices.
updateCfuFromDefaultConfig(config);
LOGGER.info("Upgraded from {}", ver);
setLatestVersion(config);
}
} catch (ConfigurationException | ConversionException | NoSuchElementException e) {
handleMalformedConfigFile(e);
}
} catch (Exception e) {
System.err.println(
"Unable to upgrade config file " + FILE_CONFIG + " " + e.getMessage());
e.printStackTrace(System.err);
System.exit(1);
}
// ZAP: Init i18n
Locale locale = loadLocale(overrides);
Locale.setDefault(locale);
messages = new I18N(locale);
}
boolean acquireHomeLock() {
try {
Path lockFile = Paths.get(zapHome, ".homelock");
if (Files.notExists(lockFile)) {
Files.createFile(lockFile);
}
homeLockFileChannel = FileChannel.open(lockFile, StandardOpenOption.WRITE);
homeLock = homeLockFileChannel.tryLock();
if (homeLock == null) {
System.err.println(
"The home directory is already in use. Ensure no other ZAP instances are running with the same home directory: "
+ zapHome);
return false;
}
return true;
} catch (Exception e) {
System.err.println("Failed to acquire home directory lock.");
e.printStackTrace();
return false;
}
}
private void renameOldWindowsHome() {
if (!isWindows()) {
return;
}
String home = getUserHome() + FILE_SEPARATOR + "OWASP ZAP";
if (isDevMode() || isDailyBuild()) {
home += "_D";
}
Path oldHome = Paths.get(getAbsolutePath(home));
if (Files.notExists(oldHome)) {
return;
}
Path newHome = Paths.get(getAbsolutePath(getDefaultHomeDirectory(true)));
if (Files.exists(newHome)) {
logAndPrintInfo("Not renaming old ZAP home, the new home already exists.");
return;
}
try {
Files.move(oldHome, newHome, StandardCopyOption.ATOMIC_MOVE);
logAndPrintInfo("Old ZAP home renamed to: " + newHome);
Path configFile = newHome.resolve(FILE_CONFIG_NAME);
if (Files.exists(configFile)) {
updatePathsInConfig(oldHome, newHome, new ZapXmlConfiguration(configFile.toFile()));
}
} catch (IOException e) {
logAndPrintError("Failed to rename the old home, will use a new home instead.", e);
} catch (ConfigurationException e) {
logAndPrintError("Failed to update home paths in configuration file:", e);
}
}
private static void updatePathsInConfig(Path oldHome, Path newHome, ZapXmlConfiguration config)
throws ConfigurationException {
config.getKeys()
.forEachRemaining(
key -> {
Path path = getPath(config.getString(key));
if (path == null || !path.startsWith(oldHome)) {
return;
}
Path newPath = newHome.resolve(oldHome.relativize(path));
config.setProperty(key, newPath.toString());
});
config.save();
}
private static Path getPath(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Paths.get(value);
} catch (Exception ignore) {
// Nothing to do.
}
return null;
}
private Locale loadLocale(ControlOverrides overrides) {
try {
String lang = null;
if (overrides != null) {
lang = overrides.getOrderedConfigs().get(OptionsParamView.LOCALE);
}
if (lang == null || lang.isEmpty()) {
XMLConfiguration config = new ZapXmlConfiguration(FILE_CONFIG);
config.setAutoSave(false);
lang = config.getString(OptionsParamView.LOCALE, OptionsParamView.DEFAULT_LOCALE);
if (lang.length() == 0) {
lang = OptionsParamView.DEFAULT_LOCALE;
}
}
String[] langArray = lang.split("_");
return new Locale.Builder().setLanguage(langArray[0]).setRegion(langArray[1]).build();
} catch (Exception e) {
System.out.println("Failed to load locale " + e);
}
return Locale.ENGLISH;
}
private void setUpLogging() throws IOException {
backupLegacyLog4jConfig();
String fileName = "log4j2.properties";
File logFile = new File(zapHome, fileName);
if (!logFile.exists()) {
String defaultConfig = "/org/zaproxy/zap/resources/log4j2-home.properties";
copyFileToHome(logFile.toPath(), "xml/" + fileName, defaultConfig);
}
Configurator.reconfigure(logFile.toURI());
}
private static void backupLegacyLog4jConfig() {
String fileName = "log4j.properties";
Path backupLegacyConfig = Paths.get(zapHome, fileName + ".bak");
if (Files.exists(backupLegacyConfig)) {
logAndPrintInfo("Ignoring legacy log4j.properties file, backup already exists.");
return;
}
Path legacyConfig = Paths.get(zapHome, fileName);
if (Files.exists(legacyConfig)) {
logAndPrintInfo("Creating backup of legacy log4j.properties file...");
try {
Files.move(legacyConfig, backupLegacyConfig);
} catch (IOException e) {
logAndPrintError("Failed to backup legacy Log4j configuration file:", e);
}
}
}
private void handleMalformedConfigFile(Exception e) throws IOException {
logAndPrintError("Failed to load/upgrade config file:", e);
try {
Path backupPath = Paths.get(zapHome, "config-" + Math.random() + ".xml.bak");
logAndPrintInfo("Creating back up for user inspection: " + backupPath);
Files.copy(Paths.get(FILE_CONFIG), backupPath);
logAndPrintInfo("Back up successfully created.");
} catch (IOException ioe) {
logAndPrintError("Failed to backup file:", ioe);
}
logAndPrintInfo("Using default config file...");
copyDefaultConfigFile();
}
private static void logAndPrintError(String message, Exception e) {
LOGGER.error(message, e);
System.err.println(message);
e.printStackTrace();
}
private static void logAndPrintInfo(String message) {
LOGGER.info(message);
System.out.println(message);
}
private void copyProperty(XMLConfiguration fromConfig, XMLConfiguration toConfig, String key) {
toConfig.setProperty(key, fromConfig.getProperty(key));
}
private void copyAllProperties(
XMLConfiguration fromConfig, XMLConfiguration toConfig, String prefix) {
Iterator<String> iter = fromConfig.getKeys(prefix);
while (iter.hasNext()) {
String key = iter.next();
copyProperty(fromConfig, toConfig, key);
}
}
private void upgradeFrom1_1_0(XMLConfiguration config) throws ConfigurationException {
// Upgrade the regexs
// ZAP: Changed to use ZapXmlConfiguration, to enforce the same character encoding when
// reading/writing configurations.
XMLConfiguration newConfig = new ZapXmlConfiguration(getUrlDefaultConfigFile());
newConfig.setAutoSave(false);
copyAllProperties(newConfig, config, "pscans");
}
private void upgradeFrom1_2_0(XMLConfiguration config) throws ConfigurationException {
// Upgrade the regexs
// ZAP: Changed to use ZapXmlConfiguration, to enforce the same character encoding when
// reading/writing configurations.
XMLConfiguration newConfig = new ZapXmlConfiguration(getUrlDefaultConfigFile());
newConfig.setAutoSave(false);
copyProperty(newConfig, config, "view.brkPanelView");
copyProperty(newConfig, config, "view.showMainToolbar");
}
private void upgradeFrom1_4_1(XMLConfiguration config) {
// As the POST_FORM option for the spider has been updated from int to boolean, keep
// compatibility for old versions
Object postForm = config.getProperty("spider.postform");
if (postForm != null) {
boolean enabled = !"0".equals(postForm.toString());
config.setProperty("spider.postform", enabled);
config.setProperty("spider.processform", enabled);
}
// Move the old session tokens to the new "httpsessions" hierarchy and
// delete the old "session" hierarchy as it's no longer used/needed.
String[] tokens = config.getStringArray("session.tokens");
for (int i = 0; i < tokens.length; ++i) {
String elementBaseKey = "httpsessions.tokens.token(" + i + ").";
config.setProperty(elementBaseKey + "name", tokens[i]);
config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
}
config.clearTree("session");
// Update the anti CSRF tokens elements/hierarchy.
tokens = config.getStringArray("anticsrf.tokens");
config.clearTree("anticsrf.tokens");
for (int i = 0; i < tokens.length; ++i) {
String elementBaseKey = "anticsrf.tokens.token(" + i + ").";
config.setProperty(elementBaseKey + "name", tokens[i]);
config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
}
// Update the invoke applications elements/hierarchy.
List<Object[]> oldData = new ArrayList<>();
for (int i = 0; ; i++) {
String baseKey = "invoke.A" + i + ".";
String host = config.getString(baseKey + "name");
if (host == null || "".equals(host)) {
break;
}
Object[] data = new Object[6];
data[0] = host;
data[1] = config.getString(baseKey + "directory", "");
data[2] = config.getString(baseKey + "command");
data[3] = config.getString(baseKey + "parameters");
data[4] = config.getBoolean(baseKey + "output", true);
data[5] = config.getBoolean(baseKey + "note", false);
oldData.add(data);
}
config.clearTree("invoke.A");
for (int i = 0, size = oldData.size(); i < size; ++i) {
String elementBaseKey = "invoke.apps.app(" + i + ").";
Object[] data = oldData.get(i);
config.setProperty(elementBaseKey + "name", data[0]);
config.setProperty(elementBaseKey + "directory", data[1]);
config.setProperty(elementBaseKey + "command", data[2]);
config.setProperty(elementBaseKey + "parameters", data[3]);
config.setProperty(elementBaseKey + "output", data[4]);
config.setProperty(elementBaseKey + "note", data[5]);
config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
}
// Update the authentication elements/hierarchy.
oldData = new ArrayList<>();
for (int i = 0; ; i++) {
String baseKey = "connection.auth.A" + i + ".";
String host = config.getString(baseKey + "hostName");
if (host == null || "".equals(host)) {
break;
}
Object[] data = new Object[5];
data[0] = host;
data[1] = Integer.valueOf(config.getString(baseKey + "port", "80"));
data[2] = config.getString(baseKey + "userName");
data[3] = config.getString(baseKey + "password");
data[4] = config.getString(baseKey + "realm");
oldData.add(data);
}
config.clearTree("connection.auth.A");
for (int i = 0, size = oldData.size(); i < size; ++i) {
String elementBaseKey = "connection.auths.auth(" + i + ").";
Object[] data = oldData.get(i);
config.setProperty(elementBaseKey + "name", "Auth " + i);
config.setProperty(elementBaseKey + "hostName", data[0]);
config.setProperty(elementBaseKey + "port", data[1]);
config.setProperty(elementBaseKey + "userName", data[2]);
config.setProperty(elementBaseKey + "password", data[3]);
config.setProperty(elementBaseKey + "realm", data[4]);
config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
}
// Update the passive scan elements/hierarchy.
String[] names = config.getStringArray("pscans.names");
oldData = new ArrayList<>();
for (String pscanName : names) {
String baseKey = "pscans." + pscanName + ".";
Object[] data = new Object[8];
data[0] = pscanName;
data[1] = config.getString(baseKey + "type");
data[2] = config.getString(baseKey + "config");
data[3] = config.getString(baseKey + "reqUrlRegex");
data[4] = config.getString(baseKey + "reqHeadRegex");
data[5] = config.getString(baseKey + "resHeadRegex");
data[6] = config.getString(baseKey + "resBodyRegex");
data[7] = config.getBoolean(baseKey + "enabled");
oldData.add(data);
}
config.clearTree("pscans.names");
for (String pscanName : names) {
config.clearTree("pscans." + pscanName);
}
for (int i = 0, size = oldData.size(); i < size; ++i) {
String elementBaseKey = "pscans.autoTagScanners.scanner(" + i + ").";
Object[] data = oldData.get(i);
config.setProperty(elementBaseKey + "name", data[0]);
config.setProperty(elementBaseKey + "type", data[1]);
config.setProperty(elementBaseKey + "config", data[2]);
config.setProperty(elementBaseKey + "reqUrlRegex", data[3]);
config.setProperty(elementBaseKey + "reqHeadRegex", data[4]);
config.setProperty(elementBaseKey + "resHeadRegex", data[5]);
config.setProperty(elementBaseKey + "resBodyRegex", data[6]);
config.setProperty(elementBaseKey + "enabled", data[7]);
}
}
private void upgradeFrom2_0_0(XMLConfiguration config) {
String forcedBrowseFile = config.getString("bruteforce.defaultFile", "");
if (!"".equals(forcedBrowseFile)) {
String absolutePath = "";
// Try the 'local' dir first
File f = new File(DIRBUSTER_CUSTOM_DIR + File.separator + forcedBrowseFile);
if (!f.exists()) {
f = new File(DIRBUSTER_DIR + File.separator + forcedBrowseFile);
}
if (f.exists()) {
absolutePath = f.getAbsolutePath();
}
config.setProperty("bruteforce.defaultFile", absolutePath);
}
// Remove the manual request editor configurations that were incorrectly created.
config.clearTree("nullrequest");
config.clearTree("nullresponse");
}
private void upgradeFrom2_2_0(XMLConfiguration config) {
try {
if (config.getInt(OptionsParamCheckForUpdates.CHECK_ON_START, 0) == 0) {
/*
* Check-for-updates on start disabled - force another prompt to ask the user,
* as this option can have been unset incorrectly before.
* And we want to encourage users to use this ;)
*/
config.setProperty(OptionsParamCheckForUpdates.DAY_LAST_CHECKED, "");
}
} catch (ConversionException e) {
LOGGER.debug(
"The option {} is not an int.", OptionsParamCheckForUpdates.CHECK_ON_START, e);
}
// Clear the block list - addons were incorrectly added to this if an update failed
config.setProperty(AddOnLoader.ADDONS_BLOCK_LIST, "");
}
private void upgradeFrom2_2_2(XMLConfiguration config) {
try {
// Change the type of the option from int to boolean.
int oldValue = config.getInt(OptionsParamCheckForUpdates.CHECK_ON_START, 1);
config.setProperty(OptionsParamCheckForUpdates.CHECK_ON_START, oldValue != 0);
} catch (ConversionException e) {
LOGGER.debug(
"The option {} is no longer an int.",
OptionsParamCheckForUpdates.CHECK_ON_START,
e);
}
}
private void upgradeFrom2_3_1(XMLConfiguration config) {
// Remove old authentication options no longer used
config.clearProperty("connection.confirmRemoveAuth");
config.clearTree("options.auth");
}
private void upgradeFrom2_4_3(XMLConfiguration config) {
List<Object[]> oldData = new ArrayList<>();
// Convert extensions' options to not use extensions' names as XML element names
for (Iterator<String> it = config.getKeys("ext"); it.hasNext(); ) {
String key = it.next();
Object[] data = new Object[2];
data[0] = key.substring(4);
data[1] = config.getBoolean(key);
oldData.add(data);
}
config.clearTree("ext");
for (int i = 0, size = oldData.size(); i < size; ++i) {
String elementBaseKey = "extensions.extension(" + i + ").";
Object[] data = oldData.get(i);
config.setProperty(elementBaseKey + "name", data[0]);
config.setProperty(elementBaseKey + "enabled", data[1]);
}
}
private static void upgradeFrom2_5_0(XMLConfiguration config) {
String oldConfigKey = "proxy.modifyAcceptEncoding";
config.setProperty(
"proxy.removeUnsupportedEncodings", config.getBoolean(oldConfigKey, true));
config.clearProperty(oldConfigKey);
// Convert passive scanners options to new structure
Set<String> classnames = new HashSet<>();
for (Iterator<String> it = config.getKeys(); it.hasNext(); ) {
String key = it.next();
if (!key.startsWith("pscans.org")) {
continue;
}
classnames.add(key.substring(7, key.lastIndexOf('.')));
}
List<Object[]> oldData = new ArrayList<>();
for (String classname : classnames) {
Object[] data = new Object[3];
data[0] = classname;
data[1] = config.getBoolean("pscans." + classname + ".enabled", true);
data[2] = config.getString("pscans." + classname + ".level", "");
oldData.add(data);
}
config.clearTree("pscans.org");
for (int i = 0, size = oldData.size(); i < size; ++i) {
String elementBaseKey = "pscans.pscanner(" + i + ").";
Object[] data = oldData.get(i);
config.setProperty(elementBaseKey + "classname", data[0]);
config.setProperty(elementBaseKey + "enabled", data[1]);
config.setProperty(elementBaseKey + "level", data[2]);
}
}
private static void upgradeFrom2_7_0(XMLConfiguration config) {
// Remove options from SNI Terminator.
config.clearTree("sniterm");
String certUseKey = "certificate.use";
try {
// Change the type of the option from int to boolean.
int oldValue = config.getInt(certUseKey, 0);
config.setProperty(certUseKey, oldValue != 0);
} catch (ConversionException e) {
LOGGER.debug("The option {} is no longer an int.", certUseKey, e);
}
}
private static void upgradeFrom2_8_0(XMLConfiguration config) {
updatePscanTagMailtoPattern(config);
}
static void upgradeFrom2_9_0(XMLConfiguration config) {
String oldKeyName = ".markocurrences"; // This is the typo we want to fix
String newKeyName = ".markoccurrences";
config.getKeys()
.forEachRemaining(
key -> {
if (key.endsWith(oldKeyName)) {
config.setProperty(
key.replace(oldKeyName, newKeyName),
config.getProperty(key));
config.clearProperty(key);
}
});
// Use new Look and Feel
config.setProperty(
OptionsParamView.LOOK_AND_FEEL, OptionsParamView.DEFAULT_LOOK_AND_FEEL_NAME);
config.setProperty(
OptionsParamView.LOOK_AND_FEEL_CLASS, OptionsParamView.DEFAULT_LOOK_AND_FEEL_CLASS);
}
private static void upgradeFrom2_11_1(XMLConfiguration config) {
config.setProperty("view.largeRequest", null);
config.setProperty("view.largeResponse", null);
config.setProperty("hud.enableTelemetry", null);
}
static void upgradeFrom2_14_0(XMLConfiguration config) throws ConfigurationException {
List<HierarchicalConfiguration> existingTagScanners =
config.configurationsAt("pscans.autoTagScanners.scanner");
List<Object> existingNames = config.getList("pscans.autoTagScanners.scanner.name");
String leadingAutoTagScannersKey = "pscans.autoTagScanners.scanner(";
String trailingNameKey = ").name";
String trailingTypeKey = ").type";
String trailingConfigKey = ").config";
String trailingResHeadRegex = ").resHeadRegex";
String trailingEnableKey = ").enabled";
int index = existingTagScanners.size(); // Size is next index due to 0th start
if (!existingNames.contains("json_extended")) {
config.addProperty(
leadingAutoTagScannersKey + index + trailingNameKey, "json_extended");
config.addProperty(leadingAutoTagScannersKey + index + trailingTypeKey, "TAG");
config.addProperty(leadingAutoTagScannersKey + index + trailingConfigKey, "JSON");
config.addProperty(
leadingAutoTagScannersKey + index + trailingResHeadRegex,
"content-type:\\s{0,10}.{1,20}\\/.{0,100}json");
config.addProperty(leadingAutoTagScannersKey + index + trailingEnableKey, false);
++index;
}
if (!existingNames.contains("response_yaml")) {
config.addProperty(
leadingAutoTagScannersKey + index + trailingNameKey, "response_yaml");
config.addProperty(leadingAutoTagScannersKey + index + trailingTypeKey, "TAG");
config.addProperty(leadingAutoTagScannersKey + index + trailingConfigKey, "YAML");
config.addProperty(
leadingAutoTagScannersKey + index + trailingResHeadRegex,
"content-type:\\s{0,10}.{1,20}\\/.{0,100}yaml");
config.addProperty(leadingAutoTagScannersKey + index + trailingEnableKey, false);
++index;
}
if (!existingNames.contains("response_xml")) {
config.addProperty(leadingAutoTagScannersKey + index + trailingNameKey, "response_xml");
config.addProperty(leadingAutoTagScannersKey + index + trailingTypeKey, "TAG");
config.addProperty(leadingAutoTagScannersKey + index + trailingConfigKey, "XML");
config.addProperty(
leadingAutoTagScannersKey + index + trailingResHeadRegex,
"content-type:\\s{0,10}.{1,20}\\/.{0,100}xml");
config.addProperty(leadingAutoTagScannersKey + index + trailingEnableKey, false);
}
}
private static void updateDefaultInt(
XMLConfiguration config, String key, int oldDefault, int newDefault) {
try {
if (config.getInteger(key, oldDefault) == oldDefault) {
config.setProperty(key, newDefault);
}
} catch (Exception e) {
// Don't bother reporting, just fix
config.setProperty(key, newDefault);
}
}
static void upgradeFrom2_12(XMLConfiguration config) {
updateDefaultInt(config, "scanner.threadPerHost", 2, getDefaultThreadCount());
updateDefaultInt(config, "pscans.threads", 4, getDefaultThreadCount() / 2);
}
private static void updatePscanTagMailtoPattern(XMLConfiguration config) {
String autoTagScannersKey = "pscans.autoTagScanners.scanner";
List<HierarchicalConfiguration> tagScanners = config.configurationsAt(autoTagScannersKey);
String badPattern = "<.*href\\s*['\"]?mailto:";
String goodPattern = "<.*href\\s*=\\s*['\"]?mailto:";
for (int i = 0, size = tagScanners.size(); i < size; ++i) {
String currentKeyResBodyRegex = autoTagScannersKey + "(" + i + ").resBodyRegex";
if (config.getProperty(currentKeyResBodyRegex).equals(badPattern)) {
config.setProperty(currentKeyResBodyRegex, goodPattern);
break;
}
}
}
private static void updateCfuFromDefaultConfig(XMLConfiguration config) {
Path path = getPathDefaultConfigFile();
if (!Files.exists(path)) {
return;
}
ZapXmlConfiguration defaultConfig;
try {
defaultConfig = new ZapXmlConfiguration(path.toFile());
} catch (ConfigurationException e) {
logAndPrintError("Failed to read default configuration file " + path, e);
return;
}
copyPropertyIfSet(defaultConfig, config, "start.checkForUpdates");
copyPropertyIfSet(defaultConfig, config, "start.downloadNewRelease");
copyPropertyIfSet(defaultConfig, config, "start.checkAddonUpdates");
copyPropertyIfSet(defaultConfig, config, "start.installAddonUpdates");
copyPropertyIfSet(defaultConfig, config, "start.installScannerRules");
copyPropertyIfSet(defaultConfig, config, "start.reportReleaseAddons");
copyPropertyIfSet(defaultConfig, config, "start.reportBetaAddons");
copyPropertyIfSet(defaultConfig, config, "start.reportAlphaAddons");
}
private static void copyPropertyIfSet(XMLConfiguration from, XMLConfiguration to, String key) {
Object value = from.getProperty(key);
if (value != null) {
to.setProperty(key, value);
}
}
public static void setLocale(String loc) {
String[] langArray = loc.split("_");
Locale locale =
new Locale.Builder().setLanguage(langArray[0]).setRegion(langArray[1]).build();
Locale.setDefault(locale);
if (messages == null) {
messages = new I18N(locale);
} else {
messages.setLocale(locale);
}
}
public static Locale getLocale() {
return messages.getLocal();
}
/**
* Returns the system's {@code Locale} (as determined by the JVM at startup, {@link
* Locale#getDefault()}). Should be used to show locale dependent information in the system's
* locale.
*
* <p><strong>Note:</strong> The default locale is overridden with the ZAP's user defined
* locale/language.
*
* @return the system's {@code Locale}
* @see Locale#setDefault(Locale)
*/
public static Locale getSystemsLocale() {
return SYSTEMS_LOCALE;
}
public static Constant getInstance() {
if (instance == null) {
// ZAP: Changed to use the method createInstance().
createInstance(null);
}
return instance;
}
public static synchronized void createInstance(ControlOverrides overrides) {
if (instance == null) {
instance = new Constant(overrides);
}
}
private void setAcceleratorKeys() {
// Undo/Redo
if (Constant.isMacOsX()) {
ACCELERATOR_UNDO = "meta Z";
ACCELERATOR_REDO = "meta shift Z";
ACCELERATOR_TRIGGER_KEY = "Meta";
} else {
ACCELERATOR_UNDO = "control Z";
ACCELERATOR_REDO = "control Y";
ACCELERATOR_TRIGGER_KEY = "Control";
}
}
// Determine Windows Operating System
// ZAP: Changed to final.
private static final Pattern patternWindows =
Pattern.compile("window", Pattern.CASE_INSENSITIVE);
public static boolean isWindows() {
String os_name = System.getProperty("os.name");
Matcher matcher = patternWindows.matcher(os_name);
return matcher.find();
}
// Determine Linux Operating System
// ZAP: Changed to final.
private static final Pattern patternLinux = Pattern.compile("linux", Pattern.CASE_INSENSITIVE);
public static boolean isLinux() {
String os_name = System.getProperty("os.name");
Matcher matcher = patternLinux.matcher(os_name);
return matcher.find();
}
// Determine Windows Operating System
// ZAP: Changed to final.
private static final Pattern patternMacOsX = Pattern.compile("mac", Pattern.CASE_INSENSITIVE);
public static boolean isMacOsX() {
String os_name = System.getProperty("os.name");
Matcher matcher = patternMacOsX.matcher(os_name);
return matcher.find();
}
public static void setZapHome(String dir) {
zapHome = getAbsolutePath(dir);
}
/**
* Returns the absolute path for the given {@code directory}.
*
* <p>The path is terminated with a separator.
*
* @param directory the directory whose path will be made absolute
* @return the absolute path for the given {@code directory}, terminated with a separator
* @since 2.4.0
*/
private static String getAbsolutePath(String directory) {
String realPath = Paths.get(directory).toAbsolutePath().toString();
String separator = FileSystems.getDefault().getSeparator();
if (!realPath.endsWith(separator)) {
realPath += separator;
}
return realPath;
}
public static String getZapHome() {
return zapHome;
}
/**
* Returns the path to default configuration file, located in installation directory.
*
* <p><strong>Note:</strong> The default configuration file is not guaranteed to exist, for
* example, when running just with ZAP JAR.
*
* @return the {@code Path} to default configuration file.
* @since 2.4.2
*/
public static Path getPathDefaultConfigFile() {
return Paths.get(getZapInstall(), "xml", FILE_CONFIG_NAME);
}
public static File getContextsDir() {
return getFromHomeDir(USER_CONTEXTS_DIR);
}
public static File getPoliciesDir() {
return getFromHomeDir(USER_POLICIES_DIR);
}
private static File getFromHomeDir(String subDir) {
Path path = Paths.get(Constant.getZapHome(), subDir);
try {
if (Files.notExists(path)) {
Files.createDirectory(path);
}
} catch (IOException e) {
}
if (Files.isDirectory(path) && Files.isWritable(path)) {
return path.toFile();
}
return Model.getSingleton().getOptionsParam().getUserDirectory();
}
public static void setZapInstall(String dir) {
zapInstall = getAbsolutePath(dir);
}
public static String getZapInstall() {
if (zapInstall == null) {
String path = ".";
Path localDir = Paths.get(path);
if (!Files.isDirectory(localDir.resolve("db"))
|| !Files.isDirectory(localDir.resolve("lang"))) {
try {
Path sourceLocation =
Paths.get(
ZAP.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI());
if (!Files.isDirectory(sourceLocation)) {
sourceLocation = sourceLocation.getParent();
}
path = sourceLocation.toString();
} catch (URISyntaxException e) {
System.err.println(
"Failed to determine the ZAP installation dir: " + e.getMessage());
path = localDir.toAbsolutePath().toString();
}
// Loggers wont have been set up yet
System.out.println("Defaulting ZAP install dir to " + path);
}
zapInstall = getAbsolutePath(path);
}
return zapInstall;
}
private static Manifest getManifest() {
String className = Constant.class.getSimpleName() + ".class";
String classPath = Constant.class.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
return null;
}
String manifestPath =
classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
try {
return new Manifest(new URI(manifestPath).toURL().openStream());
} catch (Exception e) {
// Ignore
return null;
}
}
private static String getVersionFromManifest() {
Manifest manifest = getManifest();
if (manifest != null) {
Attributes attr = manifest.getMainAttributes();
return attr.getValue("Implementation-Version");
} else {
return DEV_VERSION;
}
}
public static Date getReleaseCreateDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Manifest manifest = getManifest();
if (manifest != null) {
Attributes attr = manifest.getMainAttributes();
try {
return sdf.parse(attr.getValue("Create-Date"));
} catch (ParseException e) {
// Ignore - treat as undated
}
}
return null;
}
public static Date getInstallDate() {
String className = Constant.class.getSimpleName() + ".class";
String classPath = Constant.class.getResource(className).toString();
if (!classPath.startsWith("jar:file:")) {
// Class not from JAR
return null;
}
classPath = classPath.substring(9);
int ind = classPath.indexOf("!");
if (ind > 0) {
classPath = classPath.substring(0, ind);
}
File f = new File(classPath);
if (f.exists()) {
// Choose the parent directories date, in case the creation date was maintained
return new Date(f.getParentFile().lastModified());
}
return null;
}
/**
* Tells whether or not the "dev mode" should be enabled.
*
* <p>Should be used to enable development related utilities/functionalities.
*
* @return {@code true} if the "dev mode" should be enabled, {@code false} otherwise.
* @since 2.8.0
*/
public static boolean isDevMode() {
return devMode || isDevBuild();
}
/**
* Sets whether or not the "dev mode" should be enabled.
*
* <p><strong>Note:</strong> This method should be called only by bootstrap classes.
*
* @param devMode {@code true} if the "dev mode" should be enabled, {@code false} otherwise.
*/
public static void setDevMode(boolean devMode) {
Constant.devMode = devMode;
}
/**
* Sets whether or not ZAP should be 'silent' i.e. not make any unsolicited requests.
*
* <p><strong>Note:</strong> This method should be called only by bootstrap classes.
*
* @param silent {@code true} if ZAP should be silent, {@code false} otherwise.
* @since 2.8.0
*/
public static void setSilent(boolean silent) {
Constant.silent = silent;
}
/**
* Tells whether or not ZAP is running from a dev build.
*
* @return {@code true} if it's a dev build, {@code false} otherwise.
* @see #isDevMode()
*/
public static boolean isDevBuild() {
return isDevBuild(PROGRAM_VERSION);
}
public static boolean isDevBuild(String version) {
// Dev releases with be called "Dev Build" date stamped builds will be of the format
// D-{yyyy}-{mm}-{dd}
return DEV_VERSION.equals(version);
}
public static boolean isDailyBuild(String version) {
// Date stamped builds will be of the format D-{yyyy}-{mm}-{dd}
return version.startsWith("D-");
}
public static boolean isDailyBuild() {
return isDailyBuild(PROGRAM_VERSION);
}
/**
* If true then ZAP should not make any unsolicited requests, e.g. check-for-updates
*
* @return true if ZAP should not make any unsolicited requests, e.g. check-for-updates
* @since 2.8.0
*/
public static boolean isSilent() {
return silent;
}
public static void setLowMemoryOption(boolean lowMem) {
if (lowMemoryOption != null) {
throw new InvalidParameterException(
"Low memory option already set to " + lowMemoryOption);
}
lowMemoryOption = lowMem;
}
public static boolean isLowMemoryOptionSet() {
return lowMemoryOption != null && lowMemoryOption;
}
/**
* Tells whether or not ZAP is running in Kali (and it's not a daily build).
*
* @return {@code true} if running in Kali (and it's not daily build), {@code false} otherwise
*/
public static boolean isKali() {
if (onKali == null) {
onKali = Boolean.FALSE;
File osReleaseFile = new File("/etc/os-release");
if (isLinux() && !isDailyBuild() && osReleaseFile.exists()) {
// Ignore the fact we're on Kali if this is a daily build - they will only have been
// installed manually
try (InputStream in = Files.newInputStream(osReleaseFile.toPath())) {
Properties osProps = new Properties();
osProps.load(in);
String osLikeValue = osProps.getProperty("ID");
if (osLikeValue != null) {
String[] oSLikes = osLikeValue.split(" ");
for (String osLike : oSLikes) {
if (osLike.equalsIgnoreCase("kali")) {
onKali = Boolean.TRUE;
break;
}
}
}
} catch (Exception e) {
// Ignore
}
}
}
return onKali;
}
public static boolean isBackBox() {
if (onBackBox == null) {
onBackBox = Boolean.FALSE;
File issueFile = new File("/etc/issue");
if (isLinux() && !isDailyBuild() && issueFile.exists()) {
// Ignore the fact we're on BackBox if this is a daily build - they will only have
// been installed manually
try {
String content = new String(Files.readAllBytes(issueFile.toPath()));
if (content.startsWith("BackBox")) {
onBackBox = Boolean.TRUE;
}
} catch (Exception e) {
// Ignore
}
}
}
return onBackBox;
}
/**
* Returns true if ZAP is running in a container like Docker or Flatpak
*
* @see #getContainerName
* @since 2.11.0
*/
public static boolean isInContainer() {
if (inContainer == null) {
// This is created by the Docker files from 2.11
File containerFile = new File(ZAP_CONTAINER_FILE);
File flatpakFile = new File(FLATPAK_FILE);
File snapFile = new File(SNAP_FILE);
if (isLinux() && containerFile.exists()) {
inContainer = true;
String home = System.getenv(HOME_ENVVAR);
boolean inWebSwing = home != null && home.contains(WEBSWING_NAME);
try {
containerName =
new String(
Files.readAllBytes(containerFile.toPath()),
StandardCharsets.UTF_8)
.trim();
if (inWebSwing) {
// Append the webswing name so we don't loose the docker image name
containerName += "." + WEBSWING_NAME;
}
} catch (IOException e) {
// Ignore
}
} else if (flatpakFile.exists()) {
inContainer = true;
containerName = FLATPAK_NAME;
} else if (snapFile.exists()) {
inContainer = true;
containerName = SNAP_NAME;
} else {
inContainer = false;
}
}
return inContainer;
}
/**
* Returns the name of the container ZAP is running in (if any) e.g. zap2docker-stable, flatpak
* or null if not running in a recognised container
*
* @since 2.11.0
*/
public static String getContainerName() {
isInContainer();
return containerName;
}
/**
* Returns the recommended default number of threads. Note that add-ons should use the
* equivalent method in the commonlib add-on.
*
* @return the recommended default number of threads.
*/
public static int getDefaultThreadCount() {
return Runtime.getRuntime().availableProcessors() * 2;
}
}
| zaproxy/zaproxy | zap/src/main/java/org/parosproxy/paros/Constant.java |
45,310 | package com.mxgraph.online;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Simple client-side logging servlet
*/
public class LogServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2360583959079622105L;
private static final Logger log = Logger.getLogger(LogServlet.class
.getName());
static byte[] singleByteGif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, (byte) 0x80, 0x0, 0x0, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b };
/**
* The start string of error message we want to ignore
*/
static String[] configArray;
static Set<String> ignoreFilters;
/**
* The start string of error message we want to reduce to a warning
*/
static String[] warningArray;
static Set<String> warningFilters;
static
{
configArray = new String[]
{
"Uncaught TypeError: frames.ezLinkPreviewIFRAME.postMessage is not a function", // third party Chrome plugin
"Uncaught TypeError: Cannot set property 'tgt' of null" // Tampermonkey extension, https://github.com/kogg/InstantLogoSearch/issues/199
};
ignoreFilters = new HashSet<String>(Arrays.asList(configArray));
warningArray = new String[]
{
"Uncaught Error: Client got in an error state. Call reset() to reuse it!", // dropbox auth failing
"Error: Client got in an error state. Call reset() to reuse it!"
};
warningFilters = new HashSet<String>(Arrays.asList(warningArray));
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
String message = request.getParameter("msg");
String severity = request.getParameter("severity");
String version = request.getParameter("v");
String stack = request.getParameter("stack");
String userAgent = request.getHeader("User-Agent");
if (message != null)
{
Level severityLevel = Level.CONFIG;
if (severity != null)
{
severityLevel = Level.parse(severity);
}
if (severityLevel.intValue() >= 1000)
{
// Tidy up severes
message = message == null ? message : URLDecoder.decode(message, "UTF-8");
version = version == null ? version : URLDecoder.decode(version, "UTF-8");
stack = stack == null ? stack : URLDecoder.decode(stack, "UTF-8");
severityLevel = filterClientErrors(message, userAgent);
}
message = version != null ? message + "\nVERSION=" + version : message;
message = stack != null ? message + "\n" + stack : message;
log.log(severityLevel, "CLIENT-LOG:" + message);
}
response.setContentType("image/gif");
OutputStream out = response.getOutputStream();
out.write(singleByteGif);
out.flush();
out.close();
response.setStatus(HttpServletResponse.SC_OK);
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Filter out known red herring client errors by reducing their severity
* @param message the message thrown on the client
* @param userAgent the user agent string
* @return the severity to treat the message with
*/
protected Level filterClientErrors(String message, String userAgent)
{
try
{
String result = message.substring(message.indexOf("clientError:") + 12, message.indexOf(":url:"));
if (result != null)
{
if (ignoreFilters.contains(result))
{
return Level.CONFIG;
}
else if (warningFilters.contains(result))
{
return Level.WARNING;
}
}
}
catch (Exception e)
{
}
if (userAgent != null && userAgent.contains("compatible; MSIE 8.0;"))
{
return Level.WARNING;
}
return Level.SEVERE;
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/LogServlet.java |
45,311 | /*
* This file is part of Arduino.
*
* Arduino is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU General Public License. This exception does not however
* invalidate any other reasons why the executable file might be covered by
* the GNU General Public License.
*
* Copyright 2013 Arduino LLC (http://www.arduino.cc/)
*/
package cc.arduino.packages;
import processing.app.BaseNoGui;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.helpers.PreferencesMap;
public class BoardPort {
private String address; // unique name for this port, used by Preferences
private String protocol; // how to communicate, used for Ports menu sections
private String protocolLabel; // protocol extended name to display on GUI
private String boardName;
private String label; // friendly name shown in Ports menu
private final PreferencesMap identificationPrefs; // data to match with boards.txt
private final PreferencesMap prefs; // "vendorId", "productId", "serialNumber"
private boolean online; // used by SerialBoardsLister (during upload??)
public BoardPort() {
this.prefs = new PreferencesMap();
this.identificationPrefs = new PreferencesMap();
}
public BoardPort(BoardPort bp) {
prefs = new PreferencesMap(bp.prefs);
identificationPrefs = new PreferencesMap(bp.identificationPrefs);
address = bp.address;
protocol = bp.protocol;
boardName = bp.boardName;
label = bp.label;
online = bp.online;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocolLabel() {
return protocolLabel;
}
public void setProtocolLabel(String protocolLabel) {
this.protocolLabel = protocolLabel;
}
public String getBoardName() {
return boardName;
}
public void setBoardName(String boardName) {
this.boardName = boardName;
}
public PreferencesMap getPrefs() {
return prefs;
}
public PreferencesMap getIdentificationPrefs() {
return identificationPrefs;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setOnlineStatus(boolean online) {
this.online = online;
}
public boolean isOnline() {
return online;
}
@Override
public String toString() {
return this.address;
}
public String toCompleteString() {
return this.address + "_" + this.getPrefs().get("vid") + "_" + this.getPrefs().get("pid");
}
// Search for the board which matches identificationPrefs.
// If found, boardName is set to the name from boards.txt
// and the board is returned. If not found, null is returned.
public TargetBoard searchMatchingBoard() {
if (identificationPrefs == null || identificationPrefs.isEmpty()) return null;
for (TargetPackage targetPackage : BaseNoGui.packages.values()) {
for (TargetPlatform targetPlatform : targetPackage.getPlatforms().values()) {
for (TargetBoard board : targetPlatform.getBoards().values()) {
if (matchesBoard(board)) {
setBoardName(board.getName());
return board;
}
}
}
}
return null;
}
public boolean matchesBoard(TargetBoard board) {
PreferencesMap identificationProps = getIdentificationPrefs();
PreferencesMap boardProps = board.getPreferences();
String wildMatcher = identificationProps.get(".");
if (wildMatcher != null) {
if (wildMatcher.equals(board.getId())) {
return true;
}
if (wildMatcher.equals(board.getFQBN())) {
return true;
}
}
// Identification properties are defined in boards.txt with a ".N" suffix
// for example:
//
// uno.name=Arduino/Genuino Uno
// uno.vid.0=0x2341
// uno.pid.0=0x0043
// uno.vid.1=0x2341
// uno.pid.1=0x0001
// uno.vid.2=0x2A03
// uno.pid.2=0x0043
// uno.vid.3=0x2341
// uno.pid.3=0x0243
//
// so we must search starting from suffix ".0" and increasing until we
// found a match or the board has no more identification properties defined
for (int suffix = 0;; suffix++) {
boolean found = true;
for (String prop : identificationProps.keySet()) {
String value = identificationProps.get(prop);
prop += "." + suffix;
if (!boardProps.containsKey(prop)) {
return false;
}
if (!value.equalsIgnoreCase(boardProps.get(prop))) {
found = false;
break;
}
}
if (found) {
return true;
}
}
}
}
| maxbbraun/Arduino | arduino-core/src/cc/arduino/packages/BoardPort.java |
45,313 | /*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import io.mycat.buffer.NettyBufferPool;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import io.mycat.backend.BackendConnection;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.backend.mysql.nio.handler.MultiNodeCoordinator;
import io.mycat.backend.mysql.xa.CoordinatorLogEntry;
import io.mycat.backend.mysql.xa.ParticipantLogEntry;
import io.mycat.backend.mysql.xa.TxState;
import io.mycat.backend.mysql.xa.XARollbackCallback;
import io.mycat.backend.mysql.xa.recovery.Repository;
import io.mycat.backend.mysql.xa.recovery.impl.FileSystemRepository;
import io.mycat.buffer.BufferPool;
import io.mycat.buffer.DirectByteBufferPool;
import io.mycat.cache.CacheService;
import io.mycat.config.MycatConfig;
import io.mycat.config.classloader.DynaClassLoader;
import io.mycat.config.loader.zkprocess.comm.ZkConfig;
import io.mycat.config.loader.zkprocess.comm.ZkParamCfg;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.SystemConfig;
import io.mycat.config.model.TableConfig;
import io.mycat.config.table.structure.MySQLTableStructureDetector;
import io.mycat.manager.ManagerConnectionFactory;
import io.mycat.memory.MyCatMemory;
import io.mycat.net.AIOAcceptor;
import io.mycat.net.AIOConnector;
import io.mycat.net.NIOAcceptor;
import io.mycat.net.NIOConnector;
import io.mycat.net.NIOProcessor;
import io.mycat.net.NIOReactorPool;
import io.mycat.net.SocketAcceptor;
import io.mycat.net.SocketConnector;
import io.mycat.route.MyCATSequnceProcessor;
import io.mycat.route.RouteService;
import io.mycat.route.factory.RouteStrategyFactory;
import io.mycat.route.sequence.handler.SequenceHandler;
import io.mycat.server.ServerConnectionFactory;
import io.mycat.server.interceptor.SQLInterceptor;
import io.mycat.server.interceptor.impl.GlobalTableUtil;
import io.mycat.sqlengine.OneRawSQLQueryResultHandler;
import io.mycat.sqlengine.SQLJob;
import io.mycat.statistic.SQLRecorder;
import io.mycat.statistic.stat.SqlResultSizeRecorder;
import io.mycat.statistic.stat.UserStat;
import io.mycat.statistic.stat.UserStatAnalyzer;
import io.mycat.util.ExecutorUtil;
import io.mycat.util.NameableExecutor;
import io.mycat.util.TimeUtil;
import io.mycat.util.ZKUtils;
/**
* @author mycat
*/
public class MycatServer {
public static final String NAME = "MyCat";
private static final long LOG_WATCH_DELAY = 60000L;
private static final long TIME_UPDATE_PERIOD = 20L;
private static final long DEFAULT_SQL_STAT_RECYCLE_PERIOD = 5 * 1000L;
private static final long DEFAULT_OLD_CONNECTION_CLEAR_PERIOD = 5 * 1000L;
private static final MycatServer INSTANCE = new MycatServer();
private static final Logger LOGGER = LoggerFactory.getLogger("MycatServer");
private static final Repository fileRepository = new FileSystemRepository();
private final RouteService routerService;
private final CacheService cacheService;
private Properties dnIndexProperties;
//AIO连接群组
private AsynchronousChannelGroup[] asyncChannelGroups;
private volatile int channelIndex = 0;
//全局序列号
// private final MyCATSequnceProcessor sequnceProcessor = new MyCATSequnceProcessor();
private final DynaClassLoader catletClassLoader;
private final SQLInterceptor sqlInterceptor;
private volatile int nextProcessor;
// System Buffer Pool Instance
private BufferPool bufferPool;
private boolean aio = false;
//XA事务全局ID生成
private final AtomicLong xaIDInc = new AtomicLong();
//sequence处理对象
private SequenceHandler sequenceHandler;
/**
* Mycat 内存管理类
*/
private MyCatMemory myCatMemory = null;
public static final MycatServer getInstance() {
return INSTANCE;
}
private final MycatConfig config;
private final ScheduledExecutorService scheduler;
private final ScheduledExecutorService heartbeatScheduler;
private final SQLRecorder sqlRecorder;
private final AtomicBoolean isOnline;
private final long startupTime;
private NIOProcessor[] processors;
private SocketConnector connector;
private NameableExecutor businessExecutor;
private NameableExecutor sequenceExecutor;
private NameableExecutor timerExecutor;
private ListeningExecutorService listeningExecutorService;
private InterProcessMutex dnindexLock;
private long totalNetWorkBufferSize = 0;
private final AtomicBoolean startup=new AtomicBoolean(false);
private MycatServer() {
//读取文件配置
this.config = new MycatConfig();
//定时线程池,单线程线程池
scheduler = Executors.newSingleThreadScheduledExecutor();
//心跳调度独立出来,避免被其他任务影响
heartbeatScheduler = Executors.newSingleThreadScheduledExecutor();
//SQL记录器
this.sqlRecorder = new SQLRecorder(config.getSystem().getSqlRecordCount());
/**
* 是否在线,MyCat manager中有命令控制
* | offline | Change MyCat status to OFF |
* | online | Change MyCat status to ON |
*/
this.isOnline = new AtomicBoolean(true);
//缓存服务初始化
cacheService = new CacheService();
//路由计算初始化
routerService = new RouteService(cacheService);
// load datanode active index from properties
dnIndexProperties = loadDnIndexProps();
try {
//SQL解析器
sqlInterceptor = (SQLInterceptor) Class.forName(
config.getSystem().getSqlInterceptor()).newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
//catlet加载器
catletClassLoader = new DynaClassLoader(SystemConfig.getHomePath()
+ File.separator + "catlet", config.getSystem().getCatletClassCheckSeconds());
//记录启动时间
this.startupTime = TimeUtil.currentTimeMillis();
if(isUseZkSwitch()) {
String path= ZKUtils.getZKBasePath()+"lock/dnindex.lock";
dnindexLock = new InterProcessMutex(ZKUtils.getConnection(), path);
}
}
public AtomicBoolean getStartup() {
return startup;
}
public long getTotalNetWorkBufferSize() {
return totalNetWorkBufferSize;
}
public BufferPool getBufferPool() {
return bufferPool;
}
public NameableExecutor getTimerExecutor() {
return timerExecutor;
}
public DynaClassLoader getCatletClassLoader() {
return catletClassLoader;
}
public MyCATSequnceProcessor getSequnceProcessor() {
return MyCATSequnceProcessor.getInstance();
}
public SQLInterceptor getSqlInterceptor() {
return sqlInterceptor;
}
public ScheduledExecutorService getScheduler() {
return scheduler;
}
public String genXATXID() {
long seq = this.xaIDInc.incrementAndGet();
if (seq < 0) {
synchronized (xaIDInc) {
if ( xaIDInc.get() < 0 ) {
xaIDInc.set(0);
}
seq = xaIDInc.incrementAndGet();
}
}
return "'Mycat." + this.getConfig().getSystem().getMycatNodeId() + "." + seq + "'";
}
public String getXATXIDGLOBAL(){
return "'" + getUUID() + "'";
}
public static String getUUID(){
String s = UUID.randomUUID().toString();
//去掉“-”符号
return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
}
public MyCatMemory getMyCatMemory() {
return myCatMemory;
}
/**
* get next AsynchronousChannel ,first is exclude if multi
* AsynchronousChannelGroups
*
* @return
*/
public AsynchronousChannelGroup getNextAsyncChannelGroup() {
if (asyncChannelGroups.length == 1) {
return asyncChannelGroups[0];
} else {
int index = (++channelIndex) % asyncChannelGroups.length;
if (index == 0) {
++channelIndex;
return asyncChannelGroups[1];
} else {
return asyncChannelGroups[index];
}
}
}
public MycatConfig getConfig() {
return config;
}
public void beforeStart() {
String home = SystemConfig.getHomePath();
//ZkConfig.instance().initZk();
}
public void startup() throws IOException {
SystemConfig system = config.getSystem();
int processorCount = system.getProcessors();
//init RouteStrategyFactory first
RouteStrategyFactory.init();
// server startup
LOGGER.info(NAME + " is ready to startup ...");
String inf = "Startup processors ...,total processors:"
+ system.getProcessors() + ",aio thread pool size:"
+ system.getProcessorExecutor()
+ " \r\n each process allocated socket buffer pool "
+ " bytes ,a page size:"
+ system.getBufferPoolPageSize()
+ " a page's chunk number(PageSize/ChunkSize) is:"
+ (system.getBufferPoolPageSize()
/system.getBufferPoolChunkSize())
+ " buffer page's number is:"
+ system.getBufferPoolPageNumber();
LOGGER.info(inf);
LOGGER.info("sysconfig params:" + system.toString());
// startup manager
ManagerConnectionFactory mf = new ManagerConnectionFactory();
ServerConnectionFactory sf = new ServerConnectionFactory();
SocketAcceptor manager = null;
SocketAcceptor server = null;
aio = (system.getUsingAIO() == 1);
// startup processors
int threadPoolSize = system.getProcessorExecutor();
processors = new NIOProcessor[processorCount];
// a page size
int bufferPoolPageSize = system.getBufferPoolPageSize();
// total page number
short bufferPoolPageNumber = system.getBufferPoolPageNumber();
//minimum allocation unit
short bufferPoolChunkSize = system.getBufferPoolChunkSize();
int socketBufferLocalPercent = system.getProcessorBufferLocalPercent();
int bufferPoolType = system.getProcessorBufferPoolType();
switch (bufferPoolType){
case 0:
bufferPool = new DirectByteBufferPool(bufferPoolPageSize,bufferPoolChunkSize,
bufferPoolPageNumber,system.getFrontSocketSoRcvbuf());
totalNetWorkBufferSize = bufferPoolPageSize*bufferPoolPageNumber;
break;
case 1:
/**
* todo 对应权威指南修改:
*
* bytebufferarena由6个bytebufferlist组成,这六个list有减少内存碎片的机制
* 每个bytebufferlist由多个bytebufferchunk组成,每个list也有减少内存碎片的机制
* 每个bytebufferchunk由多个page组成,平衡二叉树管理内存使用状态,计算灵活
* 设置的pagesize对应bytebufferarena里面的每个bytebufferlist的每个bytebufferchunk的buffer长度
* bufferPoolChunkSize对应每个bytebufferchunk的每个page的长度
* bufferPoolPageNumber对应每个bytebufferlist有多少个bytebufferchunk
*/
totalNetWorkBufferSize = 6*bufferPoolPageSize * bufferPoolPageNumber;
break;
case 2:
bufferPool = new NettyBufferPool(bufferPoolChunkSize);
LOGGER.info("Use Netty Buffer Pool");
break;
default:
bufferPool = new DirectByteBufferPool(bufferPoolPageSize,bufferPoolChunkSize,
bufferPoolPageNumber,system.getFrontSocketSoRcvbuf());;
totalNetWorkBufferSize = bufferPoolPageSize*bufferPoolPageNumber;
}
/**
* Off Heap For Merge/Order/Group/Limit 初始化
*/
if(system.getUseOffHeapForMerge() == 1){
try {
myCatMemory = new MyCatMemory(system,totalNetWorkBufferSize);
} catch (NoSuchFieldException e) {
LOGGER .error("NoSuchFieldException",e);
} catch (IllegalAccessException e) {
LOGGER.error("Error",e);
}
}
businessExecutor = ExecutorUtil.create("BusinessExecutor",
threadPoolSize);
sequenceExecutor = ExecutorUtil.create("SequenceExecutor", threadPoolSize);
timerExecutor = ExecutorUtil.create("Timer", system.getTimerExecutor());
listeningExecutorService = MoreExecutors.listeningDecorator(businessExecutor);
for (int i = 0; i < processors.length; i++) {
processors[i] = new NIOProcessor("Processor" + i, bufferPool,
businessExecutor);
}
if (aio) {
LOGGER.info("using aio network handler ");
asyncChannelGroups = new AsynchronousChannelGroup[processorCount];
// startup connector
connector = new AIOConnector();
for (int i = 0; i < processors.length; i++) {
asyncChannelGroups[i] = AsynchronousChannelGroup.withFixedThreadPool(processorCount,
new ThreadFactory() {
private int inx = 1;
@Override
public Thread newThread(Runnable r) {
Thread th = new Thread(r);
//TODO
th.setName(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "AIO" + (inx++));
LOGGER.info("created new AIO thread "+ th.getName());
return th;
}
}
);
}
manager = new AIOAcceptor(NAME + "Manager", system.getBindIp(),
system.getManagerPort(), mf, this.asyncChannelGroups[0]);
// startup server
server = new AIOAcceptor(NAME + "Server", system.getBindIp(),
system.getServerPort(), sf, this.asyncChannelGroups[0]);
} else {
LOGGER.info("using nio network handler ");
NIOReactorPool reactorPool = new NIOReactorPool(
DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOREACTOR",
processors.length);
connector = new NIOConnector(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOConnector", reactorPool);
((NIOConnector) connector).start();
manager = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME
+ "Manager", system.getBindIp(), system.getManagerPort(), mf, reactorPool);
server = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME
+ "Server", system.getBindIp(), system.getServerPort(), sf, reactorPool);
}
// manager start
manager.start();
LOGGER.info(manager.getName() + " is started and listening on " + manager.getPort());
server.start();
// server started
LOGGER.info(server.getName() + " is started and listening on " + server.getPort());
LOGGER.info("===============================================");
// init datahost
Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
LOGGER.info("Initialize dataHost ...");
for (PhysicalDBPool node : dataHosts.values()) {
String index = dnIndexProperties.getProperty(node.getHostName(),"0");
if (!"0".equals(index)) {
LOGGER.info("init datahost: " + node.getHostName() + " to use datasource index:" + index);
}
node.init(Integer.parseInt(index));
node.startHeartbeat();
}
long dataNodeIldeCheckPeriod = system.getDataNodeIdleCheckPeriod();
heartbeatScheduler.scheduleAtFixedRate(updateTime(), 0L, TIME_UPDATE_PERIOD,TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(processorCheck(), 0L, system.getProcessorCheckPeriod(),TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataNodeConHeartBeatCheck(dataNodeIldeCheckPeriod), 0L, dataNodeIldeCheckPeriod,TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataNodeHeartbeat(), 0L, system.getDataNodeHeartbeatPeriod(),TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataSourceOldConsClear(), 0L, DEFAULT_OLD_CONNECTION_CLEAR_PERIOD, TimeUnit.MILLISECONDS);
scheduler.schedule(catletClassClear(), 30000,TimeUnit.MILLISECONDS);
if(system.getCheckTableConsistency()==1) {
scheduler.scheduleAtFixedRate(tableStructureCheck(), 0L, system.getCheckTableConsistencyPeriod(), TimeUnit.MILLISECONDS);
}
if(system.getUseSqlStat()==1) {
scheduler.scheduleAtFixedRate(recycleSqlStat(), 0L, DEFAULT_SQL_STAT_RECYCLE_PERIOD, TimeUnit.MILLISECONDS);
}
if(system.getUseGlobleTableCheck() == 1){ // 全局表一致性检测是否开启
scheduler.scheduleAtFixedRate(glableTableConsistencyCheck(), 0L, system.getGlableTableCheckPeriod(), TimeUnit.MILLISECONDS);
}
//定期清理结果集排行榜,控制拒绝策略
scheduler.scheduleAtFixedRate(resultSetMapClear(),0L, system.getClearBigSqLResultSetMapMs(),TimeUnit.MILLISECONDS);
// new Thread(tableStructureCheck()).start();
//XA Init recovery Log
LOGGER.info("===============================================");
LOGGER.info("Perform XA recovery log ...");
performXARecoveryLog();
if(isUseZkSwitch()) {
//首次启动如果发现zk上dnindex为空,则将本地初始化上zk
initZkDnindex();
}
initRuleData();
startup.set(true);
}
public void initRuleData() {
if(!isUseZk()) return;
InterProcessMutex ruleDataLock =null;
try {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "ruledata");
String path= ZKUtils.getZKBasePath()+"lock/ruledata.lock";
ruleDataLock= new InterProcessMutex(ZKUtils.getConnection(), path);
ruleDataLock.acquire(30, TimeUnit.SECONDS);
File[] childFiles= file.listFiles();
if(childFiles!=null&&childFiles.length>0) {
String basePath = ZKUtils.getZKBasePath() + "ruledata/";
for (File childFile : childFiles) {
CuratorFramework zk = ZKUtils.getConnection();
if (zk.checkExists().forPath(basePath + childFile.getName()) == null) {
zk.create().creatingParentsIfNeeded().forPath(basePath + childFile.getName(), Files.toByteArray(childFile));
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if(ruleDataLock!=null)
ruleDataLock.release();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private void initZkDnindex() {
try {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
dnindexLock.acquire(30, TimeUnit.SECONDS);
String path = ZKUtils.getZKBasePath() + "bindata/dnindex.properties";
CuratorFramework zk = ZKUtils.getConnection();
if (zk.checkExists().forPath(path) == null) {
zk.create().creatingParentsIfNeeded().forPath(path, Files.toByteArray(file));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
dnindexLock.release();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public void reloadDnIndex()
{
if(MycatServer.getInstance().getProcessors()==null) return;
// load datanode active index from properties
dnIndexProperties = loadDnIndexProps();
// init datahost
Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
LOGGER.info("reInitialize dataHost ...");
for (PhysicalDBPool node : dataHosts.values()) {
String index = dnIndexProperties.getProperty(node.getHostName(),"0");
if (!"0".equals(index)) {
LOGGER.info("reinit datahost: " + node.getHostName() + " to use datasource index:" + index);
}
node.switchSource(Integer.parseInt(index),true,"reload dnindex");
}
}
private Runnable catletClassClear() {
return new Runnable() {
@Override
public void run() {
try {
catletClassLoader.clearUnUsedClass();
} catch (Exception e) {
LOGGER.warn("catletClassClear err " + e);
}
};
};
}
/**
* 清理 reload @@config_all 后,老的 connection 连接
* @return
*/
private Runnable dataSourceOldConsClear() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
long sqlTimeout = MycatServer.getInstance().getConfig().getSystem().getSqlExecuteTimeout() * 1000L;
//根据 lastTime 确认事务的执行, 超过 sqlExecuteTimeout 阀值 close connection
long currentTime = TimeUtil.currentTimeMillis();
Iterator<BackendConnection> iter = NIOProcessor.backends_old.iterator();
while( iter.hasNext() ) {
BackendConnection con = iter.next();
long lastTime = con.getLastTime();
if ( currentTime - lastTime > sqlTimeout ) {
con.close("clear old backend connection ...");
iter.remove();
}
}
}
});
};
};
}
/**
* 在bufferpool使用率大于使用率阈值时不清理
* 在bufferpool使用率小于使用率阈值时清理大结果集清单内容
*
*/
private Runnable resultSetMapClear() {
return new Runnable() {
@Override
public void run() {
try {
BufferPool bufferPool=getBufferPool();
long bufferSize=bufferPool.size();
long bufferCapacity=bufferPool.capacity();
long bufferUsagePercent=(bufferCapacity-bufferSize)*100/bufferCapacity;
if(bufferUsagePercent<config.getSystem().getBufferUsagePercent()){
Map<String, UserStat> map =UserStatAnalyzer.getInstance().getUserStatMap();
Set<String> userSet=config.getUsers().keySet();
for (String user : userSet) {
UserStat userStat = map.get(user);
if(userStat!=null){
SqlResultSizeRecorder recorder=userStat.getSqlResultSizeRecorder();
//System.out.println(recorder.getSqlResultSet().size());
recorder.clearSqlResultSet();
}
}
}
} catch (Exception e) {
LOGGER.warn("resultSetMapClear err " + e);
}
};
};
}
private Properties loadDnIndexProps() {
Properties prop = new Properties();
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
if (!file.exists()) {
return prop;
}
FileInputStream filein = null;
try {
filein = new FileInputStream(file);
prop.load(filein);
} catch (Exception e) {
LOGGER.warn("load DataNodeIndex err:" + e);
} finally {
if (filein != null) {
try {
filein.close();
} catch (IOException e) {
}
}
}
return prop;
}
/**
* save cur datanode index to properties file
*
* @param
* @param curIndex
*/
public synchronized void saveDataHostIndex(String dataHost, int curIndex) {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
FileOutputStream fileOut = null;
try {
String oldIndex = dnIndexProperties.getProperty(dataHost);
String newIndex = String.valueOf(curIndex);
if (newIndex.equals(oldIndex)) {
return;
}
dnIndexProperties.setProperty(dataHost, newIndex);
LOGGER.info("save DataHost index " + dataHost + " cur index " + curIndex);
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
fileOut = new FileOutputStream(file);
dnIndexProperties.store(fileOut, "update");
if(isUseZkSwitch()) {
// save to zk
try {
dnindexLock.acquire(30,TimeUnit.SECONDS) ;
String path = ZKUtils.getZKBasePath() + "bindata/dnindex.properties";
CuratorFramework zk = ZKUtils.getConnection();
if(zk.checkExists().forPath(path)==null) {
zk.create().creatingParentsIfNeeded().forPath(path, Files.toByteArray(file));
} else{
byte[] data= zk.getData().forPath(path);
ByteArrayOutputStream out=new ByteArrayOutputStream();
Properties properties=new Properties();
properties.load(new ByteArrayInputStream(data));
if(!String.valueOf(curIndex).equals(properties.getProperty(dataHost))) {
properties.setProperty(dataHost, String.valueOf(curIndex));
properties.store(out, "update");
zk.setData().forPath(path, out.toByteArray());
}
}
}finally {
dnindexLock.release();
}
}
} catch (Exception e) {
LOGGER.warn("saveDataNodeIndex err:", e);
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
}
}
}
}
private boolean isUseZk(){
String loadZk=ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_FLAG);
return "true".equalsIgnoreCase(loadZk) ;
}
private boolean isUseZkSwitch()
{
MycatConfig mycatConfig=config;
boolean isUseZkSwitch= mycatConfig.getSystem().isUseZKSwitch();
String loadZk=ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_FLAG);
return (isUseZkSwitch&&"true".equalsIgnoreCase(loadZk)) ;
}
public RouteService getRouterService() {
return routerService;
}
public CacheService getCacheService() {
return cacheService;
}
public NameableExecutor getBusinessExecutor() {
return businessExecutor;
}
public RouteService getRouterservice() {
return routerService;
}
public NIOProcessor nextProcessor() {
int i = ++nextProcessor;
if (i >= processors.length) {
i = nextProcessor = 0;
}
return processors[i];
}
public NIOProcessor[] getProcessors() {
return processors;
}
public SocketConnector getConnector() {
return connector;
}
public SQLRecorder getSqlRecorder() {
return sqlRecorder;
}
public long getStartupTime() {
return startupTime;
}
public boolean isOnline() {
return isOnline.get();
}
public void offline() {
isOnline.set(false);
}
public void online() {
isOnline.set(true);
}
// 系统时间定时更新任务
private Runnable updateTime() {
return new Runnable() {
@Override
public void run() {
TimeUtil.update();
}
};
}
// 处理器定时检查任务
private Runnable processorCheck() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (NIOProcessor p : processors) {
p.checkBackendCons();
}
} catch (Exception e) {
LOGGER.warn("checkBackendCons caught err:" + e);
}
}
});
timerExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (NIOProcessor p : processors) {
p.checkFrontCons();
}
} catch (Exception e) {
LOGGER.warn("checkFrontCons caught err:" + e);
}
}
});
}
};
}
// 数据节点定时连接空闲超时检查任务
private Runnable dataNodeConHeartBeatCheck(final long heartPeriod) {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
Map<String, PhysicalDBPool> nodes = config.getDataHosts();
for (PhysicalDBPool node : nodes.values()) {
node.heartbeatCheck(heartPeriod);
}
/*
Map<String, PhysicalDBPool> _nodes = config.getBackupDataHosts();
if (_nodes != null) {
for (PhysicalDBPool node : _nodes.values()) {
node.heartbeatCheck(heartPeriod);
}
}*/
}
});
}
};
}
// 数据节点定时心跳任务
private Runnable dataNodeHeartbeat() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
Map<String, PhysicalDBPool> nodes = config.getDataHosts();
for (PhysicalDBPool node : nodes.values()) {
node.doHeartbeat();
}
}
});
}
};
}
//定时清理保存SqlStat中的数据
private Runnable recycleSqlStat(){
return new Runnable() {
@Override
public void run() {
Map<String, UserStat> statMap = UserStatAnalyzer.getInstance().getUserStatMap();
for (UserStat userStat : statMap.values()) {
userStat.getSqlLastStat().recycle();
userStat.getSqlRecorder().recycle();
userStat.getSqlHigh().recycle();
userStat.getSqlLargeRowStat().recycle();
}
}
};
}
//定时检查不同分片表结构一致性
private Runnable tableStructureCheck(){
return new MySQLTableStructureDetector();
}
// 全局表一致性检查任务
private Runnable glableTableConsistencyCheck() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
GlobalTableUtil.consistencyCheck();
}
});
}
};
}
//XA recovery log check
private void performXARecoveryLog() {
//fetch the recovery log
CoordinatorLogEntry[] coordinatorLogEntries = getCoordinatorLogEntries();
for(int i=0; i<coordinatorLogEntries.length; i++){
CoordinatorLogEntry coordinatorLogEntry = coordinatorLogEntries[i];
boolean needRollback = false;
for(int j=0; j<coordinatorLogEntry.participants.length; j++) {
ParticipantLogEntry participantLogEntry = coordinatorLogEntry.participants[j];
if (participantLogEntry.txState == TxState.TX_PREPARED_STATE){
needRollback = true;
break;
}
}
if(needRollback){
for(int j=0; j<coordinatorLogEntry.participants.length; j++){
ParticipantLogEntry participantLogEntry = coordinatorLogEntry.participants[j];
//XA rollback
String xacmd = "XA ROLLBACK "+ coordinatorLogEntry.id +';';
OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler( new String[0], new XARollbackCallback());
outloop:
for (SchemaConfig schema : MycatServer.getInstance().getConfig().getSchemas().values()) {
for (TableConfig table : schema.getTables().values()) {
for (String dataNode : table.getDataNodes()) {
PhysicalDBNode dn = MycatServer.getInstance().getConfig().getDataNodes().get(dataNode);
if (dn.getDbPool().getSource().getConfig().getIp().equals(participantLogEntry.uri)
&& dn.getDatabase().equals(participantLogEntry.resourceName)) {
//XA STATE ROLLBACK
participantLogEntry.txState = TxState.TX_ROLLBACKED_STATE;
SQLJob sqlJob = new SQLJob(xacmd, dn.getDatabase(), resultHandler, dn.getDbPool().getSource());
sqlJob.run();
LOGGER.debug(String.format("[XA ROLLBACK] [%s] Host:[%s] schema:[%s]", xacmd, dn.getName(), dn.getDatabase()));
break outloop;
}
}
}
}
}
}
}
//init into in memory cached
for(int i=0;i<coordinatorLogEntries.length;i++){
MultiNodeCoordinator.inMemoryRepository.put(coordinatorLogEntries[i].id,coordinatorLogEntries[i]);
}
//discard the recovery log
MultiNodeCoordinator.fileRepository.writeCheckpoint(MultiNodeCoordinator.inMemoryRepository.getAllCoordinatorLogEntries());
}
/** covert the collection to array **/
private CoordinatorLogEntry[] getCoordinatorLogEntries(){
Collection<CoordinatorLogEntry> allCoordinatorLogEntries = fileRepository.getAllCoordinatorLogEntries();
if(allCoordinatorLogEntries == null){return new CoordinatorLogEntry[0];}
if(allCoordinatorLogEntries.size()==0){return new CoordinatorLogEntry[0];}
return allCoordinatorLogEntries.toArray(new CoordinatorLogEntry[allCoordinatorLogEntries.size()]);
}
public NameableExecutor getSequenceExecutor() {
return sequenceExecutor;
}
//huangyiming add
public DirectByteBufferPool getDirectByteBufferPool() {
return (DirectByteBufferPool)bufferPool;
}
public boolean isAIO() {
return aio;
}
public ListeningExecutorService getListeningExecutorService() {
return listeningExecutorService;
}
public static void main(String[] args) throws Exception {
String path = ZKUtils.getZKBasePath() + "bindata";
CuratorFramework zk = ZKUtils.getConnection();
if(zk.checkExists().forPath(path)==null);
byte[] data= zk.getData().forPath(path);
System.out.println(data.length);
}
}
| jim0409/Mycat-Server | src/main/java/io/mycat/MycatServer.java |
45,314 | package org.telegram.messenger;
import org.telegram.SQLite.SQLiteCursor;
import org.telegram.SQLite.SQLiteDatabase;
import org.telegram.SQLite.SQLitePreparedStatement;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLRPC;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
public class DatabaseMigrationHelper {
public static int migrate(MessagesStorage messagesStorage, int version) throws Exception {
SQLiteDatabase database = messagesStorage.getDatabase();
if (version < 4) {
database.executeFast("CREATE TABLE IF NOT EXISTS user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS read_state_out_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS ttl_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS date_idx_messages;").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS download_queue(uid INTEGER, type INTEGER, date INTEGER, data BLOB, PRIMARY KEY (uid, type));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS type_date_idx_download_queue ON download_queue(type, date);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS dialog_settings(did INTEGER PRIMARY KEY, flags INTEGER);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_idx_dialogs ON dialogs(unread_count);").stepThis().dispose();
database.executeFast("UPDATE messages SET send_state = 2 WHERE mid < 0 AND send_state = 1").stepThis().dispose();
messagesStorage.fixNotificationSettings();
database.executeFast("PRAGMA user_version = 4").stepThis().dispose();
version = 4;
}
if (version == 4) {
database.executeFast("CREATE TABLE IF NOT EXISTS enc_tasks_v2(mid INTEGER PRIMARY KEY, date INTEGER)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v2 ON enc_tasks_v2(date);").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor = database.queryFinalized("SELECT date, data FROM enc_tasks WHERE 1");
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)");
if (cursor.next()) {
int date = cursor.intValue(0);
NativeByteBuffer data = cursor.byteBufferValue(1);
if (data != null) {
int length = data.limit();
for (int a = 0; a < length / 4; a++) {
state.requery();
state.bindInteger(1, data.readInt32(false));
state.bindInteger(2, date);
state.step();
}
data.reuse();
}
}
state.dispose();
cursor.dispose();
database.commitTransaction();
database.executeFast("DROP INDEX IF EXISTS date_idx_enc_tasks;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS enc_tasks;").stepThis().dispose();
database.executeFast("ALTER TABLE messages ADD COLUMN media INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 6").stepThis().dispose();
version = 6;
}
if (version == 6) {
database.executeFast("CREATE TABLE IF NOT EXISTS messages_seq(mid INTEGER PRIMARY KEY, seq_in INTEGER, seq_out INTEGER);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS seq_idx_messages_seq ON messages_seq(seq_in, seq_out);").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN layer INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN seq_in INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN seq_out INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 7").stepThis().dispose();
version = 7;
}
if (version == 7 || version == 8 || version == 9) {
database.executeFast("ALTER TABLE enc_chats ADD COLUMN use_count INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN exchange_id INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN key_date INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN fprint INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN fauthkey BLOB default NULL").stepThis().dispose();
database.executeFast("ALTER TABLE enc_chats ADD COLUMN khash BLOB default NULL").stepThis().dispose();
database.executeFast("PRAGMA user_version = 10").stepThis().dispose();
version = 10;
}
if (version == 10) {
database.executeFast("CREATE TABLE IF NOT EXISTS web_recent_v3(id TEXT, type INTEGER, image_url TEXT, thumb_url TEXT, local_url TEXT, width INTEGER, height INTEGER, size INTEGER, date INTEGER, PRIMARY KEY (id, type));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 11").stepThis().dispose();
version = 11;
}
if (version == 11 || version == 12) {
database.executeFast("DROP INDEX IF EXISTS uid_mid_idx_media;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS mid_idx_media;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_date_mid_idx_media;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS media;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS media_counts;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS media_v2(mid INTEGER PRIMARY KEY, uid INTEGER, date INTEGER, type INTEGER, data BLOB)").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS media_counts_v2(uid INTEGER, type INTEGER, count INTEGER, PRIMARY KEY(uid, type))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media ON media_v2(uid, mid, type, date);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS keyvalue(id TEXT PRIMARY KEY, value TEXT)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 13").stepThis().dispose();
version = 13;
}
if (version == 13) {
database.executeFast("ALTER TABLE messages ADD COLUMN replydata BLOB default NULL").stepThis().dispose();
database.executeFast("PRAGMA user_version = 14").stepThis().dispose();
version = 14;
}
if (version == 14) {
database.executeFast("CREATE TABLE IF NOT EXISTS hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 15").stepThis().dispose();
version = 15;
}
if (version == 15) {
database.executeFast("CREATE TABLE IF NOT EXISTS webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 16").stepThis().dispose();
version = 16;
}
if (version == 16) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN inbox_max INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN outbox_max INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 17").stepThis().dispose();
version = 17;
}
if (version == 17) {
database.executeFast("PRAGMA user_version = 18").stepThis().dispose();
version = 18;
}
if (version == 18) {
database.executeFast("DROP TABLE IF EXISTS stickers;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS stickers_v2(id INTEGER PRIMARY KEY, data BLOB, date INTEGER, hash INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 19").stepThis().dispose();
version = 19;
}
if (version == 19) {
database.executeFast("CREATE TABLE IF NOT EXISTS bot_keyboard(uid INTEGER PRIMARY KEY, mid INTEGER, info BLOB)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid ON bot_keyboard(mid);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 20").stepThis().dispose();
version = 20;
}
if (version == 20) {
database.executeFast("CREATE TABLE search_recent(did INTEGER PRIMARY KEY, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 21").stepThis().dispose();
version = 21;
}
if (version == 21) {
database.executeFast("CREATE TABLE IF NOT EXISTS chat_settings_v2(uid INTEGER PRIMARY KEY, info BLOB)").stepThis().dispose();
SQLiteCursor cursor = database.queryFinalized("SELECT uid, participants FROM chat_settings WHERE uid < 0");
SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?)");
while (cursor.next()) {
long chatId = cursor.intValue(0);
NativeByteBuffer data = cursor.byteBufferValue(1);
if (data != null) {
TLRPC.ChatParticipants participants = TLRPC.ChatParticipants.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
if (participants != null) {
TLRPC.TL_chatFull chatFull = new TLRPC.TL_chatFull();
chatFull.id = chatId;
chatFull.chat_photo = new TLRPC.TL_photoEmpty();
chatFull.notify_settings = new TLRPC.TL_peerNotifySettingsEmpty_layer77();
chatFull.exported_invite = null;
chatFull.participants = participants;
NativeByteBuffer data2 = new NativeByteBuffer(chatFull.getObjectSize());
chatFull.serializeToStream(data2);
state.requery();
state.bindLong(1, chatId);
state.bindByteBuffer(2, data2);
state.step();
data2.reuse();
}
}
}
state.dispose();
cursor.dispose();
database.executeFast("DROP TABLE IF EXISTS chat_settings;").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN last_mid_i INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN unread_count_i INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN pts INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN date_i INTEGER default 0").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_i_idx_dialogs ON dialogs(last_mid_i);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_i_idx_dialogs ON dialogs(unread_count_i);").stepThis().dispose();
database.executeFast("ALTER TABLE messages ADD COLUMN imp INTEGER default 0").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS messages_holes(uid INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, start));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_messages_holes ON messages_holes(uid, end);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 22").stepThis().dispose();
version = 22;
}
if (version == 22) {
database.executeFast("CREATE TABLE IF NOT EXISTS media_holes_v2(uid INTEGER, type INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, type, start));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_media_holes_v2 ON media_holes_v2(uid, type, end);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 23").stepThis().dispose();
version = 23;
}
if (version == 23 || version == 24) {
database.executeFast("DELETE FROM media_holes_v2 WHERE uid != 0 AND type >= 0 AND start IN (0, 1)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 25").stepThis().dispose();
version = 25;
}
if (version == 25 || version == 26) {
database.executeFast("CREATE TABLE IF NOT EXISTS channel_users_v2(did INTEGER, uid INTEGER, date INTEGER, data BLOB, PRIMARY KEY(did, uid))").stepThis().dispose();
database.executeFast("PRAGMA user_version = 27").stepThis().dispose();
version = 27;
}
if (version == 27) {
database.executeFast("ALTER TABLE web_recent_v3 ADD COLUMN document BLOB default NULL").stepThis().dispose();
database.executeFast("PRAGMA user_version = 28").stepThis().dispose();
version = 28;
}
if (version == 28 || version == 29) {
database.executeFast("DELETE FROM sent_files_v2 WHERE 1").stepThis().dispose();
database.executeFast("DELETE FROM download_queue WHERE 1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 30").stepThis().dispose();
version = 30;
}
if (version == 30) {
database.executeFast("ALTER TABLE chat_settings_v2 ADD COLUMN pinned INTEGER default 0").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS chat_settings_pinned_idx ON chat_settings_v2(uid, pinned) WHERE pinned != 0;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS users_data(uid INTEGER PRIMARY KEY, about TEXT)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 31").stepThis().dispose();
version = 31;
}
if (version == 31) {
database.executeFast("DROP TABLE IF EXISTS bot_recent;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS chat_hints(did INTEGER, type INTEGER, rating REAL, date INTEGER, PRIMARY KEY(did, type))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS chat_hints_rating_idx ON chat_hints(rating);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 32").stepThis().dispose();
version = 32;
}
if (version == 32) {
database.executeFast("DROP INDEX IF EXISTS uid_mid_idx_imp_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_date_mid_imp_idx_messages;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 33").stepThis().dispose();
version = 33;
}
if (version == 33) {
database.executeFast("CREATE TABLE IF NOT EXISTS pending_tasks(id INTEGER PRIMARY KEY, data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 34").stepThis().dispose();
version = 34;
}
if (version == 34) {
database.executeFast("CREATE TABLE IF NOT EXISTS stickers_featured(id INTEGER PRIMARY KEY, data BLOB, unread BLOB, date INTEGER, hash INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 35").stepThis().dispose();
version = 35;
}
if (version == 35) {
database.executeFast("CREATE TABLE IF NOT EXISTS requested_holes(uid INTEGER, seq_out_start INTEGER, seq_out_end INTEGER, PRIMARY KEY (uid, seq_out_start, seq_out_end));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 36").stepThis().dispose();
version = 36;
}
if (version == 36) {
database.executeFast("ALTER TABLE enc_chats ADD COLUMN in_seq_no INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 37").stepThis().dispose();
version = 37;
}
if (version == 37) {
database.executeFast("CREATE TABLE IF NOT EXISTS botcache(id TEXT PRIMARY KEY, date INTEGER, data BLOB)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS botcache_date_idx ON botcache(date);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 38").stepThis().dispose();
version = 38;
}
if (version == 38) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN pinned INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 39").stepThis().dispose();
version = 39;
}
if (version == 39) {
database.executeFast("ALTER TABLE enc_chats ADD COLUMN admin_id INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 40").stepThis().dispose();
version = 40;
}
if (version == 40) {
messagesStorage.fixNotificationSettings();
database.executeFast("PRAGMA user_version = 41").stepThis().dispose();
version = 41;
}
if (version == 41) {
database.executeFast("ALTER TABLE messages ADD COLUMN mention INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE user_contacts_v6 ADD COLUMN imported INTEGER default 0").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages ON messages(uid, mention, read_state);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 42").stepThis().dispose();
version = 42;
}
if (version == 42) {
database.executeFast("CREATE TABLE IF NOT EXISTS sharing_locations(uid INTEGER PRIMARY KEY, mid INTEGER, date INTEGER, period INTEGER, message BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 43").stepThis().dispose();
version = 43;
}
if (version == 43) {
database.executeFast("PRAGMA user_version = 44").stepThis().dispose();
version = 44;
}
if (version == 44) {
database.executeFast("CREATE TABLE IF NOT EXISTS user_contacts_v7(key TEXT PRIMARY KEY, uid INTEGER, fname TEXT, sname TEXT, imported INTEGER)").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS user_phones_v7(key TEXT, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (key, phone))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v7(sphone, deleted);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 45").stepThis().dispose();
version = 45;
}
if (version == 45) {
database.executeFast("ALTER TABLE enc_chats ADD COLUMN mtproto_seq INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 46").stepThis().dispose();
version = 46;
}
if (version == 46) {
database.executeFast("DELETE FROM botcache WHERE 1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 47").stepThis().dispose();
version = 47;
}
if (version == 47) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN flags INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 48").stepThis().dispose();
version = 48;
}
if (version == 48) {
database.executeFast("CREATE TABLE IF NOT EXISTS unread_push_messages(uid INTEGER, mid INTEGER, random INTEGER, date INTEGER, data BLOB, fm TEXT, name TEXT, uname TEXT, flags INTEGER, PRIMARY KEY(uid, mid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_date ON unread_push_messages(date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_random ON unread_push_messages(random);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 49").stepThis().dispose();
version = 49;
}
if (version == 49) {
database.executeFast("CREATE TABLE IF NOT EXISTS user_settings(uid INTEGER PRIMARY KEY, info BLOB, pinned INTEGER)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS user_settings_pinned_idx ON user_settings(uid, pinned) WHERE pinned != 0;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 50").stepThis().dispose();
version = 50;
}
if (version == 50) {
database.executeFast("DELETE FROM sent_files_v2 WHERE 1").stepThis().dispose();
database.executeFast("ALTER TABLE sent_files_v2 ADD COLUMN parent TEXT").stepThis().dispose();
database.executeFast("DELETE FROM download_queue WHERE 1").stepThis().dispose();
database.executeFast("ALTER TABLE download_queue ADD COLUMN parent TEXT").stepThis().dispose();
database.executeFast("PRAGMA user_version = 51").stepThis().dispose();
version = 51;
}
if (version == 51) {
database.executeFast("ALTER TABLE media_counts_v2 ADD COLUMN old INTEGER").stepThis().dispose();
database.executeFast("PRAGMA user_version = 52").stepThis().dispose();
version = 52;
}
if (version == 52) {
database.executeFast("CREATE TABLE IF NOT EXISTS polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS polls_id ON polls_v2(id);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 53").stepThis().dispose();
version = 53;
}
if (version == 53) {
database.executeFast("ALTER TABLE chat_settings_v2 ADD COLUMN online INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 54").stepThis().dispose();
version = 54;
}
if (version == 54) {
database.executeFast("DROP TABLE IF EXISTS wallpapers;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 55").stepThis().dispose();
version = 55;
}
if (version == 55) {
database.executeFast("CREATE TABLE IF NOT EXISTS wallpapers2(uid INTEGER PRIMARY KEY, data BLOB, num INTEGER)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS wallpapers_num ON wallpapers2(num);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 56").stepThis().dispose();
version = 56;
}
if (version == 56 || version == 57) {
database.executeFast("CREATE TABLE IF NOT EXISTS emoji_keywords_v2(lang TEXT, keyword TEXT, emoji TEXT, PRIMARY KEY(lang, keyword, emoji));").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS emoji_keywords_info_v2(lang TEXT PRIMARY KEY, alias TEXT, version INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 58").stepThis().dispose();
version = 58;
}
if (version == 58) {
database.executeFast("CREATE INDEX IF NOT EXISTS emoji_keywords_v2_keyword ON emoji_keywords_v2(keyword);").stepThis().dispose();
database.executeFast("ALTER TABLE emoji_keywords_info_v2 ADD COLUMN date INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 59").stepThis().dispose();
version = 59;
}
if (version == 59) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN folder_id INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN data BLOB default NULL").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS folder_id_idx_dialogs ON dialogs(folder_id);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 60").stepThis().dispose();
version = 60;
}
if (version == 60) {
database.executeFast("DROP TABLE IF EXISTS channel_admins;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS blocked_users;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 61").stepThis().dispose();
version = 61;
}
if (version == 61) {
database.executeFast("DROP INDEX IF EXISTS send_state_idx_messages;").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages2 ON messages(mid, send_state, date);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 62").stepThis().dispose();
version = 62;
}
if (version == 62) {
database.executeFast("CREATE TABLE IF NOT EXISTS scheduled_messages(mid INTEGER PRIMARY KEY, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages ON scheduled_messages(mid, send_state, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages ON scheduled_messages(uid, date);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 63").stepThis().dispose();
version = 63;
}
if (version == 63) {
database.executeFast("DELETE FROM download_queue WHERE 1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 64").stepThis().dispose();
version = 64;
}
if (version == 64) {
database.executeFast("CREATE TABLE IF NOT EXISTS dialog_filter(id INTEGER PRIMARY KEY, ord INTEGER, unread_count INTEGER, flags INTEGER, title TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS dialog_filter_ep(id INTEGER, peer INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose();
database.executeFast("PRAGMA user_version = 65").stepThis().dispose();
version = 65;
}
if (version == 65) {
database.executeFast("CREATE INDEX IF NOT EXISTS flags_idx_dialogs ON dialogs(flags);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 66").stepThis().dispose();
version = 66;
}
if (version == 66) {
database.executeFast("CREATE TABLE dialog_filter_pin_v2(id INTEGER, peer INTEGER, pin INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose();
database.executeFast("PRAGMA user_version = 67").stepThis().dispose();
version = 67;
}
if (version == 67) {
database.executeFast("CREATE TABLE IF NOT EXISTS stickers_dice(emoji TEXT PRIMARY KEY, data BLOB, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 68").stepThis().dispose();
version = 68;
}
if (version == 68) {
messagesStorage.executeNoException("ALTER TABLE messages ADD COLUMN forwards INTEGER default 0");
database.executeFast("PRAGMA user_version = 69").stepThis().dispose();
version = 69;
}
if (version == 69) {
messagesStorage.executeNoException("ALTER TABLE messages ADD COLUMN replies_data BLOB default NULL");
messagesStorage.executeNoException("ALTER TABLE messages ADD COLUMN thread_reply_id INTEGER default 0");
database.executeFast("PRAGMA user_version = 70").stepThis().dispose();
version = 70;
}
if (version == 70) {
database.executeFast("CREATE TABLE IF NOT EXISTS chat_pinned_v2(uid INTEGER, mid INTEGER, data BLOB, PRIMARY KEY (uid, mid));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 71").stepThis().dispose();
version = 71;
}
if (version == 71) {
messagesStorage.executeNoException("ALTER TABLE sharing_locations ADD COLUMN proximity INTEGER default 0");
database.executeFast("PRAGMA user_version = 72").stepThis().dispose();
version = 72;
}
if (version == 72) {
database.executeFast("CREATE TABLE IF NOT EXISTS chat_pinned_count(uid INTEGER PRIMARY KEY, count INTEGER, end INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 73").stepThis().dispose();
version = 73;
}
if (version == 73) {
messagesStorage.executeNoException("ALTER TABLE chat_settings_v2 ADD COLUMN inviter INTEGER default 0");
database.executeFast("PRAGMA user_version = 74").stepThis().dispose();
version = 74;
}
if (version == 74) {
database.executeFast("CREATE TABLE IF NOT EXISTS shortcut_widget(id INTEGER, did INTEGER, ord INTEGER, PRIMARY KEY (id, did));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS shortcut_widget_did ON shortcut_widget(did);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 75").stepThis().dispose();
version = 75;
}
if (version == 75) {
messagesStorage.executeNoException("ALTER TABLE chat_settings_v2 ADD COLUMN links INTEGER default 0");
database.executeFast("PRAGMA user_version = 76").stepThis().dispose();
version = 76;
}
if (version == 76) {
messagesStorage.executeNoException("ALTER TABLE enc_tasks_v2 ADD COLUMN media INTEGER default -1");
database.executeFast("PRAGMA user_version = 77").stepThis().dispose();
version = 77;
}
if (version == 77) {
database.executeFast("DROP TABLE IF EXISTS channel_admins_v2;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS channel_admins_v3(did INTEGER, uid INTEGER, data BLOB, PRIMARY KEY(did, uid))").stepThis().dispose();
database.executeFast("PRAGMA user_version = 78").stepThis().dispose();
version = 78;
}
if (version == 78) {
database.executeFast("DROP TABLE IF EXISTS bot_info;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS bot_info_v2(uid INTEGER, dialogId INTEGER, info BLOB, PRIMARY KEY(uid, dialogId))").stepThis().dispose();
database.executeFast("PRAGMA user_version = 79").stepThis().dispose();
version = 79;
}
if (version == 79) {
database.executeFast("CREATE TABLE IF NOT EXISTS enc_tasks_v3(mid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, media))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v3 ON enc_tasks_v3(date);").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor = database.queryFinalized("SELECT mid, date, media FROM enc_tasks_v2 WHERE 1");
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)");
if (cursor.next()) {
long mid = cursor.longValue(0);
int date = cursor.intValue(1);
int media = cursor.intValue(2);
state.requery();
state.bindLong(1, mid);
state.bindInteger(2, date);
state.bindInteger(3, media);
state.step();
}
state.dispose();
cursor.dispose();
database.commitTransaction();
database.executeFast("DROP INDEX IF EXISTS date_idx_enc_tasks_v2;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS enc_tasks_v2;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 80").stepThis().dispose();
version = 80;
}
if (version == 80) {
database.executeFast("CREATE TABLE IF NOT EXISTS scheduled_messages_v2(mid INTEGER, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, send_state, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages_v2 ON scheduled_messages_v2(uid, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid_v2 ON bot_keyboard(mid, uid);").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS bot_keyboard_idx_mid;").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor;
try {
cursor = database.queryFinalized("SELECT mid, uid, send_state, date, data, ttl, replydata FROM scheduled_messages_v2 WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?)");
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(4);
if (data == null) {
continue;
}
int mid = cursor.intValue(0);
long uid = cursor.longValue(1);
int sendState = cursor.intValue(2);
int date = cursor.intValue(3);
int ttl = cursor.intValue(5);
NativeByteBuffer replydata = cursor.byteBufferValue(6);
statement.requery();
statement.bindInteger(1, mid);
statement.bindLong(2, uid);
statement.bindInteger(3, sendState);
statement.bindByteBuffer(4, data);
statement.bindInteger(5, date);
statement.bindInteger(6, ttl);
if (replydata != null) {
statement.bindByteBuffer(7, replydata);
} else {
statement.bindNull(7);
}
statement.step();
if (replydata != null) {
replydata.reuse();
}
data.reuse();
}
cursor.dispose();
statement.dispose();
}
database.executeFast("DROP INDEX IF EXISTS send_state_idx_scheduled_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_date_idx_scheduled_messages;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS scheduled_messages;").stepThis().dispose();
database.commitTransaction();
database.executeFast("PRAGMA user_version = 81").stepThis().dispose();
version = 81;
}
if (version == 81) {
database.executeFast("CREATE TABLE IF NOT EXISTS media_v3(mid INTEGER, uid INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_v3 ON media_v3(uid, mid, type, date);").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor;
try {
cursor = database.queryFinalized("SELECT mid, uid, date, type, data FROM media_v2 WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)");
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(4);
if (data == null) {
continue;
}
int mid = cursor.intValue(0);
long uid = cursor.longValue(1);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
int date = cursor.intValue(2);
int type = cursor.intValue(3);
statement.requery();
statement.bindInteger(1, mid);
statement.bindLong(2, uid);
statement.bindInteger(3, date);
statement.bindInteger(4, type);
statement.bindByteBuffer(5, data);
statement.step();
data.reuse();
}
cursor.dispose();
statement.dispose();
}
database.executeFast("DROP INDEX IF EXISTS uid_mid_type_date_idx_media;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS media_v2;").stepThis().dispose();
database.commitTransaction();
database.executeFast("PRAGMA user_version = 82").stepThis().dispose();
version = 82;
}
if (version == 82) {
database.executeFast("CREATE TABLE IF NOT EXISTS randoms_v2(random_id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (random_id, mid, uid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms_v2 ON randoms_v2(mid, uid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS enc_tasks_v4(mid INTEGER, uid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, uid, media))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v4 ON enc_tasks_v4(date);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS polls_id_v2 ON polls_v2(id);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS webpage_pending_v2(id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (id, mid, uid));").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor;
try {
cursor = database.queryFinalized("SELECT r.random_id, r.mid, m.uid FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)");
while (cursor.next()) {
long randomId = cursor.longValue(0);
int mid = cursor.intValue(1);
long uid = cursor.longValue(2);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
statement.requery();
statement.bindLong(1, randomId);
statement.bindInteger(2, mid);
statement.bindLong(3, uid);
statement.step();
}
cursor.dispose();
statement.dispose();
}
try {
cursor = database.queryFinalized("SELECT p.mid, m.uid, p.id FROM polls as p INNER JOIN messages as m ON p.mid = m.mid WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)");
while (cursor.next()) {
int mid = cursor.intValue(0);
long uid = cursor.longValue(1);
long id = cursor.longValue(2);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
statement.requery();
statement.bindInteger(1, mid);
statement.bindLong(2, uid);
statement.bindLong(3, id);
statement.step();
}
cursor.dispose();
statement.dispose();
}
try {
cursor = database.queryFinalized("SELECT wp.id, wp.mid, m.uid FROM webpage_pending as wp INNER JOIN messages as m ON wp.mid = m.mid WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)");
while (cursor.next()) {
long id = cursor.longValue(0);
int mid = cursor.intValue(1);
long uid = cursor.longValue(2);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
statement.requery();
statement.bindLong(1, id);
statement.bindInteger(2, mid);
statement.bindLong(3, uid);
statement.step();
}
cursor.dispose();
statement.dispose();
}
try {
cursor = database.queryFinalized("SELECT et.mid, m.uid, et.date, et.media FROM enc_tasks_v3 as et INNER JOIN messages as m ON et.mid = m.mid WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)");
while (cursor.next()) {
int mid = cursor.intValue(0);
long uid = cursor.longValue(1);
int date = cursor.intValue(2);
int media = cursor.intValue(3);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
statement.requery();
statement.bindInteger(1, mid);
statement.bindLong(2, uid);
statement.bindInteger(3, date);
statement.bindInteger(4, media);
statement.step();
}
cursor.dispose();
statement.dispose();
}
database.executeFast("DROP INDEX IF EXISTS mid_idx_randoms;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS randoms;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS date_idx_enc_tasks_v3;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS enc_tasks_v3;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS polls_id;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS polls;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS webpage_pending;").stepThis().dispose();
database.commitTransaction();
database.executeFast("PRAGMA user_version = 83").stepThis().dispose();
version = 83;
}
if (version == 83) {
database.executeFast("CREATE TABLE IF NOT EXISTS messages_v2(mid INTEGER, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER, is_channel INTEGER, PRIMARY KEY(mid, uid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_v2 ON messages_v2(uid, mid, read_state, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages_v2 ON messages_v2(uid, date, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages_v2 ON messages_v2(mid, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages_v2 ON messages_v2(uid, out, read_state, ttl, date, send_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages_v2 ON messages_v2(mid, send_state, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_v2 ON messages_v2(uid, mention, read_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS is_channel_idx_messages_v2 ON messages_v2(mid, is_channel);").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor;
try {
cursor = database.queryFinalized("SELECT mid, uid, read_state, send_state, date, data, out, ttl, media, replydata, imp, mention, forwards, replies_data, thread_reply_id FROM messages WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
int num = 0;
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(5);
if (data == null) {
continue;
}
num++;
long mid = cursor.intValue(0);
long uid = cursor.longValue(1);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
int readState = cursor.intValue(2);
int sendState = cursor.intValue(3);
int date = cursor.intValue(4);
int out = cursor.intValue(6);
int ttl = cursor.intValue(7);
int media = cursor.intValue(8);
NativeByteBuffer replydata = cursor.byteBufferValue(9);
int imp = cursor.intValue(10);
int mention = cursor.intValue(11);
int forwards = cursor.intValue(12);
NativeByteBuffer repliesdata = cursor.byteBufferValue(13);
int thread_reply_id = cursor.intValue(14);
int channelId = (int) (uid >> 32);
if (ttl < 0) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
if (message != null) {
message.readAttachPath(data, messagesStorage.getUserConfig().clientUserId);
if (message.params == null) {
message.params = new HashMap<>();
message.params.put("fwd_peer", "" + ttl);
}
data.reuse();
data = new NativeByteBuffer(message.getObjectSize());
message.serializeToStream(data);
}
ttl = 0;
}
statement.requery();
statement.bindInteger(1, (int) mid);
statement.bindLong(2, uid);
statement.bindInteger(3, readState);
statement.bindInteger(4, sendState);
statement.bindInteger(5, date);
statement.bindByteBuffer(6, data);
statement.bindInteger(7, out);
statement.bindInteger(8, ttl);
statement.bindInteger(9, media);
if (replydata != null) {
statement.bindByteBuffer(10, replydata);
} else {
statement.bindNull(10);
}
statement.bindInteger(11, imp);
statement.bindInteger(12, mention);
statement.bindInteger(13, forwards);
if (repliesdata != null) {
statement.bindByteBuffer(14, repliesdata);
} else {
statement.bindNull(14);
}
statement.bindInteger(15, thread_reply_id);
statement.bindInteger(16, channelId > 0 ? 1 : 0);
statement.step();
if (replydata != null) {
replydata.reuse();
}
if (repliesdata != null) {
repliesdata.reuse();
}
data.reuse();
}
cursor.dispose();
statement.dispose();
}
ArrayList<Integer> secretChatsToUpdate = null;
ArrayList<Integer> foldersToUpdate = null;
cursor = database.queryFinalized("SELECT did, last_mid, last_mid_i FROM dialogs WHERE 1");
SQLitePreparedStatement statement4 = database.executeFast("UPDATE dialogs SET last_mid = ?, last_mid_i = ? WHERE did = ?");
while (cursor.next()) {
long did = cursor.longValue(0);
int lowerId = (int) did;
int highId = (int) (did >> 32);
if (lowerId == 0) {
if (secretChatsToUpdate == null) {
secretChatsToUpdate = new ArrayList<>();
}
secretChatsToUpdate.add(highId);
} else if (highId == 2) {
if (foldersToUpdate == null) {
foldersToUpdate = new ArrayList<>();
}
foldersToUpdate.add(lowerId);
}
statement4.requery();
statement4.bindInteger(1, cursor.intValue(1));
statement4.bindInteger(2, cursor.intValue(2));
statement4.bindLong(3, did);
statement4.step();
}
statement4.dispose();
cursor.dispose();
cursor = database.queryFinalized("SELECT uid, mid FROM unread_push_messages WHERE 1");
statement4 = database.executeFast("UPDATE unread_push_messages SET mid = ? WHERE uid = ? AND mid = ?");
while (cursor.next()) {
long did = cursor.longValue(0);
int mid = cursor.intValue(1);
statement4.requery();
statement4.bindInteger(1, mid);
statement4.bindLong(2, did);
statement4.bindInteger(3, mid);
statement4.step();
}
statement4.dispose();
cursor.dispose();
if (secretChatsToUpdate != null) {
SQLitePreparedStatement statement = database.executeFast("UPDATE dialogs SET did = ? WHERE did = ?");
SQLitePreparedStatement statement2 = database.executeFast("UPDATE dialog_filter_pin_v2 SET peer = ? WHERE peer = ?");
SQLitePreparedStatement statement3 = database.executeFast("UPDATE dialog_filter_ep SET peer = ? WHERE peer = ?");
for (int a = 0, N = secretChatsToUpdate.size(); a < N; a++) {
int sid = secretChatsToUpdate.get(a);
long newId = DialogObject.makeEncryptedDialogId(sid);
long oldId = ((long) sid) << 32;
statement.requery();
statement.bindLong(1, newId);
statement.bindLong(2, oldId);
statement.step();
statement2.requery();
statement2.bindLong(1, newId);
statement2.bindLong(2, oldId);
statement2.step();
statement3.requery();
statement3.bindLong(1, newId);
statement3.bindLong(2, oldId);
statement3.step();
}
statement.dispose();
statement2.dispose();
statement3.dispose();
}
if (foldersToUpdate != null) {
SQLitePreparedStatement statement = database.executeFast("UPDATE dialogs SET did = ? WHERE did = ?");
for (int a = 0, N = foldersToUpdate.size(); a < N; a++) {
int fid = foldersToUpdate.get(a);
long newId = DialogObject.makeFolderDialogId(fid);
long oldId = (((long) 2) << 32) | fid;
statement.requery();
statement.bindLong(1, newId);
statement.bindLong(2, oldId);
statement.step();
}
statement.dispose();
}
database.executeFast("DROP INDEX IF EXISTS uid_mid_read_out_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_date_mid_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS mid_out_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS task_idx_messages;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS send_state_idx_messages2;").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_mention_idx_messages;").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS messages;").stepThis().dispose();
database.commitTransaction();
database.executeFast("PRAGMA user_version = 84").stepThis().dispose();
version = 84;
}
if (version == 84) {
database.executeFast("CREATE TABLE IF NOT EXISTS media_v4(mid INTEGER, uid INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid, type))").stepThis().dispose();
database.beginTransaction();
SQLiteCursor cursor;
try {
cursor = database.queryFinalized("SELECT mid, uid, date, type, data FROM media_v3 WHERE 1");
} catch (Exception e) {
cursor = null;
FileLog.e(e);
}
if (cursor != null) {
SQLitePreparedStatement statement = database.executeFast("REPLACE INTO media_v4 VALUES(?, ?, ?, ?, ?)");
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(4);
if (data == null) {
continue;
}
int mid = cursor.intValue(0);
long uid = cursor.longValue(1);
int lowerId = (int) uid;
if (lowerId == 0) {
int highId = (int) (uid >> 32);
uid = DialogObject.makeEncryptedDialogId(highId);
}
int date = cursor.intValue(2);
int type = cursor.intValue(3);
statement.requery();
statement.bindInteger(1, mid);
statement.bindLong(2, uid);
statement.bindInteger(3, date);
statement.bindInteger(4, type);
statement.bindByteBuffer(5, data);
statement.step();
data.reuse();
}
cursor.dispose();
statement.dispose();
}
database.commitTransaction();
database.executeFast("DROP TABLE IF EXISTS media_v3;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 85").stepThis().dispose();
version = 85;
}
if (version == 85) {
messagesStorage.executeNoException("ALTER TABLE messages_v2 ADD COLUMN reply_to_message_id INTEGER default 0");
messagesStorage.executeNoException("ALTER TABLE scheduled_messages_v2 ADD COLUMN reply_to_message_id INTEGER default 0");
database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_messages_v2 ON messages_v2(mid, reply_to_message_id);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, reply_to_message_id);").stepThis().dispose();
messagesStorage.executeNoException("UPDATE messages_v2 SET replydata = NULL");
messagesStorage.executeNoException("UPDATE scheduled_messages_v2 SET replydata = NULL");
database.executeFast("PRAGMA user_version = 86").stepThis().dispose();
version = 86;
}
if (version == 86) {
database.executeFast("CREATE TABLE IF NOT EXISTS reactions(data BLOB, hash INTEGER, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 87").stepThis().dispose();
version = 87;
}
if (version == 87) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN unread_reactions INTEGER default 0").stepThis().dispose();
database.executeFast("CREATE TABLE reaction_mentions(message_id INTEGER PRIMARY KEY, state INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 88").stepThis().dispose();
version = 88;
}
if (version == 88 || version == 89) {
database.executeFast("DROP TABLE IF EXISTS reaction_mentions;").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS reaction_mentions(message_id INTEGER, state INTEGER, dialog_id INTEGER, PRIMARY KEY(dialog_id, message_id));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS reaction_mentions_did ON reaction_mentions(dialog_id);").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_mid_type_date_idx_media_v3").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_v4 ON media_v4(uid, mid, type, date);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 90").stepThis().dispose();
version = 90;
}
if (version == 90 || version == 91) {
database.executeFast("DROP TABLE IF EXISTS downloading_documents;").stepThis().dispose();
database.executeFast("CREATE TABLE downloading_documents(data BLOB, hash INTEGER, id INTEGER, state INTEGER, date INTEGER, PRIMARY KEY(hash, id));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 92").stepThis().dispose();
version = 92;
}
if (version == 92) {
database.executeFast("CREATE TABLE IF NOT EXISTS attach_menu_bots(data BLOB, hash INTEGER, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 93").stepThis().dispose();
version = 95;
}
if (version == 95 || version == 93) {
messagesStorage.executeNoException("ALTER TABLE messages_v2 ADD COLUMN custom_params BLOB default NULL");
database.executeFast("PRAGMA user_version = 96").stepThis().dispose();
version = 96;
}
// skip 94, 95. private beta db rollback
if (version == 96) {
database.executeFast("CREATE TABLE IF NOT EXISTS premium_promo(data BLOB, date INTEGER);").stepThis().dispose();
database.executeFast("UPDATE stickers_v2 SET date = 0");
database.executeFast("PRAGMA user_version = 97").stepThis().dispose();
version = 97;
}
if (version == 97) {
database.executeFast("DROP TABLE IF EXISTS stickers_featured;").stepThis().dispose();
database.executeFast("CREATE TABLE stickers_featured(id INTEGER PRIMARY KEY, data BLOB, unread BLOB, date INTEGER, hash INTEGER, premium INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 98").stepThis().dispose();
version = 98;
}
if (version == 98) {
database.executeFast("CREATE TABLE animated_emoji(document_id INTEGER PRIMARY KEY, data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 99").stepThis().dispose();
version = 99;
}
if (version == 99) {
database.executeFast("ALTER TABLE stickers_featured ADD COLUMN emoji INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 100").stepThis().dispose();
version = 100;
}
if (version == 100) {
database.executeFast("CREATE TABLE emoji_statuses(data BLOB, type INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 101").stepThis().dispose();
version = 101;
}
if (version == 101) {
database.executeFast("ALTER TABLE messages_v2 ADD COLUMN group_id INTEGER default NULL").stepThis().dispose();
database.executeFast("ALTER TABLE dialogs ADD COLUMN last_mid_group INTEGER default NULL").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_groupid_messages_v2 ON messages_v2(uid, mid, group_id);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 102").stepThis().dispose();
version = 102;
}
if (version == 102) {
database.executeFast("CREATE TABLE messages_holes_topics(uid INTEGER, topic_id INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, topic_id, start));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_messages_holes ON messages_holes_topics(uid, topic_id, end);").stepThis().dispose();
database.executeFast("CREATE TABLE messages_topics(mid INTEGER, uid INTEGER, topic_id INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER, is_channel INTEGER, reply_to_message_id INTEGER, custom_params BLOB, PRIMARY KEY(mid, topic_id, uid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_topics ON messages_topics(uid, mid, read_state, out);").stepThis().dispose();//move to topic id
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages_topics ON messages_topics(uid, date, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages_topics ON messages_topics(mid, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages_topics ON messages_topics(uid, out, read_state, ttl, date, send_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages_topics ON messages_topics(mid, send_state, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_topics ON messages_topics(uid, mention, read_state);").stepThis().dispose();//move to uid, topic_id, mentiin_read_state
database.executeFast("CREATE INDEX IF NOT EXISTS is_channel_idx_messages_topics ON messages_topics(mid, is_channel);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_messages_topics ON messages_topics(mid, reply_to_message_id);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_uid_messages_topics ON messages_topics(mid, uid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_uid_topic_id_messages_topics ON messages_topics(mid, topic_id, uid);").stepThis().dispose();
database.executeFast("CREATE TABLE media_topics(mid INTEGER, uid INTEGER, topic_id INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid, topic_id, type))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_topics ON media_topics(uid, topic_id, mid, type, date);").stepThis().dispose();
database.executeFast("CREATE TABLE media_holes_topics(uid INTEGER, topic_id INTEGER, type INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, topic_id, type, start));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_media_holes_topics ON media_holes_topics(uid, topic_id, type, end);").stepThis().dispose();
database.executeFast("CREATE TABLE topics(did INTEGER, topic_id INTEGER, data BLOB, top_message INTEGER, topic_message BLOB, unread_count INTEGER, max_read_id INTEGER, unread_mentions INTEGER, unread_reactions INTEGER, PRIMARY KEY(did, topic_id));").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS did_top_message_topics ON topics(did, top_message);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 103").stepThis().dispose();
version = 103;
}
if (version == 103) {
database.executeFast("CREATE TABLE IF NOT EXISTS media_counts_topics(uid INTEGER, topic_id INTEGER, type INTEGER, count INTEGER, old INTEGER, PRIMARY KEY(uid, topic_id, type))").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS reaction_mentions_topics(message_id INTEGER, state INTEGER, dialog_id INTEGER, topic_id INTEGER, PRIMARY KEY(message_id, dialog_id, topic_id))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS reaction_mentions_topics_did ON reaction_mentions_topics(dialog_id, topic_id);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 104").stepThis().dispose();
version = 104;
}
if (version == 104) {
database.executeFast("ALTER TABLE topics ADD COLUMN read_outbox INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 105").stepThis().dispose();
version = 105;
}
if (version == 105) {
database.executeFast("ALTER TABLE topics ADD COLUMN pinned INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 106").stepThis().dispose();
version = 106;
}
if (version == 106) {
database.executeFast("DROP INDEX IF EXISTS uid_mid_read_out_idx_messages_topics").stepThis().dispose();
database.executeFast("DROP INDEX IF EXISTS uid_mention_idx_messages_topics").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_topics ON messages_topics(uid, topic_id, mid, read_state, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_topics ON messages_topics(uid, topic_id, mention, read_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_topic_id_messages_topics ON messages_topics(uid, topic_id);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_topic_id_date_mid_messages_topics ON messages_topics(uid, topic_id, date, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_topic_id_mid_messages_topics ON messages_topics(uid, topic_id, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS did_topics ON topics(did);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 107").stepThis().dispose();
version = 107;
}
if (version == 107) {
database.executeFast("ALTER TABLE topics ADD COLUMN total_messages_count INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 108").stepThis().dispose();
version = 108;
}
if (version == 108) {
database.executeFast("ALTER TABLE topics ADD COLUMN hidden INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 109").stepThis().dispose();
version = 109;
}
if (version == 109) {
database.executeFast("ALTER TABLE dialogs ADD COLUMN ttl_period INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 110").stepThis().dispose();
version = 110;
}
if (version == 110) {
database.executeFast("CREATE TABLE stickersets(id INTEGER PRIMATE KEY, data BLOB, hash INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 111").stepThis().dispose();
version = 111;
}
if (version == 111) {
database.executeFast("CREATE TABLE emoji_groups(type INTEGER PRIMARY KEY, data BLOB)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 112").stepThis().dispose();
version = 112;
}
if (version == 112) {
database.executeFast("CREATE TABLE app_config(data BLOB)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 113").stepThis().dispose();
version = 113;
}
if (version == 113) {
//fix issue when database file was deleted
//just reload dialogs
messagesStorage.reset();
database.executeFast("PRAGMA user_version = 114").stepThis().dispose();
version = 114;
}
if (version == 114) {
database.executeFast("CREATE TABLE bot_keyboard_topics(uid INTEGER, tid INTEGER, mid INTEGER, info BLOB, PRIMARY KEY(uid, tid))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_topics_idx_mid_v2 ON bot_keyboard_topics(mid, uid, tid);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 115").stepThis().dispose();
version = 115;
}
if (version == 115) {
database.executeFast("CREATE INDEX IF NOT EXISTS idx_to_reply_messages_v2 ON messages_v2(reply_to_message_id, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS idx_to_reply_scheduled_messages_v2 ON scheduled_messages_v2(reply_to_message_id, mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS idx_to_reply_messages_topics ON messages_topics(reply_to_message_id, mid);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 117").stepThis().dispose();
version = 117;
}
if (version == 116 || version == 117 || version == 118) {
database.executeFast("DROP TABLE IF EXISTS stories").stepThis().dispose();
database.executeFast("DROP TABLE IF EXISTS stories_counter").stepThis().dispose();
database.executeFast("CREATE TABLE stories (dialog_id INTEGER, story_id INTEGER, data BLOB, local_path TEXT, local_thumb_path TEXT, PRIMARY KEY (dialog_id, story_id));").stepThis().dispose();
database.executeFast("CREATE TABLE stories_counter (dialog_id INTEGER PRIMARY KEY, count INTEGER, max_read INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 119").stepThis().dispose();
messagesStorage.getMessagesController().getStoriesController().cleanup();
version = 119;
}
if (version == 119) {
database.executeFast("ALTER TABLE messages_v2 ADD COLUMN reply_to_story_id INTEGER default 0").stepThis().dispose();
database.executeFast("ALTER TABLE messages_topics ADD COLUMN reply_to_story_id INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 120").stepThis().dispose();
version = 120;
}
if (version == 120) {
database.executeFast("CREATE TABLE profile_stories (dialog_id INTEGER, story_id INTEGER, data BLOB, PRIMARY KEY(dialog_id, story_id));").stepThis().dispose();
database.executeFast("CREATE TABLE archived_stories (story_id INTEGER PRIMARY KEY, data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 121").stepThis().dispose();
version = 121;
}
if (version == 121) {
database.executeFast("CREATE TABLE story_drafts (id INTEGER PRIMARY KEY, date INTEGER, data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 122").stepThis().dispose();
version = 122;
}
if (version == 122) {
database.executeFast("ALTER TABLE chat_settings_v2 ADD COLUMN participants_count INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 123").stepThis().dispose();
version = 123;
}
if (version == 123) {
database.executeFast("CREATE TABLE story_pushes (uid INTEGER PRIMARY KEY, minId INTEGER, maxId INTEGER, date INTEGER, localName TEXT);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 124").stepThis().dispose();
version = 124;
}
if (version == 124) {
database.executeFast("DROP TABLE IF EXISTS story_pushes;").stepThis().dispose();
database.executeFast("CREATE TABLE story_pushes (uid INTEGER, sid INTEGER, date INTEGER, localName TEXT, PRIMARY KEY(uid, sid));").stepThis().dispose();
database.executeFast("PRAGMA user_version = 125").stepThis().dispose();
version = 125;
}
if (version == 125) {
database.executeFast("ALTER TABLE story_pushes ADD COLUMN flags INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 126").stepThis().dispose();
version = 126;
}
if (version == 126) {
database.executeFast("ALTER TABLE story_pushes ADD COLUMN expire_date INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 127").stepThis().dispose();
version = 127;
}
if (version == 127) {
database.executeFast("ALTER TABLE stories ADD COLUMN custom_params BLOB default NULL").stepThis().dispose();
database.executeFast("PRAGMA user_version = 128").stepThis().dispose();
version = 128;
}
if (version == 128) {
database.executeFast("ALTER TABLE story_drafts ADD COLUMN type INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 129").stepThis().dispose();
version = 129;
}
if (version == 129) {
database.executeFast("CREATE INDEX IF NOT EXISTS stickers_featured_emoji_index ON stickers_featured(emoji);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 130").stepThis().dispose();
version = 130;
}
if (version == 130) {
database.executeFast("DROP TABLE archived_stories").stepThis().dispose();
database.executeFast("ALTER TABLE profile_stories ADD COLUMN type INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 131").stepThis().dispose();
version = 131;
}
if (version == 131) {
database.executeFast("ALTER TABLE stories DROP COLUMN local_path").stepThis().dispose();
database.executeFast("ALTER TABLE stories DROP COLUMN local_thumb_path").stepThis().dispose();
database.executeFast("PRAGMA user_version = 132").stepThis().dispose();
version = 132;
}
if (version == 132) {
database.executeFast("CREATE TABLE unconfirmed_auth (data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 133").stepThis().dispose();
version = 133;
}
if (version == 133) {
database.executeFast("ALTER TABLE unread_push_messages ADD COLUMN topicId INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 134").stepThis().dispose();
version = 134;
}
if (version == 134) {
database.executeFast("DROP TABLE user_photos").stepThis().dispose();
database.executeFast("CREATE TABLE dialog_photos(uid INTEGER, id INTEGER, num INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose();
database.executeFast("CREATE TABLE dialog_photos_count(uid INTEGER PRIMARY KEY, count INTEGER)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 135").stepThis().dispose();
version = 135;
}
if (version == 135) {
// database.executeFast("DROP TABLE stickersets").stepThis().dispose();
database.executeFast("CREATE TABLE stickersets2(id INTEGER PRIMATE KEY, data BLOB, hash INTEGER, date INTEGER);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS stickersets2_id_index ON stickersets2(id);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 136").stepThis().dispose();
version = 136;
}
if (version == 136) {
database.executeFast("CREATE TABLE saved_dialogs(did INTEGER PRIMARY KEY, date INTEGER, last_mid INTEGER, pinned INTEGER, flags INTEGER, folder_id INTEGER, last_mid_group INTEGER, count INTEGER)").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_dialogs ON saved_dialogs(date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_idx_dialogs ON saved_dialogs(last_mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS folder_id_idx_dialogs ON saved_dialogs(folder_id);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS flags_idx_dialogs ON saved_dialogs(flags);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 137").stepThis().dispose();
version = 137;
}
if (version == 137) {
database.executeFast("ALTER TABLE unread_push_messages ADD COLUMN is_reaction INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 138").stepThis().dispose();
version = 138;
}
if (version == 138 || version == 139 || version == 140 || version == 141) {
database.executeFast("DROP TABLE IF EXISTS tag_message_id;").stepThis().dispose();
database.executeFast("CREATE TABLE tag_message_id(mid INTEGER, topic_id INTEGER, tag INTEGER, text TEXT);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS tag_idx_tag_message_id ON tag_message_id(tag);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS tag_text_idx_tag_message_id ON tag_message_id(tag, text);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS tag_topic_idx_tag_message_id ON tag_message_id(topic_id, tag);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS tag_topic_text_idx_tag_message_id ON tag_message_id(topic_id, tag, text);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 142").stepThis().dispose();
version = 142;
}
if (version == 142) {
database.executeFast("DROP TABLE IF EXISTS saved_reaction_tags;").stepThis().dispose();
database.executeFast("CREATE TABLE saved_reaction_tags (topic_id INTEGER PRIMARY KEY, data BLOB);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 143").stepThis().dispose();
version = 143;
}
if (version == 143) {
database.executeFast("ALTER TABLE dialog_filter ADD COLUMN color INTEGER default -1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 144").stepThis().dispose();
version = 144;
}
if (version == 144) {
// database.executeFast("CREATE TABLE business_messages(mid INTEGER, type INTEGER, topic_id INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, reply_to_message_id INTEGER, PRIMARY KEY(mid, type))").stepThis().dispose();
// database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_business_messages ON business_messages(mid, send_state, date);").stepThis().dispose();
// database.executeFast("CREATE INDEX IF NOT EXISTS type_topic_date_idx_business_messages ON business_messages(type, topic_id, date);").stepThis().dispose();
// database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_business_messages ON business_messages(mid, reply_to_message_id);").stepThis().dispose();
// database.executeFast("CREATE INDEX IF NOT EXISTS idx_to_reply_business_messages ON business_messages(reply_to_message_id, mid);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 145").stepThis().dispose();
version = 145;
}
if (version == 145) {
database.executeFast("CREATE TABLE business_replies(topic_id INTEGER PRIMARY KEY, name TEXT, order_value INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 146").stepThis().dispose();
version = 146;
}
if (version == 146) {
database.executeFast("CREATE TABLE quick_replies_messages(mid INTEGER, topic_id INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, reply_to_message_id INTEGER, PRIMARY KEY(mid, topic_id))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_quick_replies_messages ON quick_replies_messages(mid, send_state, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS topic_date_idx_quick_replies_messages ON quick_replies_messages(topic_id, date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS reply_to_idx_quick_replies_messages ON quick_replies_messages(mid, reply_to_message_id);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS idx_to_reply_quick_replies_messages ON quick_replies_messages(reply_to_message_id, mid);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 147").stepThis().dispose();
version = 147;
}
if (version == 147) {
database.executeFast("ALTER TABLE business_replies ADD COLUMN count INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 148").stepThis().dispose();
version = 148;
}
if (version == 148) {
database.executeFast("ALTER TABLE topics ADD COLUMN edit_date INTEGER default 0").stepThis().dispose();
database.executeFast("PRAGMA user_version = 149").stepThis().dispose();
version = 149;
}
if (version == 149) {
database.executeFast("ALTER TABLE stickersets2 ADD COLUMN short_name TEXT;").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS stickersets2_id_short_name ON stickersets2(id, short_name);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 150").stepThis().dispose();
version = 150;
}
if (version == 150) {
database.executeFast("CREATE TABLE business_links(data BLOB, order_value INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 151").stepThis().dispose();
version = 151;
}
if (version == 151) {
database.executeFast("ALTER TABLE profile_stories ADD COLUMN seen INTEGER default 0;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 152").stepThis().dispose();
version = 152;
}
if (version == 152) {
database.executeFast("ALTER TABLE profile_stories ADD COLUMN pin INTEGER default 0;").stepThis().dispose();
database.executeFast("PRAGMA user_version = 153").stepThis().dispose();
version = 153;
}
return version;
}
public static boolean recoverDatabase(File oldDatabaseFile, File oldDatabaseWall, File oldDatabaseShm, int currentAccount) {
File filesDir = ApplicationLoader.getFilesDirFixed();
filesDir = new File(filesDir, "recover_database_" + currentAccount + "/");
filesDir.mkdirs();
File cacheFile = new File(filesDir, "cache4.db");
File walCacheFile = new File(filesDir, "cache4.db-wal");
File shmCacheFile = new File(filesDir, "cache4.db-shm");
try {
cacheFile.delete();
walCacheFile.delete();
shmCacheFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
SQLiteDatabase newDatabase = null;
long time = 0;
ArrayList<Long> encryptedDialogs = new ArrayList<>();
ArrayList<Long> dialogs = new ArrayList<>();
boolean recovered = true;
FileLog.d("start recover database");
try {
time = System.currentTimeMillis();
newDatabase = new SQLiteDatabase(cacheFile.getPath());
newDatabase.executeFast("PRAGMA secure_delete = ON").stepThis().dispose();
newDatabase.executeFast("PRAGMA temp_store = MEMORY").stepThis().dispose();
newDatabase.executeFast("PRAGMA journal_mode = WAL").stepThis().dispose();
newDatabase.executeFast("PRAGMA journal_size_limit = 10485760").stepThis().dispose();
MessagesStorage.createTables(newDatabase);
newDatabase.executeFast("ATTACH DATABASE \"" + oldDatabaseFile.getAbsolutePath() + "\" AS old;").stepThis().dispose();
int version = newDatabase.executeInt("PRAGMA old.user_version");
if (version != MessagesStorage.LAST_DB_VERSION) {
FileLog.e("can't restore database from version " + version);
return false;
}
HashSet<String> excludeTables = new HashSet<>();
excludeTables.add("messages_v2");
excludeTables.add("messages_holes");
excludeTables.add("scheduled_messages_v2");
excludeTables.add("media_holes_v2");
excludeTables.add("media_v4");
excludeTables.add("messages_holes_topics");
excludeTables.add("messages_topics");
excludeTables.add("media_topics");
excludeTables.add("media_holes_topics");
excludeTables.add("topics");
excludeTables.add("media_counts_v2");
excludeTables.add("media_counts_topics");
excludeTables.add("dialogs");
excludeTables.add("dialog_filter");
excludeTables.add("dialog_filter_ep");
excludeTables.add("dialog_filter_pin_v2");
//restore whole tables
for (int i = 0; i < MessagesStorage.DATABASE_TABLES.length; i++) {
String tableName = MessagesStorage.DATABASE_TABLES[i];
if (excludeTables.contains(tableName)) {
continue;
}
newDatabase.executeFast(String.format(Locale.US, "INSERT OR IGNORE INTO %s SELECT * FROM old.%s;", tableName, tableName)).stepThis().dispose();
}
SQLiteCursor cursor = newDatabase.queryFinalized("SELECT did FROM old.dialogs");
while (cursor.next()) {
long did = cursor.longValue(0);
if (DialogObject.isEncryptedDialog(did)) {
encryptedDialogs.add(did);
} else {
dialogs.add(did);
}
}
cursor.dispose();
//restore only secret chats
for (int i = 0; i < encryptedDialogs.size(); i++) {
long dialogId = encryptedDialogs.get(i);
newDatabase.executeFast(String.format(Locale.US, "INSERT OR IGNORE INTO messages_v2 SELECT * FROM old.messages_v2 WHERE uid = %d;", dialogId)).stepThis().dispose();
newDatabase.executeFast(String.format(Locale.US, "INSERT OR IGNORE INTO messages_holes SELECT * FROM old.messages_holes WHERE uid = %d;", dialogId)).stepThis().dispose();
newDatabase.executeFast(String.format(Locale.US, "INSERT OR IGNORE INTO media_holes_v2 SELECT * FROM old.media_holes_v2 WHERE uid = %d;", dialogId)).stepThis().dispose();
newDatabase.executeFast(String.format(Locale.US, "INSERT OR IGNORE INTO media_v4 SELECT * FROM old.media_v4 WHERE uid = %d;", dialogId)).stepThis().dispose();
}
SQLitePreparedStatement state5 = newDatabase.executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
SQLitePreparedStatement state6 = newDatabase.executeFast("REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");
for (int a = 0; a < dialogs.size(); a++) {
Long did = dialogs.get(a);
cursor = newDatabase.queryFinalized("SELECT last_mid_i, last_mid FROM old.dialogs WHERE did = " + did);
if (cursor.next()) {
long last_mid_i = cursor.longValue(0);
long last_mid = cursor.longValue(1);
newDatabase.executeFast("INSERT OR IGNORE INTO messages_v2 SELECT * FROM old.messages_v2 WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")").stepThis().dispose();
MessagesStorage.createFirstHoles(did, state5, state6, (int) last_mid, 0);
}
cursor.dispose();
cursor = null;
}
state5.dispose();
state6.dispose();
newDatabase.executeFast("DETACH DATABASE old;").stepThis().dispose();
newDatabase.close();
} catch (Exception e) {
FileLog.e(e);
recovered = false;
}
if (!recovered) {
return false;
}
try {
oldDatabaseFile.delete();
oldDatabaseWall.delete();
oldDatabaseShm.delete();
AndroidUtilities.copyFile(cacheFile, oldDatabaseFile);
AndroidUtilities.copyFile(walCacheFile, oldDatabaseWall);
AndroidUtilities.copyFile(shmCacheFile, oldDatabaseShm);
cacheFile.delete();
walCacheFile.delete();
shmCacheFile.delete();
} catch (IOException e) {
e.printStackTrace();
return false;
}
FileLog.d("database recovered time " + (System.currentTimeMillis() - time));
return true;
}
}
| DrKLO/Telegram | TMessagesProj/src/main/java/org/telegram/messenger/DatabaseMigrationHelper.java |
45,315 | package me.chanjar.weixin.common.error;
import com.google.common.collect.Maps;
import lombok.Getter;
import java.util.Map;
/**
* <pre>
* 微信开放平台全局返回码.
* 参考文档:<a href="https://developers.weixin.qq.com/doc/oplatform/Return_codes/Return_code_descriptions_new.html">开放平台全局返回码</a>
* </pre>
*
* @author Lam Jerry
*/
@Getter
public enum WxOpenErrorMsgEnum {
/**
* 系统繁忙,此时请开发者稍候再试 system error
*/
CODE_1(-1, "系统繁忙,此时请开发者稍候再试"),
/**
* 请求成功 ok
*/
CODE_0(0, "请求成功"),
/**
* POST参数非法
*/
CODE_1003(1003, "POST参数非法"),
/**
* 商品id不存在
*/
CODE_20002(20002, "商品id不存在"),
/**
* 获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口 invalid credential, access_token is invalid or not latest
*/
CODE_40001(40001, "获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口"),
/**
* 不合法的凭证类型 invalid grant_type
*/
CODE_40002(40002, "不合法的凭证类型"),
/**
* 不合法的 OpenID ,请开发者确认 OpenID (该用户)是否已关注公众号,或是否是其他公众号的 OpenID invalid openid
*/
CODE_40003(40003, "不合法的 OpenID ,请开发者确认 OpenID (该用户)是否已关注公众号,或是否是其他公众号的 OpenID"),
/**
* 不合法的媒体文件类型 invalid media type
*/
CODE_40004(40004, "不合法的媒体文件类型"),
/**
* 上传素材文件格式不对 invalid file type
*/
CODE_40005(40005, "上传素材文件格式不对"),
/**
* 上传素材文件大小超出限制 invalid meida size
*/
CODE_40006(40006, "上传素材文件大小超出限制"),
/**
* 不合法的媒体文件 id invalid media_id
*/
CODE_40007(40007, "不合法的媒体文件 id"),
/**
* 不合法的消息类型 invalid message type
*/
CODE_40008(40008, "不合法的消息类型"),
/**
* 图片尺寸太大 invalid image size
*/
CODE_40009(40009, "图片尺寸太大"),
/**
* 不合法的语音文件大小 invalid voice size
*/
CODE_40010(40010, "不合法的语音文件大小"),
/**
* 不合法的视频文件大小 invalid video size
*/
CODE_40011(40011, "不合法的视频文件大小"),
/**
* 不合法的缩略图文件大小 invalid thumb size
*/
CODE_40012(40012, "不合法的缩略图文件大小"),
/**
* 不合法的appid invalid appid
*/
CODE_40013(40013, "不合法的appid"),
/**
* 不合法的 access_token ,请开发者认真比对 access_token 的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口 invalid access_token
*/
CODE_40014(40014, "不合法的 access_token ,请开发者认真比对 access_token 的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口"),
/**
* 不合法的菜单类型 invalid menu type
*/
CODE_40015(40015, "不合法的菜单类型"),
/**
* 不合法的按钮个数 invalid button size
*/
CODE_40016(40016, "不合法的按钮个数"),
/**
* 不合法的按钮类型 invalid button type
*/
CODE_40017(40017, "不合法的按钮类型"),
/**
* 不合法的按钮名字长度 invalid button name size
*/
CODE_40018(40018, "不合法的按钮名字长度"),
/**
* 不合法的按钮 KEY 长度 invalid button key size
*/
CODE_40019(40019, "不合法的按钮 KEY 长度"),
/**
* 不合法的按钮 URL 长度 invalid button url size
*/
CODE_40020(40020, "不合法的按钮 URL 长度"),
/**
* 不合法的菜单版本号 invalid menu version
*/
CODE_40021(40021, "不合法的菜单版本号"),
/**
* 不合法的子菜单级数 invalid sub_menu level
*/
CODE_40022(40022, "不合法的子菜单级数"),
/**
* 不合法的子菜单按钮个数 invalid sub button size
*/
CODE_40023(40023, "不合法的子菜单按钮个数"),
/**
* 不合法的子菜单按钮类型 invalid sub button type
*/
CODE_40024(40024, "不合法的子菜单按钮类型"),
/**
* 不合法的子菜单按钮名字长度 invalid sub button name size
*/
CODE_40025(40025, "不合法的子菜单按钮名字长度"),
/**
* 不合法的子菜单按钮 KEY 长度 invalid sub button key size
*/
CODE_40026(40026, "不合法的子菜单按钮 KEY 长度"),
/**
* 不合法的子菜单按钮 URL 长度 invalid sub button url size
*/
CODE_40027(40027, "不合法的子菜单按钮 URL 长度"),
/**
* 不合法的自定义菜单使用用户 invalid menu api user
*/
CODE_40028(40028, "不合法的自定义菜单使用用户"),
/**
* 无效的 oauth_code invalid code
*/
CODE_40029(40029, "无效的 oauth_code"),
/**
* 不合法的 refresh_token invalid refresh_token
*/
CODE_40030(40030, "不合法的 refresh_token"),
/**
* 不合法的 openid 列表 invalid openid list
*/
CODE_40031(40031, "不合法的 openid 列表"),
/**
* 不合法的 openid 列表长度 invalid openid list size
*/
CODE_40032(40032, "不合法的 openid 列表长度"),
/**
* 不合法的请求字符,不能包含 \\uxxxx 格式的字符 invalid charset. please check your request, if include \\uxxxx will create fail!
*/
CODE_40033(40033, "不合法的请求字符,不能包含 \\uxxxx 格式的字符"),
/**
* invalid template size
*/
CODE_40034(40034, "invalid template size"),
/**
* 不合法的参数 invalid args size
*/
CODE_40035(40035, "不合法的参数"),
/**
* 不合法的 template_id 长度 invalid template_id size
*/
CODE_40036(40036, "不合法的 template_id 长度"),
/**
* 不合法的 template_id invalid template_id
*/
CODE_40037(40037, "不合法的 template_id"),
/**
* 不合法的请求格式 invalid packaging type
*/
CODE_40038(40038, "不合法的请求格式"),
/**
* 不合法的 URL 长度 invalid url size
*/
CODE_40039(40039, "不合法的 URL 长度"),
/**
* invalid plugin token
*/
CODE_40040(40040, "invalid plugin token"),
/**
* invalid plugin id
*/
CODE_40041(40041, "invalid plugin id"),
/**
* invalid plugin session
*/
CODE_40042(40042, "invalid plugin session"),
/**
* invalid fav type
*/
CODE_40043(40043, "invalid fav type"),
/**
* invalid size in link.title
*/
CODE_40044(40044, "invalid size in link.title"),
/**
* invalid size in link.description
*/
CODE_40045(40045, "invalid size in link.description"),
/**
* invalid size in link.iconurl
*/
CODE_40046(40046, "invalid size in link.iconurl"),
/**
* invalid size in link.url
*/
CODE_40047(40047, "invalid size in link.url"),
/**
* 无效的url invalid url domain
*/
CODE_40048(40048, "无效的url"),
/**
* invalid score report type
*/
CODE_40049(40049, "invalid score report type"),
/**
* 不合法的分组 id invalid timeline type
*/
CODE_40050(40050, "不合法的分组 id"),
/**
* 分组名字不合法 invalid group name
*/
CODE_40051(40051, "分组名字不合法"),
/**
* invalid action name
*/
CODE_40052(40052, "invalid action name"),
/**
* invalid action info, please check document
*/
CODE_40053(40053, "invalid action info, please check document"),
/**
* 不合法的子菜单按钮 url 域名 invalid sub button url domain
*/
CODE_40054(40054, "不合法的子菜单按钮 url 域名"),
/**
* 不合法的菜单按钮 url 域名 invalid button url domain
*/
CODE_40055(40055, "不合法的菜单按钮 url 域名"),
/**
* invalid serial code
*/
CODE_40056(40056, "invalid serial code"),
/**
* invalid tabbar size
*/
CODE_40057(40057, "invalid tabbar size"),
/**
* invalid tabbar name size
*/
CODE_40058(40058, "invalid tabbar name size"),
/**
* invalid msg id
*/
CODE_40059(40059, "invalid msg id"),
/**
* 删除单篇图文时,指定的 article_idx 不合法 invalid article idx
*/
CODE_40060(40060, "删除单篇图文时,指定的 article_idx 不合法"),
/**
* invalid title size
*/
CODE_40062(40062, "invalid title size"),
/**
* invalid message_ext size
*/
CODE_40063(40063, "invalid message_ext size"),
/**
* invalid app type
*/
CODE_40064(40064, "invalid app type"),
/**
* invalid msg status
*/
CODE_40065(40065, "invalid msg status"),
/**
* 不合法的 url ,递交的页面被sitemap标记为拦截 invalid url
*/
CODE_40066(40066, "不合法的 url ,递交的页面被sitemap标记为拦截"),
/**
* invalid tvid
*/
CODE_40067(40067, "invalid tvid"),
/**
* contain mailcious url
*/
CODE_40068(40068, "contain mailcious url"),
/**
* invalid hardware type
*/
CODE_40069(40069, "invalid hardware type"),
/**
* invalid sku info
*/
CODE_40070(40070, "invalid sku info"),
/**
* invalid card type
*/
CODE_40071(40071, "invalid card type"),
/**
* invalid location id
*/
CODE_40072(40072, "invalid location id"),
/**
* invalid card id
*/
CODE_40073(40073, "invalid card id"),
/**
* invalid pay template id
*/
CODE_40074(40074, "invalid pay template id"),
/**
* invalid encrypt code
*/
CODE_40075(40075, "invalid encrypt code"),
/**
* invalid color id
*/
CODE_40076(40076, "invalid color id"),
/**
* invalid score type
*/
CODE_40077(40077, "invalid score type"),
/**
* invalid card status
*/
CODE_40078(40078, "invalid card status"),
/**
* invalid time
*/
CODE_40079(40079, "invalid time"),
/**
* invalid card ext
*/
CODE_40080(40080, "invalid card ext"),
/**
* invalid template_id
*/
CODE_40081(40081, "invalid template_id"),
/**
* invalid banner picture size
*/
CODE_40082(40082, "invalid banner picture size"),
/**
* invalid banner url size
*/
CODE_40083(40083, "invalid banner url size"),
/**
* invalid button desc size
*/
CODE_40084(40084, "invalid button desc size"),
/**
* invalid button url size
*/
CODE_40085(40085, "invalid button url size"),
/**
* invalid sharelink logo size
*/
CODE_40086(40086, "invalid sharelink logo size"),
/**
* invalid sharelink desc size
*/
CODE_40087(40087, "invalid sharelink desc size"),
/**
* invalid sharelink title size
*/
CODE_40088(40088, "invalid sharelink title size"),
/**
* invalid platform id
*/
CODE_40089(40089, "invalid platform id"),
/**
* invalid request source (bad client ip)
*/
CODE_40090(40090, "invalid request source (bad client ip)"),
/**
* invalid component ticket
*/
CODE_40091(40091, "invalid component ticket"),
/**
* invalid remark name
*/
CODE_40092(40092, "invalid remark name"),
/**
* not completely ok, err_item will return location_id=-1,check your required_fields in json.
*/
CODE_40093(40093, "not completely ok, err_item will return location_id=-1,check your required_fields in json."),
/**
* invalid component credential
*/
CODE_40094(40094, "invalid component credential"),
/**
* bad source of caller
*/
CODE_40095(40095, "bad source of caller"),
/**
* invalid biztype
*/
CODE_40096(40096, "invalid biztype"),
/**
* 参数错误 invalid args
*/
CODE_40097(40097, "参数错误"),
/**
* invalid poiid
*/
CODE_40098(40098, "invalid poiid"),
/**
* invalid code, this code has consumed.
*/
CODE_40099(40099, "invalid code, this code has consumed."),
/**
* invalid DateInfo, Make Sure OldDateInfoType==NewDateInfoType && NewBeginTime<=OldBeginTime && OldEndTime<= NewEndTime
*/
CODE_40100(40100, "invalid DateInfo, Make Sure OldDateInfoType==NewDateInfoType && NewBeginTime<=OldBeginTime && OldEndTime<= NewEndTime"),
/**
* missing parameter
*/
CODE_40101(40101, "missing parameter"),
/**
* invalid industry id
*/
CODE_40102(40102, "invalid industry id"),
/**
* invalid industry index
*/
CODE_40103(40103, "invalid industry index"),
/**
* invalid category id
*/
CODE_40104(40104, "invalid category id"),
/**
* invalid view type
*/
CODE_40105(40105, "invalid view type"),
/**
* invalid user name
*/
CODE_40106(40106, "invalid user name"),
/**
* invalid card id! 1,card status must verify ok; 2,this card must have location_id
*/
CODE_40107(40107, "invalid card id! 1,card status must verify ok; 2,this card must have location_id"),
/**
* invalid client version
*/
CODE_40108(40108, "invalid client version"),
/**
* too many code size, must <= 100
*/
CODE_40109(40109, "too many code size, must <= 100"),
/**
* have empty code
*/
CODE_40110(40110, "have empty code"),
/**
* have same code
*/
CODE_40111(40111, "have same code"),
/**
* can not set bind openid
*/
CODE_40112(40112, "can not set bind openid"),
/**
* unsupported file type
*/
CODE_40113(40113, "unsupported file type"),
/**
* invalid index value
*/
CODE_40114(40114, "invalid index value"),
/**
* invalid session from
*/
CODE_40115(40115, "invalid session from"),
/**
* invalid code
*/
CODE_40116(40116, "invalid code"),
/**
* 分组名字不合法 invalid button media_id size
*/
CODE_40117(40117, "分组名字不合法"),
/**
* media_id 大小不合法 invalid sub button media_id size
*/
CODE_40118(40118, "media_id 大小不合法"),
/**
* button 类型错误 invalid use button type
*/
CODE_40119(40119, "button 类型错误"),
/**
* 子 button 类型错误 invalid use sub button type
*/
CODE_40120(40120, "子 button 类型错误"),
/**
* 不合法的 media_id 类型 invalid media type in view_limited
*/
CODE_40121(40121, "不合法的 media_id 类型"),
/**
* invalid card quantity
*/
CODE_40122(40122, "invalid card quantity"),
/**
* invalid task_id
*/
CODE_40123(40123, "invalid task_id"),
/**
* too many custom field!
*/
CODE_40124(40124, "too many custom field!"),
/**
* 不合法的 AppID ,请开发者检查 AppID 的正确性,避免异常字符,注意大小写 invalid appsecret
*/
CODE_40125(40125, "不合法的 AppID ,请开发者检查 AppID 的正确性,避免异常字符,注意大小写"),
/**
* invalid text size
*/
CODE_40126(40126, "invalid text size"),
/**
* invalid user-card status! Hint: the card was given to user, but may be deleted or expired or set unavailable !
*/
CODE_40127(40127, "invalid user-card status! Hint: the card was given to user, but may be deleted or expired or set unavailable !"),
/**
* invalid media id! must be uploaded by api(cgi-bin/material/add_material)
*/
CODE_40128(40128, "invalid media id! must be uploaded by api(cgi-bin/material/add_material)"),
/**
* invalid scene
*/
CODE_40129(40129, "invalid scene"),
/**
* invalid openid list size, at least two openid
*/
CODE_40130(40130, "invalid openid list size, at least two openid"),
/**
* out of limit of ticket
*/
CODE_40131(40131, "out of limit of ticket"),
/**
* 微信号不合法 invalid username
*/
CODE_40132(40132, "微信号不合法"),
/**
* invalid encryt data
*/
CODE_40133(40133, "invalid encryt data"),
/**
* invalid not supply bonus, can not change card_id which supply bonus to be not supply
*/
CODE_40135(40135, "invalid not supply bonus, can not change card_id which supply bonus to be not supply"),
/**
* invalid use DepositCodeMode, make sure sku.quantity>DepositCode.quantity
*/
CODE_40136(40136, "invalid use DepositCodeMode, make sure sku.quantity>DepositCode.quantity"),
/**
* 不支持的图片格式 invalid image format
*/
CODE_40137(40137, "不支持的图片格式"),
/**
* emphasis word can not be first neither remark
*/
CODE_40138(40138, "emphasis word can not be first neither remark"),
/**
* invalid sub merchant id
*/
CODE_40139(40139, "invalid sub merchant id"),
/**
* invalid sub merchant status
*/
CODE_40140(40140, "invalid sub merchant status"),
/**
* invalid image url
*/
CODE_40141(40141, "invalid image url"),
/**
* invalid sharecard parameters
*/
CODE_40142(40142, "invalid sharecard parameters"),
/**
* invalid least cost info, should be 0
*/
CODE_40143(40143, "invalid least cost info, should be 0"),
/**
* 1)maybe share_card_list.num or consume_share_self_num too big; 2)maybe card_id_list also has self-card_id;3)maybe card_id_list has many different card_id;4)maybe both consume_share_self_num and share_card_list.num bigger than 0
*/
CODE_40144(40144, "1)maybe share_card_list.num or consume_share_self_num too big; 2)maybe card_id_list also has self-card_id;3)maybe card_id_list has many different card_id;4)maybe both consume_share_self_num and share_card_list.num bigger than 0"),
/**
* invalid update! Can not both set PayCell and CenterCellInfo(include: center_title, center_sub_title, center_url).
*/
CODE_40145(40145, "invalid update! Can not both set PayCell and CenterCellInfo(include: center_title, center_sub_title, center_url)."),
/**
* invalid openid! card may be marked by other user!
*/
CODE_40146(40146, "invalid openid! card may be marked by other user!"),
/**
* invalid consume! Consume time overranging restricts.
*/
CODE_40147(40147, "invalid consume! Consume time overranging restricts."),
/**
* invalid friends card type
*/
CODE_40148(40148, "invalid friends card type"),
/**
* invalid use time limit
*/
CODE_40149(40149, "invalid use time limit"),
/**
* invalid card parameters
*/
CODE_40150(40150, "invalid card parameters"),
/**
* invalid card info, text/pic hit antispam
*/
CODE_40151(40151, "invalid card info, text/pic hit antispam"),
/**
* invalid group id
*/
CODE_40152(40152, "invalid group id"),
/**
* self consume cell for friends card must need verify code
*/
CODE_40153(40153, "self consume cell for friends card must need verify code"),
/**
* invalid voip parameters
*/
CODE_40154(40154, "invalid voip parameters"),
/**
* 请勿添加其他公众号的主页链接 please don't contain other home page url
*/
CODE_40155(40155, "请勿添加其他公众号的主页链接"),
/**
* invalid face recognize parameters
*/
CODE_40156(40156, "invalid face recognize parameters"),
/**
* invalid picture, has no face
*/
CODE_40157(40157, "invalid picture, has no face"),
/**
* invalid use_custom_code, need be false
*/
CODE_40158(40158, "invalid use_custom_code, need be false"),
/**
* invalid length for path, or the data is not json string
*/
CODE_40159(40159, "invalid length for path, or the data is not json string"),
/**
* invalid image file
*/
CODE_40160(40160, "invalid image file"),
/**
* image file not match
*/
CODE_40161(40161, "image file not match"),
/**
* invalid lifespan
*/
CODE_40162(40162, "invalid lifespan"),
/**
* oauth_code已使用 code been used
*/
CODE_40163(40163, "oauth_code已使用"),
/**
* invalid ip, not in whitelist
*/
CODE_40164(40164, "invalid ip, not in whitelist"),
/**
* invalid weapp pagepath
*/
CODE_40165(40165, "invalid weapp pagepath"),
/**
* invalid weapp appid
*/
CODE_40166(40166, "invalid weapp appid"),
/**
* there is no relation with plugin appid
*/
CODE_40167(40167, "there is no relation with plugin appid"),
/**
* unlinked weapp card
*/
CODE_40168(40168, "unlinked weapp card"),
/**
* invalid length for scene, or the data is not json string
*/
CODE_40169(40169, "invalid length for scene, or the data is not json string"),
/**
* args count exceed count limit
*/
CODE_40170(40170, "args count exceed count limit"),
/**
* product id can not empty and the length cannot exceed 32
*/
CODE_40171(40171, "product id can not empty and the length cannot exceed 32"),
/**
* can not have same product id
*/
CODE_40172(40172, "can not have same product id"),
/**
* there is no bind relation
*/
CODE_40173(40173, "there is no bind relation"),
/**
* not card user
*/
CODE_40174(40174, "not card user"),
/**
* invalid material id
*/
CODE_40175(40175, "invalid material id"),
/**
* invalid template id
*/
CODE_40176(40176, "invalid template id"),
/**
* invalid product id
*/
CODE_40177(40177, "invalid product id"),
/**
* invalid sign
*/
CODE_40178(40178, "invalid sign"),
/**
* Function is adjusted, rules are not allowed to add or update
*/
CODE_40179(40179, "Function is adjusted, rules are not allowed to add or update"),
/**
* invalid client tmp token
*/
CODE_40180(40180, "invalid client tmp token"),
/**
* invalid opengid
*/
CODE_40181(40181, "invalid opengid"),
/**
* invalid pack_id
*/
CODE_40182(40182, "invalid pack_id"),
/**
* invalid product_appid, product_appid should bind with wxa_appid
*/
CODE_40183(40183, "invalid product_appid, product_appid should bind with wxa_appid"),
/**
* invalid url path
*/
CODE_40184(40184, "invalid url path"),
/**
* invalid auth_token, or auth_token is expired
*/
CODE_40185(40185, "invalid auth_token, or auth_token is expired"),
/**
* invalid delegate
*/
CODE_40186(40186, "invalid delegate"),
/**
* invalid ip
*/
CODE_40187(40187, "invalid ip"),
/**
* invalid scope
*/
CODE_40188(40188, "invalid scope"),
/**
* invalid width
*/
CODE_40189(40189, "invalid width"),
/**
* invalid delegate time
*/
CODE_40190(40190, "invalid delegate time"),
/**
* invalid pic_url
*/
CODE_40191(40191, "invalid pic_url"),
/**
* invalid author in news
*/
CODE_40192(40192, "invalid author in news"),
/**
* invalid recommend length
*/
CODE_40193(40193, "invalid recommend length"),
/**
* illegal recommend
*/
CODE_40194(40194, "illegal recommend"),
/**
* invalid show_num
*/
CODE_40195(40195, "invalid show_num"),
/**
* invalid smartmsg media_id
*/
CODE_40196(40196, "invalid smartmsg media_id"),
/**
* invalid smartmsg media num
*/
CODE_40197(40197, "invalid smartmsg media num"),
/**
* invalid default msg article size, must be same as show_num
*/
CODE_40198(40198, "invalid default msg article size, must be same as show_num"),
/**
* 运单 ID 不存在,未查到运单 waybill_id not found
*/
CODE_40199(40199, "运单 ID 不存在,未查到运单"),
/**
* invalid account type
*/
CODE_40200(40200, "invalid account type"),
/**
* invalid check url
*/
CODE_40201(40201, "invalid check url"),
/**
* invalid check action
*/
CODE_40202(40202, "invalid check action"),
/**
* invalid check operator
*/
CODE_40203(40203, "invalid check operator"),
/**
* can not delete wash or rumor article
*/
CODE_40204(40204, "can not delete wash or rumor article"),
/**
* invalid check keywords string
*/
CODE_40205(40205, "invalid check keywords string"),
/**
* invalid check begin stamp
*/
CODE_40206(40206, "invalid check begin stamp"),
/**
* invalid check alive seconds
*/
CODE_40207(40207, "invalid check alive seconds"),
/**
* invalid check notify id
*/
CODE_40208(40208, "invalid check notify id"),
/**
* invalid check notify msg
*/
CODE_40209(40209, "invalid check notify msg"),
/**
* pages 中的path参数不存在或为空 invalid check wxa path
*/
CODE_40210(40210, "pages 中的path参数不存在或为空"),
/**
* invalid scope_data
*/
CODE_40211(40211, "invalid scope_data"),
/**
* paegs 当中存在不合法的query,query格式遵循URL标准,即k1=v1&k2=v2 invalid query
*/
CODE_40212(40212, "paegs 当中存在不合法的query,query格式遵循URL标准,即k1=v1&k2=v2"),
/**
* invalid href tag
*/
CODE_40213(40213, "invalid href tag"),
/**
* invalid href text
*/
CODE_40214(40214, "invalid href text"),
/**
* invalid image count
*/
CODE_40215(40215, "invalid image count"),
/**
* invalid desc
*/
CODE_40216(40216, "invalid desc"),
/**
* invalid video count
*/
CODE_40217(40217, "invalid video count"),
/**
* invalid video id
*/
CODE_40218(40218, "invalid video id"),
/**
* pages不存在或者参数为空 pages is empty
*/
CODE_40219(40219, "pages不存在或者参数为空"),
/**
* data_list is empty
*/
CODE_40220(40220, "data_list is empty"),
/**
* invalid Content-Encoding
*/
CODE_40221(40221, "invalid Content-Encoding"),
/**
* invalid request idc domain
*/
CODE_40222(40222, "invalid request idc domain"),
/**
* empty media cover, please check the media
*/
CODE_40229(40229, "媒体封面为空,请添加媒体封面"),
/**
* 缺少 access_token 参数 access_token missing
*/
CODE_41001(41001, "缺少 access_token 参数"),
/**
* 缺少 appid 参数 appid missing
*/
CODE_41002(41002, "缺少 appid 参数"),
/**
* 缺少 refresh_token 参数 refresh_token missing
*/
CODE_41003(41003, "缺少 refresh_token 参数"),
/**
* 缺少 secret 参数 appsecret missing
*/
CODE_41004(41004, "缺少 secret 参数"),
/**
* 缺少多媒体文件数据,传输素材无视频或图片内容 media data missing
*/
CODE_41005(41005, "缺少多媒体文件数据,传输素材无视频或图片内容"),
/**
* 缺少 media_id 参数 media_id missing
*/
CODE_41006(41006, "缺少 media_id 参数"),
/**
* 缺少子菜单数据 sub_menu data missing
*/
CODE_41007(41007, "缺少子菜单数据"),
/**
* 缺少 oauth code missing code
*/
CODE_41008(41008, "缺少 oauth code"),
/**
* 缺少 openid missing openid
*/
CODE_41009(41009, "缺少 openid"),
/**
* 缺失 url 参数 missing url
*/
CODE_41010(41010, "缺失 url 参数"),
/**
* missing required fields! please check document and request json!
*/
CODE_41011(41011, "missing required fields! please check document and request json!"),
/**
* missing card id
*/
CODE_41012(41012, "missing card id"),
/**
* missing code
*/
CODE_41013(41013, "missing code"),
/**
* missing ticket_class
*/
CODE_41014(41014, "missing ticket_class"),
/**
* missing show_time
*/
CODE_41015(41015, "missing show_time"),
/**
* missing screening_room
*/
CODE_41016(41016, "missing screening_room"),
/**
* missing seat_number
*/
CODE_41017(41017, "missing seat_number"),
/**
* missing component_appid
*/
CODE_41018(41018, "missing component_appid"),
/**
* missing platform_secret
*/
CODE_41019(41019, "missing platform_secret"),
/**
* missing platform_ticket
*/
CODE_41020(41020, "missing platform_ticket"),
/**
* missing component_access_token
*/
CODE_41021(41021, "missing component_access_token"),
/**
* missing "display" field
*/
CODE_41024(41024, "missing \"display\" field"),
/**
* poi_list empty
*/
CODE_41025(41025, "poi_list empty"),
/**
* missing image list info, text maybe empty
*/
CODE_41026(41026, "missing image list info, text maybe empty"),
/**
* missing voip call key
*/
CODE_41027(41027, "missing voip call key"),
/**
* invalid form id
*/
CODE_41028(41028, "invalid form id"),
/**
* form id used count reach limit
*/
CODE_41029(41029, "form id used count reach limit"),
/**
* page路径不正确,需要保证在现网版本小程序中存在,与app.json保持一致 invalid page
*/
CODE_41030(41030, "page路径不正确,需要保证在现网版本小程序中存在,与app.json保持一致"),
/**
* the form id have been blocked!
*/
CODE_41031(41031, "the form id have been blocked!"),
/**
* not allow to send message with submitted form id, for punishment
*/
CODE_41032(41032, "not allow to send message with submitted form id, for punishment"),
/**
* 只允许通过api创建的小程序使用 invaid register type
*/
CODE_41033(41033, "只允许通过api创建的小程序使用"),
/**
* not allow to send message with submitted form id, for punishment
*/
CODE_41034(41034, "not allow to send message with submitted form id, for punishment"),
/**
* not allow to send message with prepay id, for punishment
*/
CODE_41035(41035, "not allow to send message with prepay id, for punishment"),
/**
* appid ad cid
*/
CODE_41036(41036, "appid ad cid"),
/**
* appid ad_mch_appid
*/
CODE_41037(41037, "appid ad_mch_appid"),
/**
* appid pos_type
*/
CODE_41038(41038, "appid pos_type"),
/**
* access_token 超时,请检查 access_token 的有效期,请参考基础支持 - 获取 access_token 中,对 access_token 的详细机制说明 access_token expired
*/
CODE_42001(42001, "access_token 超时,请检查 access_token 的有效期,请参考基础支持 - 获取 access_token 中,对 access_token 的详细机制说明"),
/**
* refresh_token 超时 refresh_token expired
*/
CODE_42002(42002, "refresh_token 超时"),
/**
* oauth_code 超时 code expired
*/
CODE_42003(42003, "oauth_code 超时"),
/**
* plugin token expired
*/
CODE_42004(42004, "plugin token expired"),
/**
* api usage expired
*/
CODE_42005(42005, "api usage expired"),
/**
* component_access_token expired
*/
CODE_42006(42006, "component_access_token expired"),
/**
* 用户修改微信密码, accesstoken 和 refreshtoken 失效,需要重新授权 access_token and refresh_token exception
*/
CODE_42007(42007, "用户修改微信密码, accesstoken 和 refreshtoken 失效,需要重新授权"),
/**
* voip call key expired
*/
CODE_42008(42008, "voip call key expired"),
/**
* client tmp token expired
*/
CODE_42009(42009, "client tmp token expired"),
/**
* 需要 GET 请求 require GET method
*/
CODE_43001(43001, "需要 GET 请求"),
/**
* 需要 POST 请求 require POST method
*/
CODE_43002(43002, "需要 POST 请求"),
/**
* 需要 HTTPS 请求 require https
*/
CODE_43003(43003, "需要 HTTPS 请求"),
/**
* 需要接收者关注 require subscribe
*/
CODE_43004(43004, "需要接收者关注"),
/**
* 需要好友关系 require friend relations
*/
CODE_43005(43005, "需要好友关系"),
/**
* require not block
*/
CODE_43006(43006, "require not block"),
/**
* require bizuser authorize
*/
CODE_43007(43007, "require bizuser authorize"),
/**
* require biz pay auth
*/
CODE_43008(43008, "require biz pay auth"),
/**
* can not use custom code, need authorize
*/
CODE_43009(43009, "can not use custom code, need authorize"),
/**
* can not use balance, need authorize
*/
CODE_43010(43010, "can not use balance, need authorize"),
/**
* can not use bonus, need authorize
*/
CODE_43011(43011, "can not use bonus, need authorize"),
/**
* can not use custom url, need authorize
*/
CODE_43012(43012, "can not use custom url, need authorize"),
/**
* can not use shake card, need authorize
*/
CODE_43013(43013, "can not use shake card, need authorize"),
/**
* require check agent
*/
CODE_43014(43014, "require check agent"),
/**
* require authorize by wechat team to use this function!
*/
CODE_43015(43015, "require authorize by wechat team to use this function!"),
/**
* 小程序未认证 require verify
*/
CODE_43016(43016, "小程序未认证"),
/**
* require location id!
*/
CODE_43017(43017, "require location id!"),
/**
* code has no been mark!
*/
CODE_43018(43018, "code has no been mark!"),
/**
* 需要将接收者从黑名单中移除 require remove blacklist
*/
CODE_43019(43019, "需要将接收者从黑名单中移除"),
/**
* change template too frequently
*/
CODE_43100(43100, "change template too frequently"),
/**
* 用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系 user refuse to accept the msg
*/
CODE_43101(43101, "用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系"),
/**
* the tempalte is not subscriptiontype
*/
CODE_43102(43102, "the tempalte is not subscriptiontype"),
/**
* the api only can cancel the subscription
*/
CODE_43103(43103, "the api only can cancel the subscription"),
/**
* this appid does not have permission
*/
CODE_43104(43104, "this appid does not have permission"),
/**
* news has no binding relation with template_id
*/
CODE_43105(43105, "news has no binding relation with template_id"),
/**
* not allow to add template, for punishment
*/
CODE_43106(43106, "not allow to add template, for punishment"),
/**
* 多媒体文件为空 empty media data
*/
CODE_44001(44001, "多媒体文件为空"),
/**
* POST 的数据包为空 empty post data
*/
CODE_44002(44002, "POST 的数据包为空"),
/**
* 图文消息内容为空 empty news data
*/
CODE_44003(44003, "图文消息内容为空"),
/**
* 文本消息内容为空 empty content
*/
CODE_44004(44004, "文本消息内容为空"),
/**
* 空白的列表 empty list size
*/
CODE_44005(44005, "空白的列表"),
/**
* empty file data
*/
CODE_44006(44006, "empty file data"),
/**
* repeated msg id
*/
CODE_44007(44007, "repeated msg id"),
/**
* image url size out of limit
*/
CODE_44997(44997, "image url size out of limit"),
/**
* keyword string media size out of limit
*/
CODE_44998(44998, "keyword string media size out of limit"),
/**
* keywords list size out of limit
*/
CODE_44999(44999, "keywords list size out of limit"),
/**
* msg_id size out of limit
*/
CODE_45000(45000, "msg_id size out of limit"),
/**
* 多媒体文件大小超过限制 media size out of limit
*/
CODE_45001(45001, "多媒体文件大小超过限制"),
/**
* 消息内容超过限制 content size out of limit
*/
CODE_45002(45002, "消息内容超过限制"),
/**
* 标题字段超过限制 title size out of limit
*/
CODE_45003(45003, "标题字段超过限制"),
/**
* 描述字段超过限制 description size out of limit
*/
CODE_45004(45004, "描述字段超过限制"),
/**
* 链接字段超过限制 url size out of limit
*/
CODE_45005(45005, "链接字段超过限制"),
/**
* 图片链接字段超过限制 picurl size out of limit
*/
CODE_45006(45006, "图片链接字段超过限制"),
/**
* 语音播放时间超过限制 playtime out of limit
*/
CODE_45007(45007, "语音播放时间超过限制"),
/**
* 图文消息超过限制 article size out of limit
*/
CODE_45008(45008, "图文消息超过限制"),
/**
* 接口调用超过限制 reach max api daily quota limit
*/
CODE_45009(45009, "接口调用超过限制"),
/**
* 创建菜单个数超过限制 create menu limit
*/
CODE_45010(45010, "创建菜单个数超过限制"),
/**
* API 调用太频繁,请稍候再试 api minute-quota reach limit, must slower, retry next minute
*/
CODE_45011(45011, "API 调用太频繁,请稍候再试"),
/**
* 模板大小超过限制 template size out of limit
*/
CODE_45012(45012, "模板大小超过限制"),
/**
* too many template args
*/
CODE_45013(45013, "too many template args"),
/**
* template message size out of limit
*/
CODE_45014(45014, "template message size out of limit"),
/**
* 回复时间超过限制 response out of time limit or subscription is canceled
*/
CODE_45015(45015, "回复时间超过限制"),
/**
* 系统分组,不允许修改 can't modify sys group
*/
CODE_45016(45016, "系统分组,不允许修改"),
/**
* 分组名字过长 can't set group name too long sys group
*/
CODE_45017(45017, "分组名字过长"),
/**
* 分组数量超过上限 too many group now, no need to add new
*/
CODE_45018(45018, "分组数量超过上限"),
/**
* too many openid, please input less
*/
CODE_45019(45019, "too many openid, please input less"),
/**
* too many image, please input less
*/
CODE_45020(45020, "too many image, please input less"),
/**
* some argument may be out of length limit! please check document and request json!
*/
CODE_45021(45021, "some argument may be out of length limit! please check document and request json!"),
/**
* bonus is out of limit
*/
CODE_45022(45022, "bonus is out of limit"),
/**
* balance is out of limit
*/
CODE_45023(45023, "balance is out of limit"),
/**
* rank template number is out of limit
*/
CODE_45024(45024, "rank template number is out of limit"),
/**
* poiid count is out of limit
*/
CODE_45025(45025, "poiid count is out of limit"),
/**
* template num exceeds limit
*/
CODE_45026(45026, "template num exceeds limit"),
/**
* template conflict with industry
*/
CODE_45027(45027, "template conflict with industry"),
/**
* has no masssend quota
*/
CODE_45028(45028, "has no masssend quota"),
/**
* qrcode count out of limit
*/
CODE_45029(45029, "qrcode count out of limit"),
/**
* limit cardid, not support this function
*/
CODE_45030(45030, "limit cardid, not support this function"),
/**
* stock is out of limit
*/
CODE_45031(45031, "stock is out of limit"),
/**
* not inner ip for special acct in white-list
*/
CODE_45032(45032, "not inner ip for special acct in white-list"),
/**
* user get card num is out of get_limit
*/
CODE_45033(45033, "user get card num is out of get_limit"),
/**
* media file count is out of limit
*/
CODE_45034(45034, "media file count is out of limit"),
/**
* access clientip is not registered, not in ip-white-list
*/
CODE_45035(45035, "access clientip is not registered, not in ip-white-list"),
/**
* User receive announcement limit
*/
CODE_45036(45036, "User receive announcement limit"),
/**
* user out of time limit or never talked in tempsession
*/
CODE_45037(45037, "user out of time limit or never talked in tempsession"),
/**
* user subscribed, cannot use tempsession api
*/
CODE_45038(45038, "user subscribed, cannot use tempsession api"),
/**
* card_list_size out of limit
*/
CODE_45039(45039, "card_list_size out of limit"),
/**
* reach max monthly quota limit
*/
CODE_45040(45040, "reach max monthly quota limit"),
/**
* this card reach total sku quantity limit!
*/
CODE_45041(45041, "this card reach total sku quantity limit!"),
/**
* limit card type, this card type can NOT create by sub merchant
*/
CODE_45042(45042, "limit card type, this card type can NOT create by sub merchant"),
/**
* can not set share_friends=true because has no Abstract Or Text_Img_List has no img Or image url not valid
*/
CODE_45043(45043, "can not set share_friends=true because has no Abstract Or Text_Img_List has no img Or image url not valid"),
/**
* icon url size in abstract is out of limit
*/
CODE_45044(45044, "icon url size in abstract is out of limit"),
/**
* unauthorized friends card, please contact administrator
*/
CODE_45045(45045, "unauthorized friends card, please contact administrator"),
/**
* operate field conflict, CenterCell, PayCell, SelfConsumeCell conflict
*/
CODE_45046(45046, "operate field conflict, CenterCell, PayCell, SelfConsumeCell conflict"),
/**
* 客服接口下行条数超过上限 out of response count limit
*/
CODE_45047(45047, "客服接口下行条数超过上限"),
/**
* menu use invalid type
*/
CODE_45048(45048, "menu use invalid type"),
/**
* ivr use invalid type
*/
CODE_45049(45049, "ivr use invalid type"),
/**
* custom msg use invalid type
*/
CODE_45050(45050, "custom msg use invalid type"),
/**
* template msg use invalid link
*/
CODE_45051(45051, "template msg use invalid link"),
/**
* masssend msg use invalid type
*/
CODE_45052(45052, "masssend msg use invalid type"),
/**
* exceed consume verify code size
*/
CODE_45053(45053, "exceed consume verify code size"),
/**
* below consume verify code size
*/
CODE_45054(45054, "below consume verify code size"),
/**
* the code is not in consume verify code charset
*/
CODE_45055(45055, "the code is not in consume verify code charset"),
/**
* too many tag now, no need to add new
*/
CODE_45056(45056, "too many tag now, no need to add new"),
/**
* can't delete the tag that has too many fans
*/
CODE_45057(45057, "can't delete the tag that has too many fans"),
/**
* can't modify sys tag
*/
CODE_45058(45058, "can't modify sys tag"),
/**
* can not tagging one user too much
*/
CODE_45059(45059, "can not tagging one user too much"),
/**
* media is applied in ivr or menu, can not be deleted
*/
CODE_45060(45060, "media is applied in ivr or menu, can not be deleted"),
/**
* maybe the update frequency is too often, please try again
*/
CODE_45061(45061, "maybe the update frequency is too often, please try again"),
/**
* has agreement ad. please use mp.weixin.qq.com
*/
CODE_45062(45062, "has agreement ad. please use mp.weixin.qq.com"),
/**
* accesstoken is not xiaochengxu
*/
CODE_45063(45063, "accesstoken is not xiaochengxu"),
/**
* 创建菜单包含未关联的小程序 no permission to use weapp in menu
*/
CODE_45064(45064, "创建菜单包含未关联的小程序"),
/**
* 相同 clientmsgid 已存在群发记录,返回数据中带有已存在的群发任务的 msgid clientmsgid exist
*/
CODE_45065(45065, "相同 clientmsgid 已存在群发记录,返回数据中带有已存在的群发任务的 msgid"),
/**
* 相同 clientmsgid 重试速度过快,请间隔1分钟重试 same clientmsgid retry too fast
*/
CODE_45066(45066, "相同 clientmsgid 重试速度过快,请间隔1分钟重试"),
/**
* clientmsgid 长度超过限制 clientmsgid size out of limit
*/
CODE_45067(45067, "clientmsgid 长度超过限制"),
/**
* file size out of limit
*/
CODE_45068(45068, "file size out of limit"),
/**
* product list size out of limit
*/
CODE_45069(45069, "product list size out of limit"),
/**
* the business account have been created
*/
CODE_45070(45070, "the business account have been created"),
/**
* business account not found
*/
CODE_45071(45071, "business account not found"),
/**
* command字段取值不对 invalid command
*/
CODE_45072(45072, "command字段取值不对"),
/**
* not inner vip for sns in white list
*/
CODE_45073(45073, "not inner vip for sns in white list"),
/**
* material list size out of limit, you should delete the useless material
*/
CODE_45074(45074, "material list size out of limit, you should delete the useless material"),
/**
* invalid keyword id
*/
CODE_45075(45075, "invalid keyword id"),
/**
* invalid count
*/
CODE_45076(45076, "invalid count"),
/**
* number of business account reach limit
*/
CODE_45077(45077, "number of business account reach limit"),
/**
* nickname is illegal!
*/
CODE_45078(45078, "nickname is illegal!"),
/**
* nickname is forbidden!(matched forbidden keyword)
*/
CODE_45079(45079, "nickname is forbidden!(matched forbidden keyword)"),
/**
* 下发输入状态,需要之前30秒内跟用户有过消息交互 need sending message to user, or recving message from user in the last 30 seconds before typing
*/
CODE_45080(45080, "下发输入状态,需要之前30秒内跟用户有过消息交互"),
/**
* 已经在输入状态,不可重复下发 you are already typing
*/
CODE_45081(45081, "已经在输入状态,不可重复下发"),
/**
* need icp license for the url domain
*/
CODE_45082(45082, "need icp license for the url domain"),
/**
* the speed out of range
*/
CODE_45083(45083, "the speed out of range"),
/**
* No speed message
*/
CODE_45084(45084, "No speed message"),
/**
* speed server err
*/
CODE_45085(45085, "speed server err"),
/**
* invalid attrbute 'data-miniprogram-appid'
*/
CODE_45086(45086, "invalid attrbute 'data-miniprogram-appid'"),
/**
* customer service message from this account have been blocked!
*/
CODE_45087(45087, "customer service message from this account have been blocked!"),
/**
* action size out of limit
*/
CODE_45088(45088, "action size out of limit"),
/**
* expired
*/
CODE_45089(45089, "expired"),
/**
* invalid group msg ticket
*/
CODE_45090(45090, "invalid group msg ticket"),
/**
* account_name is illegal!
*/
CODE_45091(45091, "account_name is illegal!"),
/**
* no voice data
*/
CODE_45092(45092, "no voice data"),
/**
* no quota to send msg
*/
CODE_45093(45093, "no quota to send msg"),
/**
* not allow to send custom message when user enter session, for punishment
*/
CODE_45094(45094, "not allow to send custom message when user enter session, for punishment"),
/**
* not allow to modify stock for the advertisement batch
*/
CODE_45095(45095, "not allow to modify stock for the advertisement batch"),
/**
* invalid qrcode
*/
CODE_45096(45096, "invalid qrcode"),
/**
* invalid qrcode prefix
*/
CODE_45097(45097, "invalid qrcode prefix"),
/**
* msgmenu list size is out of limit
*/
CODE_45098(45098, "msgmenu list size is out of limit"),
/**
* msgmenu item content size is out of limit
*/
CODE_45099(45099, "msgmenu item content size is out of limit"),
/**
* invalid size of keyword_id_list
*/
CODE_45100(45100, "invalid size of keyword_id_list"),
/**
* hit upload limit
*/
CODE_45101(45101, "hit upload limit"),
/**
* this api have been blocked temporarily.
*/
CODE_45102(45102, "this api have been blocked temporarily."),
/**
* This API has been unsupported
*/
CODE_45103(45103, "This API has been unsupported"),
/**
* reach max domain quota limit
*/
CODE_45104(45104, "reach max domain quota limit"),
/**
* the consume verify code not found
*/
CODE_45154(45154, "the consume verify code not found"),
/**
* the consume verify code is existed
*/
CODE_45155(45155, "the consume verify code is existed"),
/**
* the consume verify code's length not invalid
*/
CODE_45156(45156, "the consume verify code's length not invalid"),
/**
* invalid tag name
*/
CODE_45157(45157, "invalid tag name"),
/**
* tag name too long
*/
CODE_45158(45158, "tag name too long"),
/**
* invalid tag id
*/
CODE_45159(45159, "invalid tag id"),
/**
* invalid category to create card
*/
CODE_45160(45160, "invalid category to create card"),
/**
* this video id must be generated by calling upload api
*/
CODE_45161(45161, "this video id must be generated by calling upload api"),
/**
* invalid type
*/
CODE_45162(45162, "invalid type"),
/**
* invalid sort_method
*/
CODE_45163(45163, "invalid sort_method"),
/**
* invalid offset
*/
CODE_45164(45164, "invalid offset"),
/**
* invalid limit
*/
CODE_45165(45165, "invalid limit"),
/**
* invalid content
*/
CODE_45166(45166, "invalid content"),
/**
* invalid voip call key
*/
CODE_45167(45167, "invalid voip call key"),
/**
* keyword in blacklist
*/
CODE_45168(45168, "keyword in blacklist"),
/**
* part or whole of the requests from the very app is temporary blocked by supervisor
*/
CODE_45501(45501, "part or whole of the requests from the very app is temporary blocked by supervisor"),
/**
* 不存在媒体数据,media_id 不存在 media data no exist
*/
CODE_46001(46001, "不存在媒体数据,media_id 不存在"),
/**
* 不存在的菜单版本 menu version no exist
*/
CODE_46002(46002, "不存在的菜单版本"),
/**
* 不存在的菜单数据 menu no exist
*/
CODE_46003(46003, "不存在的菜单数据"),
/**
* 不存在的用户 user no exist
*/
CODE_46004(46004, "不存在的用户"),
/**
* poi no exist
*/
CODE_46005(46005, "poi no exist"),
/**
* voip file not exist
*/
CODE_46006(46006, "voip file not exist"),
/**
* file being transcoded, please try later
*/
CODE_46007(46007, "file being transcoded, please try later"),
/**
* result id not exist
*/
CODE_46008(46008, "result id not exist"),
/**
* there is no user data
*/
CODE_46009(46009, "there is no user data"),
/**
* this api have been not supported since 2020-01-11 00:00:00, please use new api(subscribeMessage)!
*/
CODE_46101(46101, "this api have been not supported since 2020-01-11 00:00:00, please use new api(subscribeMessage)!"),
/**
* 解析 JSON/XML 内容错误 data format error
*/
CODE_47001(47001, "解析 JSON/XML 内容错误"),
/**
* data format error, do NOT use json unicode encode (\\uxxxx\\uxxxx), please use utf8 encoded text!
*/
CODE_47002(47002, "data format error, do NOT use json unicode encode (\\uxxxx\\uxxxx), please use utf8 encoded text!"),
/**
* 模板参数不准确,可能为空或者不满足规则,errmsg会提示具体是哪个字段出错 argument invalid!
*/
CODE_47003(47003, "模板参数不准确,可能为空或者不满足规则,errmsg会提示具体是哪个字段出错"),
/**
* 每次提交的页面数超过1000(备注:每次提交页面数应小于或等于1000) submit pages count more than each quota
*/
CODE_47004(47004, "每次提交的页面数超过1000(备注:每次提交页面数应小于或等于1000)"),
/**
* tabbar no exist
*/
CODE_47005(47005, "tabbar no exist"),
/**
* 当天提交页面数达到了配额上限,请明天再试 submit pages count reach daily limit, please try tomorrow
*/
CODE_47006(47006, "当天提交页面数达到了配额上限,请明天再试"),
/**
* 搜索结果总数超过了1000条 search results count more than limit
*/
CODE_47101(47101, "搜索结果总数超过了1000条"),
/**
* next_page_info参数错误 next_page_info error
*/
CODE_47102(47102, "next_page_info参数错误"),
/**
* 参数 activity_id 错误 activity_id error
*/
CODE_47501(47501, "参数 activity_id 错误"),
/**
* 参数 target_state 错误 target_state error
*/
CODE_47502(47502, "参数 target_state 错误"),
/**
* 参数 version_type 错误 version_type error
*/
CODE_47503(47503, "参数 version_type 错误"),
/**
* activity_id activity_id expired time
*/
CODE_47504(47504, "activity_id"),
/**
* api 功能未授权,请确认公众号已获得该接口,可以在公众平台官网 - 开发者中心页中查看接口权限 api unauthorized
*/
CODE_48001(48001, "api 功能未授权,请确认公众号已获得该接口,可以在公众平台官网 - 开发者中心页中查看接口权限"),
/**
* 粉丝拒收消息(粉丝在公众号选项中,关闭了 “ 接收消息 ” ) user block receive message
*/
CODE_48002(48002, "粉丝拒收消息(粉丝在公众号选项中,关闭了 “ 接收消息 ” )"),
/**
* user not agree mass-send protocol
*/
CODE_48003(48003, "user not agree mass-send protocol"),
/**
* api 接口被封禁,请登录 mp.weixin.qq.com 查看详情 api forbidden for irregularities, view detail on mp.weixin.qq.com
*/
CODE_48004(48004, "api 接口被封禁,请登录 mp.weixin.qq.com 查看详情"),
/**
* api 禁止删除被自动回复和自定义菜单引用的素材 forbid to delete material used by auto-reply or menu
*/
CODE_48005(48005, "api 禁止删除被自动回复和自定义菜单引用的素材"),
/**
* api 禁止清零调用次数,因为清零次数达到上限 forbid to clear quota because of reaching the limit
*/
CODE_48006(48006, "api 禁止清零调用次数,因为清零次数达到上限"),
/**
* forbid to use other's voip call key
*/
CODE_48007(48007, "forbid to use other's voip call key"),
/**
* 没有该类型消息的发送权限 no permission for this msgtype
*/
CODE_48008(48008, "没有该类型消息的发送权限"),
/**
* this api is expired
*/
CODE_48009(48009, "this api is expired"),
/**
* forbid to modify the material, please see more information on mp.weixin.qq.com
*/
CODE_48010(48010, "forbid to modify the material, please see more information on mp.weixin.qq.com"),
/**
* disabled template id
*/
CODE_48011(48011, "disabled template id"),
/**
* invalid token
*/
CODE_48012(48012, "invalid token"),
/**
* 该视频非新接口上传,不能用于视频消息群发
*/
CODE_48013(48013, "该视频非新接口上传,不能用于视频消息群发"),
/**
* 该视频审核状态异常,请检查后重试
*/
CODE_48014(48014, "该视频审核状态异常,请检查后重试"),
/**
* 该账号无留言功能权限
*/
CODE_48015(48015, "该账号无留言功能权限"),
/**
* 该账号不满足智能配置"观看更多"视频条件
*/
CODE_48016(48016, "该账号不满足智能配置\"观看更多\"视频条件"),
/**
* not same appid with appid of access_token
*/
CODE_49001(49001, "not same appid with appid of access_token"),
/**
* empty openid or transid
*/
CODE_49002(49002, "empty openid or transid"),
/**
* not match openid with appid
*/
CODE_49003(49003, "not match openid with appid"),
/**
* not match signature
*/
CODE_49004(49004, "not match signature"),
/**
* not existed transid
*/
CODE_49005(49005, "not existed transid"),
/**
* missing arg two_dim_code
*/
CODE_49006(49006, "missing arg two_dim_code"),
/**
* invalid two_dim_code
*/
CODE_49007(49007, "invalid two_dim_code"),
/**
* invalid qrcode
*/
CODE_49008(49008, "invalid qrcode"),
/**
* missing arg qrcode
*/
CODE_49009(49009, "missing arg qrcode"),
/**
* invalid partner id
*/
CODE_49010(49010, "invalid partner id"),
/**
* not existed feedbackid
*/
CODE_49300(49300, "not existed feedbackid"),
/**
* feedback exist
*/
CODE_49301(49301, "feedback exist"),
/**
* feedback status already changed
*/
CODE_49302(49302, "feedback status already changed"),
/**
* 用户未授权该 api api unauthorized or user unauthorized
*/
CODE_50001(50001, "用户未授权该 api"),
/**
* 用户受限,可能是用户帐号被冻结或注销 user limited
*/
CODE_50002(50002, "用户受限,可能是用户帐号被冻结或注销"),
/**
* user unexpected, maybe not in white list
*/
CODE_50003(50003, "user unexpected, maybe not in white list"),
/**
* user not allow to use accesstoken, maybe for punishment
*/
CODE_50004(50004, "user not allow to use accesstoken, maybe for punishment"),
/**
* 用户未关注公众号 user is unsubscribed
*/
CODE_50005(50005, "用户未关注公众号"),
/**
* user has switched off friends authorization
*/
CODE_50006(50006, "user has switched off friends authorization"),
/**
* enterprise father account not exist
*/
CODE_51000(51000, "enterprise father account not exist"),
/**
* enterprise child account not belong to the father
*/
CODE_51001(51001, "enterprise child account not belong to the father"),
/**
* enterprise verify message not correct
*/
CODE_51002(51002, "enterprise verify message not correct"),
/**
* invalid enterprise child list size
*/
CODE_51003(51003, "invalid enterprise child list size"),
/**
* not a enterprise father account
*/
CODE_51004(51004, "not a enterprise father account"),
/**
* not a enterprise child account
*/
CODE_51005(51005, "not a enterprise child account"),
/**
* invalid nick name
*/
CODE_51006(51006, "invalid nick name"),
/**
* not a enterprise account
*/
CODE_51007(51007, "not a enterprise account"),
/**
* invalid email
*/
CODE_51008(51008, "invalid email"),
/**
* invalid pwd
*/
CODE_51009(51009, "invalid pwd"),
/**
* repeated email
*/
CODE_51010(51010, "repeated email"),
/**
* access deny
*/
CODE_51011(51011, "access deny"),
/**
* need verify code
*/
CODE_51012(51012, "need verify code"),
/**
* wrong verify code
*/
CODE_51013(51013, "wrong verify code"),
/**
* need modify pwd
*/
CODE_51014(51014, "need modify pwd"),
/**
* user not exist
*/
CODE_51015(51015, "user not exist"),
/**
* tv info not exist
*/
CODE_51020(51020, "tv info not exist"),
/**
* stamp crossed
*/
CODE_51021(51021, "stamp crossed"),
/**
* invalid stamp range
*/
CODE_51022(51022, "invalid stamp range"),
/**
* stamp not match date
*/
CODE_51023(51023, "stamp not match date"),
/**
* empty program name
*/
CODE_51024(51024, "empty program name"),
/**
* empty action url
*/
CODE_51025(51025, "empty action url"),
/**
* program name size out of limit
*/
CODE_51026(51026, "program name size out of limit"),
/**
* action url size out of limit
*/
CODE_51027(51027, "action url size out of limit"),
/**
* invalid program name
*/
CODE_51028(51028, "invalid program name"),
/**
* invalid action url
*/
CODE_51029(51029, "invalid action url"),
/**
* invalid action id
*/
CODE_51030(51030, "invalid action id"),
/**
* invalid action offset
*/
CODE_51031(51031, "invalid action offset"),
/**
* empty action title
*/
CODE_51032(51032, "empty action title"),
/**
* action title size out of limit
*/
CODE_51033(51033, "action title size out of limit"),
/**
* empty action icon url
*/
CODE_51034(51034, "empty action icon url"),
/**
* action icon url out of limit
*/
CODE_51035(51035, "action icon url out of limit"),
/**
* pic is not from cdn
*/
CODE_52000(52000, "pic is not from cdn"),
/**
* wechat price is not less than origin price
*/
CODE_52001(52001, "wechat price is not less than origin price"),
/**
* category/sku is wrong
*/
CODE_52002(52002, "category/sku is wrong"),
/**
* product id not existed
*/
CODE_52003(52003, "product id not existed"),
/**
* category id is not exist, or doesn't has sub category
*/
CODE_52004(52004, "category id is not exist, or doesn't has sub category"),
/**
* quantity is zero
*/
CODE_52005(52005, "quantity is zero"),
/**
* area code is invalid
*/
CODE_52006(52006, "area code is invalid"),
/**
* express template param is error
*/
CODE_52007(52007, "express template param is error"),
/**
* express template id is not existed
*/
CODE_52008(52008, "express template id is not existed"),
/**
* group name is empty
*/
CODE_52009(52009, "group name is empty"),
/**
* group id is not existed
*/
CODE_52010(52010, "group id is not existed"),
/**
* mod_action is invalid
*/
CODE_52011(52011, "mod_action is invalid"),
/**
* shelf components count is greater than 20
*/
CODE_52012(52012, "shelf components count is greater than 20"),
/**
* shelf component is empty
*/
CODE_52013(52013, "shelf component is empty"),
/**
* shelf id is not existed
*/
CODE_52014(52014, "shelf id is not existed"),
/**
* order id is not existed
*/
CODE_52015(52015, "order id is not existed"),
/**
* order filter param is invalid
*/
CODE_52016(52016, "order filter param is invalid"),
/**
* order express param is invalid
*/
CODE_52017(52017, "order express param is invalid"),
/**
* order delivery param is invalid
*/
CODE_52018(52018, "order delivery param is invalid"),
/**
* brand name empty
*/
CODE_52019(52019, "brand name empty"),
/**
* principal limit exceed
*/
CODE_53000(53000, "principal limit exceed"),
/**
* principal in black list
*/
CODE_53001(53001, "principal in black list"),
/**
* mobile limit exceed
*/
CODE_53002(53002, "mobile limit exceed"),
/**
* idcard limit exceed
*/
CODE_53003(53003, "idcard limit exceed"),
/**
* 名称格式不合法 nickname invalid
*/
CODE_53010(53010, "名称格式不合法"),
/**
* 名称检测命中频率限制 check nickname too frequently
*/
CODE_53011(53011, "名称检测命中频率限制"),
/**
* 禁止使用该名称 nickname ban
*/
CODE_53012(53012, "禁止使用该名称"),
/**
* 公众号:名称与已有公众号名称重复;小程序:该名称与已有小程序名称重复 nickname has been occupied
*/
CODE_53013(53013, "公众号:名称与已有公众号名称重复;小程序:该名称与已有小程序名称重复"),
/**
* 公众号:公众号已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A};小程序:小程序已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A}
*/
CODE_53014(53014, "公众号:公众号已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A};小程序:小程序已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A}"),
/**
* 公众号:该名称与已有小程序名称重复,需与该小程序帐号相同主体才可申请;小程序:该名称与已有公众号名称重复,需与该公众号帐号相同主体才可申请
*/
CODE_53015(53015, "公众号:该名称与已有小程序名称重复,需与该小程序帐号相同主体才可申请;小程序:该名称与已有公众号名称重复,需与该公众号帐号相同主体才可申请"),
/**
* 公众号:该名称与已有多个小程序名称重复,暂不支持申请;小程序:该名称与已有多个公众号名称重复,暂不支持申请
*/
CODE_53016(53016, "公众号:该名称与已有多个小程序名称重复,暂不支持申请;小程序:该名称与已有多个公众号名称重复,暂不支持申请"),
/**
* 公众号:小程序已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A};小程序:公众号已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A}
*/
CODE_53017(53017, "公众号:小程序已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A};小程序:公众号已有{名称 A+}时,需与该帐号相同主体才可申请{名称 A}"),
/**
* 名称命中微信号 nickname hit alias
*/
CODE_53018(53018, "名称命中微信号"),
/**
* 名称在保护期内 nickname protected by infringement
*/
CODE_53019(53019, "名称在保护期内"),
/**
* order not found
*/
CODE_53100(53100, "订单不存在"),
/**
* order already paid
*/
CODE_53101(53101, "已经支付的订单"),
/**
* already has checking order, can not apply
*/
CODE_53102(53102, "已有检查单,不能申请"),
/**
* order can not do refill
*/
CODE_53103(53103, "order can not do refill"),
/**
* 本月功能介绍修改次数已用完 modify signature quota limit exceed
*/
CODE_53200(53200, "本月功能介绍修改次数已用完"),
/**
* 功能介绍内容命中黑名单关键字 signature in black list, can not use
*/
CODE_53201(53201, "功能介绍内容命中黑名单关键字"),
/**
* 本月头像修改次数已用完 modify avatar quota limit exceed
*/
CODE_53202(53202, "本月头像修改次数已用完"),
/**
* can't be modified for the time being
*/
CODE_53203(53203, "暂时还不能修改"),
/**
* signature invalid
*/
CODE_53204(53204, "无效签名"),
/**
* 超出每月次数限制
*/
CODE_53300(53300, "超出每月次数限制"),
/**
* 超出可配置类目总数限制
*/
CODE_53301(53301, "超出可配置类目总数限制"),
/**
* 当前账号主体类型不允许设置此种类目
*/
CODE_53302(53302, "当前账号主体类型不允许设置此种类目"),
/**
* 提交的参数不合法
*/
CODE_53303(53303, "提交的参数不合法"),
/**
* 与已有类目重复
*/
CODE_53304(53304, "与已有类目重复"),
/**
* 包含未通过IPC校验的类目
*/
CODE_53305(53305, "包含未通过IPC校验的类目"),
/**
* 修改类目只允许修改类目资质,不允许修改类目ID
*/
CODE_53306(53306, "修改类目只允许修改类目资质,不允许修改类目ID"),
/**
* 只有审核失败的类目允许修改
*/
CODE_53307(53307, "只有审核失败的类目允许修改"),
/**
* 审核中的类目不允许删除
*/
CODE_53308(53308, "审核中的类目不允许删除"),
/**
* 社交红包不允许删除
*/
CODE_53309(53309, "社交红包不允许删除"),
/**
* 类目超过上限,但是可以添加apply_reason参数申请更多类目
*/
CODE_53310(53310, "类目超过上限,但是可以添加apply_reason参数申请更多类目"),
/**
* 需要提交资料信息
*/
CODE_53311(53311, "需要提交资料信息"),
/**
* empty jsapi name
*/
CODE_60005(60005, "空的jsapi名称"),
/**
* user cancel the auth
*/
CODE_60006(60006, "用户取消该授权"),
/**
* invalid component type
*/
CODE_61000(61000, "无效的第三方类型"),
/**
* component type and component appid is not match
*/
CODE_61001(61001, "第三方类型与第三方APPID不匹配"),
/**
* the third appid is not open KF
*/
CODE_61002(61002, "第三方APPID没有开放客服"),
/**
* component is not authorized by this account
*/
CODE_61003(61003, "帐号未授权"),
/**
* api 功能未授权,请确认公众号/小程序已获得该接口,可以在公众平台官网 - 开发者中心页中查看接口权限 access clientip is not registered
*/
CODE_61004(61004, "api 功能未授权,请确认公众号/小程序已获得该接口,可以在公众平台官网 - 开发者中心页中查看接口权限"),
/**
* component ticket is expired
*/
CODE_61005(61005, "ticket 已过期"),
/**
* component ticket is invalid
*/
CODE_61006(61006, "无效 ticket"),
/**
* api is unauthorized to component
*/
CODE_61007(61007, "接口未授权给第三方平台"),
/**
* component req key is duplicated
*/
CODE_61008(61008, "第三方请求的key存在重复"),
/**
* code is invalid
*/
CODE_61009(61009, "无效code"),
/**
* code is expired
*/
CODE_61010(61010, "code已过期"),
/**
* invalid component
*/
CODE_61011(61011, "无效的第三方平台"),
/**
* invalid option name
*/
CODE_61012(61012, "无效的选项名称"),
/**
* invalid option value
*/
CODE_61013(61013, "无效的选项值"),
/**
* must use component token for component api
*/
CODE_61014(61014, "必须使用component接口的token"),
/**
* must use biz account token for not component api
*/
CODE_61015(61015, "必须使用商业帐号token,而不是component api"),
/**
* function category of API need be confirmed by component
*/
CODE_61016(61016, "function category of API need be confirmed by component"),
/**
* function category is not authorized
*/
CODE_61017(61017, "function category is not authorized"),
/**
* already confirm
*/
CODE_61018(61018, "已确认"),
/**
* not need confirm
*/
CODE_61019(61019, "不需要确认"),
/**
* err parameter
*/
CODE_61020(61020, "err parameter"),
/**
* can't confirm
*/
CODE_61021(61021, "can't confirm"),
/**
* can't resubmit
*/
CODE_61022(61022, "can't resubmit"),
/**
* refresh_token is invalid
*/
CODE_61023(61023, "refresh_token is invalid"),
/**
* must use api(api_component_token) to get token for component acct
*/
CODE_61024(61024, "must use api(api_component_token) to get token for component acct"),
/**
* read-only option
*/
CODE_61025(61025, "read-only option"),
/**
* register access deny
*/
CODE_61026(61026, "register access deny"),
/**
* register limit exceed
*/
CODE_61027(61027, "register limit exceed"),
/**
* component is unpublished
*/
CODE_61028(61028, "component is unpublished"),
/**
* component need republish with base category
*/
CODE_61029(61029, "component need republish with base category"),
/**
* component cancel authorization not allowed
*/
CODE_61030(61030, "component cancel authorization not allowed"),
/**
* invalid realname type
*/
CODE_61051(61051, "invalid realname type"),
/**
* need to be certified
*/
CODE_61052(61052, "need to be certified"),
/**
* realname exceed limits
*/
CODE_61053(61053, "realname exceed limits"),
/**
* realname in black list
*/
CODE_61054(61054, "realname in black list"),
/**
* exceed quota per month
*/
CODE_61055(61055, "exceed quota per month"),
/**
* copy_wx_verify is required option
*/
CODE_61056(61056, "copy_wx_verify is required option"),
/**
* invalid ticket
*/
CODE_61058(61058, "invalid ticket"),
/**
* overseas access deny
*/
CODE_61061(61061, "overseas access deny"),
/**
* admin exceed limits
*/
CODE_61063(61063, "admin exceed limits"),
/**
* admin in black list
*/
CODE_61064(61064, "admin in black list"),
/**
* idcard exceed limits
*/
CODE_61065(61065, "idcard exceed limits"),
/**
* idcard in black list
*/
CODE_61066(61066, "idcard in black list"),
/**
* mobile exceed limits
*/
CODE_61067(61067, "mobile exceed limits"),
/**
* mobile in black list
*/
CODE_61068(61068, "mobile in black list"),
/**
* invalid admin
*/
CODE_61069(61069, "invalid admin"),
/**
* name, idcard, wechat name not in accordance
*/
CODE_61070(61070, "name, idcard, wechat name not in accordance"),
/**
* invalid url
*/
CODE_61100(61100, "invalid url"),
/**
* invalid openid
*/
CODE_61101(61101, "invalid openid"),
/**
* share relation not existed
*/
CODE_61102(61102, "share relation not existed"),
/**
* product wording not set
*/
CODE_61200(61200, "product wording not set"),
/**
* invalid base info
*/
CODE_61300(61300, "invalid base info"),
/**
* invalid detail info
*/
CODE_61301(61301, "invalid detail info"),
/**
* invalid action info
*/
CODE_61302(61302, "invalid action info"),
/**
* brand info not exist
*/
CODE_61303(61303, "brand info not exist"),
/**
* invalid product id
*/
CODE_61304(61304, "invalid product id"),
/**
* invalid key info
*/
CODE_61305(61305, "invalid key info"),
/**
* invalid appid
*/
CODE_61306(61306, "invalid appid"),
/**
* invalid card id
*/
CODE_61307(61307, "invalid card id"),
/**
* base info not exist
*/
CODE_61308(61308, "base info not exist"),
/**
* detail info not exist
*/
CODE_61309(61309, "detail info not exist"),
/**
* action info not exist
*/
CODE_61310(61310, "action info not exist"),
/**
* invalid media info
*/
CODE_61311(61311, "invalid media info"),
/**
* invalid buffer size
*/
CODE_61312(61312, "invalid buffer size"),
/**
* invalid buffer
*/
CODE_61313(61313, "invalid buffer"),
/**
* invalid qrcode extinfo
*/
CODE_61314(61314, "invalid qrcode extinfo"),
/**
* invalid local ext info
*/
CODE_61315(61315, "invalid local ext info"),
/**
* key conflict
*/
CODE_61316(61316, "key conflict"),
/**
* ticket invalid
*/
CODE_61317(61317, "ticket invalid"),
/**
* verify not pass
*/
CODE_61318(61318, "verify not pass"),
/**
* category invalid
*/
CODE_61319(61319, "category invalid"),
/**
* merchant info not exist
*/
CODE_61320(61320, "merchant info not exist"),
/**
* cate id is a leaf node
*/
CODE_61321(61321, "cate id is a leaf node"),
/**
* category id no permision
*/
CODE_61322(61322, "category id no permision"),
/**
* barcode no permision
*/
CODE_61323(61323, "barcode no permision"),
/**
* exceed max action num
*/
CODE_61324(61324, "exceed max action num"),
/**
* brandinfo invalid store mgr type
*/
CODE_61325(61325, "brandinfo invalid store mgr type"),
/**
* anti-spam blocked
*/
CODE_61326(61326, "anti-spam blocked"),
/**
* comment reach limit
*/
CODE_61327(61327, "comment reach limit"),
/**
* comment data is not the newest
*/
CODE_61328(61328, "comment data is not the newest"),
/**
* comment hit ban word
*/
CODE_61329(61329, "comment hit ban word"),
/**
* image already add
*/
CODE_61330(61330, "image already add"),
/**
* image never add
*/
CODE_61331(61331, "image never add"),
/**
* warning, image quanlity too low
*/
CODE_61332(61332, "warning, image quanlity too low"),
/**
* warning, image simility too high
*/
CODE_61333(61333, "warning, image simility too high"),
/**
* product not exists
*/
CODE_61334(61334, "product not exists"),
/**
* key apply fail
*/
CODE_61335(61335, "key apply fail"),
/**
* check status fail
*/
CODE_61336(61336, "check status fail"),
/**
* product already exists
*/
CODE_61337(61337, "product already exists"),
/**
* forbid delete
*/
CODE_61338(61338, "forbid delete"),
/**
* firmcode claimed
*/
CODE_61339(61339, "firmcode claimed"),
/**
* check firm info fail
*/
CODE_61340(61340, "check firm info fail"),
/**
* too many white list uin
*/
CODE_61341(61341, "too many white list uin"),
/**
* keystandard not match
*/
CODE_61342(61342, "keystandard not match"),
/**
* keystandard error
*/
CODE_61343(61343, "keystandard error"),
/**
* id map not exists
*/
CODE_61344(61344, "id map not exists"),
/**
* invalid action code
*/
CODE_61345(61345, "invalid action code"),
/**
* invalid actioninfo store
*/
CODE_61346(61346, "invalid actioninfo store"),
/**
* invalid actioninfo media
*/
CODE_61347(61347, "invalid actioninfo media"),
/**
* invalid actioninfo text
*/
CODE_61348(61348, "invalid actioninfo text"),
/**
* invalid input data
*/
CODE_61350(61350, "invalid input data"),
/**
* input data exceed max size
*/
CODE_61351(61351, "input data exceed max size"),
/**
* kf_account error
*/
CODE_61400(61400, "kf_account error"),
/**
* kf system alredy transfer
*/
CODE_61401(61401, "kf system alredy transfer"),
/**
* 系统错误 (system error)
*/
CODE_61450(61450, "系统错误 (system error)"),
/**
* 参数错误 (invalid parameter)
*/
CODE_61451(61451, "参数错误 (invalid parameter)"),
/**
* 无效客服账号 (invalid kf_account)
*/
CODE_61452(61452, "无效客服账号 (invalid kf_account)"),
/**
* 客服帐号已存在 (kf_account exsited)
*/
CODE_61453(61453, "客服帐号已存在 (kf_account exsited)"),
/**
* 客服帐号名长度超过限制 ( 仅允许 10 个英文字符,不包括 @ 及 @ 后的公众号的微信号 )(invalid kf_acount length)
*/
CODE_61454(61454, "客服帐号名长度超过限制 ( 仅允许 10 个英文字符,不包括 @ 及 @ 后的公众号的微信号 )(invalid kf_acount length)"),
/**
* 客服帐号名包含非法字符 ( 仅允许英文 + 数字 )(illegal character in kf_account)
*/
CODE_61455(61455, "客服帐号名包含非法字符 ( 仅允许英文 + 数字 )(illegal character in kf_account)"),
/**
* 客服帐号个数超过限制 (10 个客服账号 )(kf_account count exceeded)
*/
CODE_61456(61456, "客服帐号个数超过限制 (10 个客服账号 )(kf_account count exceeded)"),
/**
* 无效头像文件类型 (invalid file type)
*/
CODE_61457(61457, "无效头像文件类型 (invalid file type)"),
/**
* 日期格式错误 date format error
*/
CODE_61500(61500, "日期格式错误"),
/**
* date range error
*/
CODE_61501(61501, "date range error"),
/**
* this is game miniprogram, data api is not supported
*/
CODE_61502(61502, "this is game miniprogram, data api is not supported"),
/**
* data not ready, please try later
*/
CODE_61503(61503, "data not ready, please try later"),
/**
* trying to access other's app
*/
CODE_62001(62001, "trying to access other's app"),
/**
* app name already exists
*/
CODE_62002(62002, "app name already exists"),
/**
* please provide at least one platform
*/
CODE_62003(62003, "please provide at least one platform"),
/**
* invalid app name
*/
CODE_62004(62004, "invalid app name"),
/**
* invalid app id
*/
CODE_62005(62005, "invalid app id"),
/**
* 部分参数为空 some arguments is empty
*/
CODE_63001(63001, "部分参数为空"),
/**
* 无效的签名 invalid signature
*/
CODE_63002(63002, "无效的签名"),
/**
* invalid signature method
*/
CODE_63003(63003, "invalid signature method"),
/**
* no authroize
*/
CODE_63004(63004, "no authroize"),
/**
* gen ticket fail
*/
CODE_63149(63149, "gen ticket fail"),
/**
* set ticket fail
*/
CODE_63152(63152, "set ticket fail"),
/**
* shortid decode fail
*/
CODE_63153(63153, "shortid decode fail"),
/**
* invalid status
*/
CODE_63154(63154, "invalid status"),
/**
* invalid color
*/
CODE_63155(63155, "invalid color"),
/**
* invalid tag
*/
CODE_63156(63156, "invalid tag"),
/**
* invalid recommend
*/
CODE_63157(63157, "invalid recommend"),
/**
* branditem out of limits
*/
CODE_63158(63158, "branditem out of limits"),
/**
* retail_price empty
*/
CODE_63159(63159, "retail_price empty"),
/**
* priceinfo invalid
*/
CODE_63160(63160, "priceinfo invalid"),
/**
* antifake module num limit
*/
CODE_63161(63161, "antifake module num limit"),
/**
* antifake native_type err
*/
CODE_63162(63162, "antifake native_type err"),
/**
* antifake link not exists
*/
CODE_63163(63163, "antifake link not exists"),
/**
* module type not exist
*/
CODE_63164(63164, "module type not exist"),
/**
* module info not exist
*/
CODE_63165(63165, "module info not exist"),
/**
* item is beding verified
*/
CODE_63166(63166, "item is beding verified"),
/**
* item not published
*/
CODE_63167(63167, "item not published"),
/**
* verify not pass
*/
CODE_63168(63168, "verify not pass"),
/**
* already published
*/
CODE_63169(63169, "already published"),
/**
* only banner or media
*/
CODE_63170(63170, "only banner or media"),
/**
* card num limit
*/
CODE_63171(63171, "card num limit"),
/**
* user num limit
*/
CODE_63172(63172, "user num limit"),
/**
* text num limit
*/
CODE_63173(63173, "text num limit"),
/**
* link card user sum limit
*/
CODE_63174(63174, "link card user sum limit"),
/**
* detail info error
*/
CODE_63175(63175, "detail info error"),
/**
* not this type
*/
CODE_63176(63176, "not this type"),
/**
* src or secretkey or version or expired_time is wrong
*/
CODE_63177(63177, "src or secretkey or version or expired_time is wrong"),
/**
* appid wrong
*/
CODE_63178(63178, "appid wrong"),
/**
* openid num limit
*/
CODE_63179(63179, "openid num limit"),
/**
* this app msg not found
*/
CODE_63180(63180, "this app msg not found"),
/**
* get history app msg end
*/
CODE_63181(63181, "get history app msg end"),
/**
* openid_list empty
*/
CODE_63182(63182, "openid_list empty"),
/**
* unknown deeplink type
*/
CODE_65001(65001, "unknown deeplink type"),
/**
* deeplink unauthorized
*/
CODE_65002(65002, "deeplink unauthorized"),
/**
* bad deeplink
*/
CODE_65003(65003, "bad deeplink"),
/**
* deeplinks of the very type are supposed to have short-life
*/
CODE_65004(65004, "deeplinks of the very type are supposed to have short-life"),
/**
* invalid categories
*/
CODE_65104(65104, "invalid categories"),
/**
* invalid photo url
*/
CODE_65105(65105, "invalid photo url"),
/**
* poi audit state must be approved
*/
CODE_65106(65106, "poi audit state must be approved"),
/**
* poi not allowed modify now
*/
CODE_65107(65107, "poi not allowed modify now"),
/**
* invalid business name
*/
CODE_65109(65109, "invalid business name"),
/**
* invalid address
*/
CODE_65110(65110, "invalid address"),
/**
* invalid telephone
*/
CODE_65111(65111, "invalid telephone"),
/**
* invalid city
*/
CODE_65112(65112, "invalid city"),
/**
* invalid province
*/
CODE_65113(65113, "invalid province"),
/**
* photo list empty
*/
CODE_65114(65114, "photo list empty"),
/**
* poi_id is not exist
*/
CODE_65115(65115, "poi_id is not exist"),
/**
* poi has been deleted
*/
CODE_65116(65116, "poi has been deleted"),
/**
* cannot delete poi
*/
CODE_65117(65117, "cannot delete poi"),
/**
* store status is invalid
*/
CODE_65118(65118, "store status is invalid"),
/**
* lack of qualification for relevant principals
*/
CODE_65119(65119, "lack of qualification for relevant principals"),
/**
* category info is not found
*/
CODE_65120(65120, "category info is not found"),
/**
* room_name is empty, please check your input
*/
CODE_65201(65201, "room_name is empty, please check your input"),
/**
* user_id is empty, please check your input
*/
CODE_65202(65202, "user_id is empty, please check your input"),
/**
* invalid check ticket
*/
CODE_65203(65203, "invalid check ticket"),
/**
* invalid check ticket opt code
*/
CODE_65204(65204, "invalid check ticket opt code"),
/**
* check ticket out of time
*/
CODE_65205(65205, "check ticket out of time"),
/**
* 不存在此 menuid 对应的个性化菜单 this menu is not conditionalmenu
*/
CODE_65301(65301, "不存在此 menuid 对应的个性化菜单"),
/**
* 没有相应的用户 no such user
*/
CODE_65302(65302, "没有相应的用户"),
/**
* 没有默认菜单,不能创建个性化菜单 there is no selfmenu, please create selfmenu first
*/
CODE_65303(65303, "没有默认菜单,不能创建个性化菜单"),
/**
* MatchRule 信息为空 match rule empty
*/
CODE_65304(65304, "MatchRule 信息为空"),
/**
* 个性化菜单数量受限 menu count limit
*/
CODE_65305(65305, "个性化菜单数量受限"),
/**
* 不支持个性化菜单的帐号 conditional menu not support
*/
CODE_65306(65306, "不支持个性化菜单的帐号"),
/**
* 个性化菜单信息为空 conditional menu is empty
*/
CODE_65307(65307, "个性化菜单信息为空"),
/**
* 包含没有响应类型的 button exist empty button act
*/
CODE_65308(65308, "包含没有响应类型的 button"),
/**
* 个性化菜单开关处于关闭状态 conditional menu switch is closed
*/
CODE_65309(65309, "个性化菜单开关处于关闭状态"),
/**
* 填写了省份或城市信息,国家信息不能为空 region info: country is empty
*/
CODE_65310(65310, "填写了省份或城市信息,国家信息不能为空"),
/**
* 填写了城市信息,省份信息不能为空 region info: province is empty
*/
CODE_65311(65311, "填写了城市信息,省份信息不能为空"),
/**
* 不合法的国家信息 invalid country info
*/
CODE_65312(65312, "不合法的国家信息"),
/**
* 不合法的省份信息 invalid province info
*/
CODE_65313(65313, "不合法的省份信息"),
/**
* 不合法的城市信息 invalid city info
*/
CODE_65314(65314, "不合法的城市信息"),
/**
* not fans
*/
CODE_65315(65315, "not fans"),
/**
* 该公众号的菜单设置了过多的域名外跳(最多跳转到 3 个域名的链接) domain count reach limit
*/
CODE_65316(65316, "该公众号的菜单设置了过多的域名外跳(最多跳转到 3 个域名的链接)"),
/**
* 不合法的 URL contain invalid url
*/
CODE_65317(65317, "不合法的 URL"),
/**
* must use utf-8 charset
*/
CODE_65318(65318, "must use utf-8 charset"),
/**
* not allow to create menu
*/
CODE_65319(65319, "not allow to create menu"),
/**
* please enable new custom service, or wait for a while if you have enabled
*/
CODE_65400(65400, "please enable new custom service, or wait for a while if you have enabled"),
/**
* invalid custom service account
*/
CODE_65401(65401, "invalid custom service account"),
/**
* the custom service account need to bind a wechat user
*/
CODE_65402(65402, "the custom service account need to bind a wechat user"),
/**
* illegal nickname
*/
CODE_65403(65403, "illegal nickname"),
/**
* illegal custom service account
*/
CODE_65404(65404, "illegal custom service account"),
/**
* custom service account number reach limit
*/
CODE_65405(65405, "custom service account number reach limit"),
/**
* custom service account exists
*/
CODE_65406(65406, "custom service account exists"),
/**
* the wechat user have been one of your workers
*/
CODE_65407(65407, "the wechat user have been one of your workers"),
/**
* you have already invited the wechat user
*/
CODE_65408(65408, "you have already invited the wechat user"),
/**
* wechat account invalid
*/
CODE_65409(65409, "wechat account invalid"),
/**
* too many custom service accounts bound by the worker
*/
CODE_65410(65410, "too many custom service accounts bound by the worker"),
/**
* a effective invitation to bind the custom service account exists
*/
CODE_65411(65411, "a effective invitation to bind the custom service account exists"),
/**
* the custom service account have been bound by a wechat user
*/
CODE_65412(65412, "the custom service account have been bound by a wechat user"),
/**
* no effective session for the customer
*/
CODE_65413(65413, "no effective session for the customer"),
/**
* another worker is serving the customer
*/
CODE_65414(65414, "another worker is serving the customer"),
/**
* the worker is not online
*/
CODE_65415(65415, "the worker is not online"),
/**
* param invalid, please check
*/
CODE_65416(65416, "param invalid, please check"),
/**
* it is too long from the starttime to endtime
*/
CODE_65417(65417, "it is too long from the starttime to endtime"),
/**
* homepage not exists
*/
CODE_65450(65450, "homepage not exists"),
/**
* invalid store type
*/
CODE_68002(68002, "invalid store type"),
/**
* invalid store name
*/
CODE_68003(68003, "invalid store name"),
/**
* invalid store wxa path
*/
CODE_68004(68004, "invalid store wxa path"),
/**
* miss store wxa path
*/
CODE_68005(68005, "miss store wxa path"),
/**
* invalid kefu type
*/
CODE_68006(68006, "invalid kefu type"),
/**
* invalid kefu wxa path
*/
CODE_68007(68007, "invalid kefu wxa path"),
/**
* invalid kefu phone number
*/
CODE_68008(68008, "invalid kefu phone number"),
/**
* invalid sub mch id
*/
CODE_68009(68009, "invalid sub mch id"),
/**
* store id has exist
*/
CODE_68010(68010, "store id has exist"),
/**
* miss store name
*/
CODE_68011(68011, "miss store name"),
/**
* miss create time
*/
CODE_68012(68012, "miss create time"),
/**
* invalid status
*/
CODE_68013(68013, "invalid status"),
/**
* invalid receiver info
*/
CODE_68014(68014, "invalid receiver info"),
/**
* invalid product
*/
CODE_68015(68015, "invalid product"),
/**
* invalid pay type
*/
CODE_68016(68016, "invalid pay type"),
/**
* invalid fast mail no
*/
CODE_68017(68017, "invalid fast mail no"),
/**
* invalid busi id
*/
CODE_68018(68018, "invalid busi id"),
/**
* miss product sku
*/
CODE_68019(68019, "miss product sku"),
/**
* invalid service type
*/
CODE_68020(68020, "invalid service type"),
/**
* invalid service status
*/
CODE_68021(68021, "invalid service status"),
/**
* invalid service_id
*/
CODE_68022(68022, "invalid service_id"),
/**
* service_id has exist
*/
CODE_68023(68023, "service_id has exist"),
/**
* miss service wxa path
*/
CODE_68024(68024, "miss service wxa path"),
/**
* invalid product sku
*/
CODE_68025(68025, "invalid product sku"),
/**
* invalid product spu
*/
CODE_68026(68026, "invalid product spu"),
/**
* miss product spu
*/
CODE_68027(68027, "miss product spu"),
/**
* can not find product spu and spu in order list
*/
CODE_68028(68028, "can not find product spu and spu in order list"),
/**
* sku and spu duplicated
*/
CODE_68029(68029, "sku and spu duplicated"),
/**
* busi_id has exist
*/
CODE_68030(68030, "busi_id has exist"),
/**
* update fail
*/
CODE_68031(68031, "update fail"),
/**
* busi_id not exist
*/
CODE_68032(68032, "busi_id not exist"),
/**
* store no exist
*/
CODE_68033(68033, "store no exist"),
/**
* miss product number
*/
CODE_68034(68034, "miss product number"),
/**
* miss wxa order detail path
*/
CODE_68035(68035, "miss wxa order detail path"),
/**
* there is no enough products to refund
*/
CODE_68036(68036, "there is no enough products to refund"),
/**
* invalid refund info
*/
CODE_68037(68037, "invalid refund info"),
/**
* shipped but no fast mail info
*/
CODE_68038(68038, "shipped but no fast mail info"),
/**
* invalid wechat pay no
*/
CODE_68039(68039, "invalid wechat pay no"),
/**
* all product has been refunded, the order can not be finished
*/
CODE_68040(68040, "all product has been refunded, the order can not be finished"),
/**
* invalid service create time, it must bigger than the time of order
*/
CODE_68041(68041, "invalid service create time, it must bigger than the time of order"),
/**
* invalid total cost, it must be smaller than the sum of product and shipping cost
*/
CODE_68042(68042, "invalid total cost, it must be smaller than the sum of product and shipping cost"),
/**
* invalid role
*/
CODE_68043(68043, "invalid role"),
/**
* invalid service_available args
*/
CODE_68044(68044, "invalid service_available args"),
/**
* invalid order type
*/
CODE_68045(68045, "invalid order type"),
/**
* invalid order deliver type
*/
CODE_68046(68046, "invalid order deliver type"),
/**
* require store_id
*/
CODE_68500(68500, "require store_id"),
/**
* invalid store_id
*/
CODE_68501(68501, "invalid store_id"),
/**
* invalid parameter, parameter is zero or missing
*/
CODE_71001(71001, "invalid parameter, parameter is zero or missing"),
/**
* invalid orderid, may be the other parameter not fit with orderid
*/
CODE_71002(71002, "invalid orderid, may be the other parameter not fit with orderid"),
/**
* coin not enough
*/
CODE_71003(71003, "coin not enough"),
/**
* card is expired
*/
CODE_71004(71004, "card is expired"),
/**
* limit exe count
*/
CODE_71005(71005, "limit exe count"),
/**
* limit coin count, 1 <= coin_count <= 100000
*/
CODE_71006(71006, "limit coin count, 1 <= coin_count <= 100000"),
/**
* order finish
*/
CODE_71007(71007, "order finish"),
/**
* order time out
*/
CODE_71008(71008, "order time out"),
/**
* no match card
*/
CODE_72001(72001, "no match card"),
/**
* mchid is not bind appid
*/
CODE_72002(72002, "mchid is not bind appid"),
/**
* invalid card type, need member card
*/
CODE_72003(72003, "invalid card type, need member card"),
/**
* mchid is occupied by the other appid
*/
CODE_72004(72004, "mchid is occupied by the other appid"),
/**
* out of mchid size limit
*/
CODE_72005(72005, "out of mchid size limit"),
/**
* invald title
*/
CODE_72006(72006, "invald title"),
/**
* invalid reduce cost, can not less than 100
*/
CODE_72007(72007, "invalid reduce cost, can not less than 100"),
/**
* invalid least cost, most larger than reduce cost
*/
CODE_72008(72008, "invalid least cost, most larger than reduce cost"),
/**
* invalid get limit, can not over 50
*/
CODE_72009(72009, "invalid get limit, can not over 50"),
/**
* invalid mchid
*/
CODE_72010(72010, "invalid mchid"),
/**
* invalid activate_ticket.Maybe this ticket is not belong this AppId
*/
CODE_72011(72011, "invalid activate_ticket.Maybe this ticket is not belong this AppId"),
/**
* activate_ticket has been expired
*/
CODE_72012(72012, "activate_ticket has been expired"),
/**
* unauthorized order_id or authorization is expired
*/
CODE_72013(72013, "unauthorized order_id or authorization is expired"),
/**
* task card share stock can not modify stock
*/
CODE_72014(72014, "task card share stock can not modify stock"),
/**
* unauthorized create invoice
*/
CODE_72015(72015, "unauthorized create invoice"),
/**
* unauthorized create member card
*/
CODE_72016(72016, "unauthorized create member card"),
/**
* invalid invoice title
*/
CODE_72017(72017, "invalid invoice title"),
/**
* duplicate order id, invoice had inserted to user
*/
CODE_72018(72018, "duplicate order id, invoice had inserted to user"),
/**
* limit msg operation card list size, must <= 5
*/
CODE_72019(72019, "limit msg operation card list size, must <= 5"),
/**
* limit consume in use limit
*/
CODE_72020(72020, "limit consume in use limit"),
/**
* unauthorized create general card
*/
CODE_72021(72021, "unauthorized create general card"),
/**
* user unexpected, please add user to white list
*/
CODE_72022(72022, "user unexpected, please add user to white list"),
/**
* invoice has been lock by others
*/
CODE_72023(72023, "invoice has been lock by others"),
/**
* invoice status error
*/
CODE_72024(72024, "invoice status error"),
/**
* invoice token error
*/
CODE_72025(72025, "invoice token error"),
/**
* need set wx_activate true
*/
CODE_72026(72026, "need set wx_activate true"),
/**
* invoice action error
*/
CODE_72027(72027, "invoice action error"),
/**
* invoice never set pay mch info
*/
CODE_72028(72028, "invoice never set pay mch info"),
/**
* invoice never set auth field
*/
CODE_72029(72029, "invoice never set auth field"),
/**
* invalid mchid
*/
CODE_72030(72030, "invalid mchid"),
/**
* invalid params
*/
CODE_72031(72031, "invalid params"),
/**
* pay gift card rule expired
*/
CODE_72032(72032, "pay gift card rule expired"),
/**
* pay gift card rule status err
*/
CODE_72033(72033, "pay gift card rule status err"),
/**
* invlid rule id
*/
CODE_72034(72034, "invlid rule id"),
/**
* biz reject insert
*/
CODE_72035(72035, "biz reject insert"),
/**
* invoice is busy, try again please
*/
CODE_72036(72036, "invoice is busy, try again please"),
/**
* invoice owner error
*/
CODE_72037(72037, "invoice owner error"),
/**
* invoice order never auth
*/
CODE_72038(72038, "invoice order never auth"),
/**
* invoice must be lock first
*/
CODE_72039(72039, "invoice must be lock first"),
/**
* invoice pdf error
*/
CODE_72040(72040, "invoice pdf error"),
/**
* billing_code and billing_no invalid
*/
CODE_72041(72041, "billing_code and billing_no invalid"),
/**
* billing_code and billing_no repeated
*/
CODE_72042(72042, "billing_code and billing_no repeated"),
/**
* billing_code or billing_no size error
*/
CODE_72043(72043, "billing_code or billing_no size error"),
/**
* scan text out of time
*/
CODE_72044(72044, "scan text out of time"),
/**
* check_code is empty
*/
CODE_72045(72045, "check_code is empty"),
/**
* pdf_url is invalid
*/
CODE_72046(72046, "pdf_url is invalid"),
/**
* pdf billing_code or pdf billing_no is error
*/
CODE_72047(72047, "pdf billing_code or pdf billing_no is error"),
/**
* insert too many invoice, need auth again
*/
CODE_72048(72048, "insert too many invoice, need auth again"),
/**
* never auth
*/
CODE_72049(72049, "never auth"),
/**
* auth expired, need auth again
*/
CODE_72050(72050, "auth expired, need auth again"),
/**
* app type error
*/
CODE_72051(72051, "app type error"),
/**
* get too many invoice
*/
CODE_72052(72052, "get too many invoice"),
/**
* user never auth
*/
CODE_72053(72053, "user never auth"),
/**
* invoices is inserting, wait a moment please
*/
CODE_72054(72054, "invoices is inserting, wait a moment please"),
/**
* too many invoices
*/
CODE_72055(72055, "too many invoices"),
/**
* order_id repeated, please check order_id
*/
CODE_72056(72056, "order_id repeated, please check order_id"),
/**
* today insert limit
*/
CODE_72057(72057, "today insert limit"),
/**
* callback biz error
*/
CODE_72058(72058, "callback biz error"),
/**
* this invoice is giving to others, wait a moment please
*/
CODE_72059(72059, "this invoice is giving to others, wait a moment please"),
/**
* this invoice has been cancelled, check the reimburse_status please
*/
CODE_72060(72060, "this invoice has been cancelled, check the reimburse_status please"),
/**
* this invoice has been closed, check the reimburse_status please
*/
CODE_72061(72061, "this invoice has been closed, check the reimburse_status please"),
/**
* this code_auth_key is limited, try other code_auth_key please
*/
CODE_72062(72062, "this code_auth_key is limited, try other code_auth_key please"),
/**
* biz contact is empty, set contact first please
*/
CODE_72063(72063, "biz contact is empty, set contact first please"),
/**
* tbc error
*/
CODE_72064(72064, "tbc error"),
/**
* tbc logic error
*/
CODE_72065(72065, "tbc logic error"),
/**
* the card is send for advertisement, not allow modify time and budget
*/
CODE_72066(72066, "the card is send for advertisement, not allow modify time and budget"),
/**
* BatchInsertAuthKey_Expired
*/
CODE_72067(72067, "BatchInsertAuthKey_Expired"),
/**
* BatchInsertAuthKey_Owner
*/
CODE_72068(72068, "BatchInsertAuthKey_Owner"),
/**
* BATCHTASKRUN_ERROR
*/
CODE_72069(72069, "BATCHTASKRUN_ERROR"),
/**
* BIZ_TITLE_KEY_OUT_TIME
*/
CODE_72070(72070, "BIZ_TITLE_KEY_OUT_TIME"),
/**
* Discern_GaoPeng_Error
*/
CODE_72071(72071, "Discern_GaoPeng_Error"),
/**
* Discern_Type_Error
*/
CODE_72072(72072, "Discern_Type_Error"),
/**
* Fee_Error
*/
CODE_72073(72073, "Fee_Error"),
/**
* HAS_Auth
*/
CODE_72074(72074, "HAS_Auth"),
/**
* HAS_SEND
*/
CODE_72075(72075, "HAS_SEND"),
/**
* INVOICESIGN
*/
CODE_72076(72076, "INVOICESIGN"),
/**
* KEY_DELETED
*/
CODE_72077(72077, "KEY_DELETED"),
/**
* KEY_EXPIRED
*/
CODE_72078(72078, "KEY_EXPIRED"),
/**
* MOUNT_ERROR
*/
CODE_72079(72079, "MOUNT_ERROR"),
/**
* NO_FOUND
*/
CODE_72080(72080, "NO_FOUND"),
/**
* No_Pull_Pdf
*/
CODE_72081(72081, "No_Pull_Pdf"),
/**
* PDF_CHECK_ERROR
*/
CODE_72082(72082, "PDF_CHECK_ERROR"),
/**
* PULL_PDF_FAIL
*/
CODE_72083(72083, "PULL_PDF_FAIL"),
/**
* PUSH_BIZ_EMPTY
*/
CODE_72084(72084, "PUSH_BIZ_EMPTY"),
/**
* SDK_APPID_ERROR
*/
CODE_72085(72085, "SDK_APPID_ERROR"),
/**
* SDK_BIZ_ERROR
*/
CODE_72086(72086, "SDK_BIZ_ERROR"),
/**
* SDK_URL_ERROR
*/
CODE_72087(72087, "SDK_URL_ERROR"),
/**
* Search_Title_Fail
*/
CODE_72088(72088, "Search_Title_Fail"),
/**
* TITLE_BUSY
*/
CODE_72089(72089, "TITLE_BUSY"),
/**
* TITLE_NO_FOUND
*/
CODE_72090(72090, "TITLE_NO_FOUND"),
/**
* TOKEN_ERR
*/
CODE_72091(72091, "TOKEN_ERR"),
/**
* USER_TITLE_NOT_FOUND
*/
CODE_72092(72092, "USER_TITLE_NOT_FOUND"),
/**
* Verify_3rd_Fail
*/
CODE_72093(72093, "Verify_3rd_Fail"),
/**
* sys error make out invoice failed
*/
CODE_73000(73000, "sys error make out invoice failed"),
/**
* wxopenid error
*/
CODE_73001(73001, "wxopenid error"),
/**
* ddh orderid empty
*/
CODE_73002(73002, "ddh orderid empty"),
/**
* wxopenid empty
*/
CODE_73003(73003, "wxopenid empty"),
/**
* fpqqlsh empty
*/
CODE_73004(73004, "fpqqlsh empty"),
/**
* not a commercial
*/
CODE_73005(73005, "not a commercial"),
/**
* kplx empty
*/
CODE_73006(73006, "kplx empty"),
/**
* nsrmc empty
*/
CODE_73007(73007, "nsrmc empty"),
/**
* nsrdz empty
*/
CODE_73008(73008, "nsrdz empty"),
/**
* nsrdh empty
*/
CODE_73009(73009, "nsrdh empty"),
/**
* ghfmc empty
*/
CODE_73010(73010, "ghfmc empty"),
/**
* kpr empty
*/
CODE_73011(73011, "kpr empty"),
/**
* jshj empty
*/
CODE_73012(73012, "jshj empty"),
/**
* hjje empty
*/
CODE_73013(73013, "hjje empty"),
/**
* hjse empty
*/
CODE_73014(73014, "hjse empty"),
/**
* hylx empty
*/
CODE_73015(73015, "hylx empty"),
/**
* nsrsbh empty
*/
CODE_73016(73016, "nsrsbh empty"),
/**
* kaipiao plat error
*/
CODE_73100(73100, "kaipiao plat error"),
/**
* nsrsbh not cmp
*/
CODE_73101(73101, "nsrsbh not cmp"),
/**
* invalid wxa appid in url_cell, wxa appid is need to bind biz appid
*/
CODE_73103(73103, "invalid wxa appid in url_cell, wxa appid is need to bind biz appid"),
/**
* reach frequency limit
*/
CODE_73104(73104, "reach frequency limit"),
/**
* Kp plat make invoice timeout, please try again with the same fpqqlsh
*/
CODE_73105(73105, "Kp plat make invoice timeout, please try again with the same fpqqlsh"),
/**
* Fpqqlsh exist with different ddh
*/
CODE_73106(73106, "Fpqqlsh exist with different ddh"),
/**
* Fpqqlsh is processing, please wait and query later
*/
CODE_73107(73107, "Fpqqlsh is processing, please wait and query later"),
/**
* This ddh with other fpqqlsh already exist
*/
CODE_73108(73108, "This ddh with other fpqqlsh already exist"),
/**
* This Fpqqlsh not exist in kpplat
*/
CODE_73109(73109, "This Fpqqlsh not exist in kpplat"),
/**
* get card detail by card id and code fail
*/
CODE_73200(73200, "get card detail by card id and code fail"),
/**
* get cloud invoice record fail
*/
CODE_73201(73201, "get cloud invoice record fail"),
/**
* get appinfo fail
*/
CODE_73202(73202, "get appinfo fail"),
/**
* get invoice category or rule kv error
*/
CODE_73203(73203, "get invoice category or rule kv error"),
/**
* request card not exist
*/
CODE_73204(73204, "request card not exist"),
/**
* 朋友的券玩法升级中,当前暂停创建,请创建其他类型卡券
*/
CODE_73205(73205, "朋友的券玩法升级中,当前暂停创建,请创建其他类型卡券"),
/**
* 朋友的券玩法升级中,当前暂停券点充值,请创建其他类型卡券
*/
CODE_73206(73206, "朋友的券玩法升级中,当前暂停券点充值,请创建其他类型卡券"),
/**
* 朋友的券玩法升级中,当前暂停开通券点账户
*/
CODE_73207(73207, "朋友的券玩法升级中,当前暂停开通券点账户"),
/**
* 朋友的券玩法升级中,当前不支持修改库存
*/
CODE_73208(73208, "朋友的券玩法升级中,当前不支持修改库存"),
/**
* 朋友的券玩法升级中,当前不支持修改有效期
*/
CODE_73209(73209, "朋友的券玩法升级中,当前不支持修改有效期"),
/**
* 当前批次不支持修改卡券批次库存
*/
CODE_73210(73210, "当前批次不支持修改卡券批次库存"),
/**
* 不再支持配置网页链接跳转,请选择小程序替代
*/
CODE_73211(73211, "不再支持配置网页链接跳转,请选择小程序替代"),
/**
* unauthorized backup member
*/
CODE_73212(73212, "unauthorized backup member"),
/**
* invalid code type
*/
CODE_73213(73213, "invalid code type"),
/**
* the user is already a member
*/
CODE_73214(73214, "the user is already a member"),
/**
* 支付打通券能力已下线,请直接使用微信支付代金券API:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/marketing/convention/chapter1_1.shtml
*/
CODE_73215(73215, "支付打通券能力已下线,请直接使用微信支付代金券API:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/marketing/convention/chapter1_1.shtml"),
/**
* 不合法的按钮名字,请从中选择一个:使用礼品卡/立即使用/去点外卖
*/
CODE_73216(73216, "不合法的按钮名字,请从中选择一个:使用礼品卡/立即使用/去点外卖"),
/**
* 礼品卡本身没有设置appname和path,不允许在修改接口设置
*/
CODE_73217(73217, "礼品卡本身没有设置appname和path,不允许在修改接口设置"),
/**
* 未授权使用礼品卡落地页跳转小程序功能
*/
CODE_73218(73218, "未授权使用礼品卡落地页跳转小程序功能"),
/**
* not find this wx_hotel_id info
*/
CODE_74000(74000, "not find this wx_hotel_id info"),
/**
* request some param empty
*/
CODE_74001(74001, "request some param empty"),
/**
* request some param error
*/
CODE_74002(74002, "request some param error"),
/**
* request some param error
*/
CODE_74003(74003, "request some param error"),
/**
* datetime error
*/
CODE_74004(74004, "datetime error"),
/**
* checkin mode error
*/
CODE_74005(74005, "checkin mode error"),
/**
* carid from error
*/
CODE_74007(74007, "carid from error"),
/**
* this hotel routecode not exist
*/
CODE_74008(74008, "this hotel routecode not exist"),
/**
* this hotel routecode info error contract developer
*/
CODE_74009(74009, "this hotel routecode info error contract developer"),
/**
* maybe not support report mode
*/
CODE_74010(74010, "maybe not support report mode"),
/**
* pic deocde not ok maybe its not good picdata
*/
CODE_74011(74011, "pic deocde not ok maybe its not good picdata"),
/**
* verify sys erro
*/
CODE_74021(74021, "verify sys erro"),
/**
* inner police erro
*/
CODE_74022(74022, "inner police erro"),
/**
* unable to detect the face
*/
CODE_74023(74023, "unable to detect the face"),
/**
* report checkin 2 lvye sys erro
*/
CODE_74040(74040, "report checkin 2 lvye sys erro"),
/**
* report checkou 2 lvye sys erro
*/
CODE_74041(74041, "report checkou 2 lvye sys erro"),
/**
* some param emtpy please check
*/
CODE_75001(75001, "some param emtpy please check"),
/**
* param illegal please check
*/
CODE_75002(75002, "param illegal please check"),
/**
* sys error kv store error
*/
CODE_75003(75003, "sys error kv store error"),
/**
* sys error kvstring store error
*/
CODE_75004(75004, "sys error kvstring store error"),
/**
* product not exist please check your product_id
*/
CODE_75005(75005, "product not exist please check your product_id"),
/**
* order not exist please check order_id and buyer_appid
*/
CODE_75006(75006, "order not exist please check order_id and buyer_appid"),
/**
* do not allow this status to change please check this order_id status now
*/
CODE_75007(75007, "do not allow this status to change please check this order_id status now"),
/**
* product has exist please use new id
*/
CODE_75008(75008, "product has exist please use new id"),
/**
* notify order status failed
*/
CODE_75009(75009, "notify order status failed"),
/**
* buyer bussiness info not exist
*/
CODE_75010(75010, "buyer bussiness info not exist"),
/**
* you had registered
*/
CODE_75011(75011, "you had registered"),
/**
* store image key to kv error, please try again
*/
CODE_75012(75012, "store image key to kv error, please try again"),
/**
* get image fail, please check you image key
*/
CODE_75013(75013, "get image fail, please check you image key"),
/**
* this key is not belong to you
*/
CODE_75014(75014, "this key is not belong to you"),
/**
* this key is expired
*/
CODE_75015(75015, "this key is expired"),
/**
* encrypt decode key fail
*/
CODE_75016(75016, "encrypt decode key fail"),
/**
* encrypt encode key fail
*/
CODE_75017(75017, "encrypt encode key fail"),
/**
* bind buyer business info fail please contact us
*/
CODE_75018(75018, "bind buyer business info fail please contact us"),
/**
* this key is empty, user may not upload file
*/
CODE_75019(75019, "this key is empty, user may not upload file"),
/**
* 系统错误,请稍后再试
*/
CODE_80000(80000, "系统错误,请稍后再试"),
/**
* 参数格式校验错误
*/
CODE_80001(80001, "参数格式校验错误"),
/**
* 签名失败
*/
CODE_80002(80002, "签名失败"),
/**
* 该日期订单未生成
*/
CODE_80003(80003, "该日期订单未生成"),
/**
* 用户未绑卡
*/
CODE_80004(80004, "用户未绑卡"),
/**
* 姓名不符
*/
CODE_80005(80005, "姓名不符"),
/**
* 身份证不符
*/
CODE_80006(80006, "身份证不符"),
/**
* 获取城市信息失败
*/
CODE_80007(80007, "获取城市信息失败"),
/**
* 未找到指定少儿信息
*/
CODE_80008(80008, "未找到指定少儿信息"),
/**
* 少儿身份证不符
*/
CODE_80009(80009, "少儿身份证不符"),
/**
* 少儿未绑定
*/
CODE_80010(80010, "少儿未绑定"),
/**
* 签约号不符
*/
CODE_80011(80011, "签约号不符"),
/**
* 该地区局方配置不存在
*/
CODE_80012(80012, "该地区局方配置不存在"),
/**
* 调用方appid与局方配置不匹配
*/
CODE_80013(80013, "调用方appid与局方配置不匹配"),
/**
* 获取消息账号失败
*/
CODE_80014(80014, "获取消息账号失败"),
/**
* 非法的插件版本
*/
CODE_80066(80066, "非法的插件版本"),
/**
* 找不到使用的插件
*/
CODE_80067(80067, "找不到使用的插件"),
/**
* 没有权限使用该插件
*/
CODE_80082(80082, "没有权限使用该插件"),
/**
* 商家未接入
*/
CODE_80101(80101, "商家未接入"),
/**
* 实名校验code不存在
*/
CODE_80111(80111, "实名校验code不存在"),
/**
* code并发冲突
*/
CODE_80112(80112, "code并发冲突"),
/**
* 无效code
*/
CODE_80113(80113, "无效code"),
/**
* report_type无效
*/
CODE_80201(80201, "report_type无效"),
/**
* service_type无效
*/
CODE_80202(80202, "service_type无效"),
/**
* 申请单不存在
*/
CODE_80300(80300, "申请单不存在"),
/**
* 申请单不属于该账号
*/
CODE_80301(80301, "申请单不属于该账号"),
/**
* 激活号段有重叠
*/
CODE_80302(80302, "激活号段有重叠"),
/**
* 码格式错误
*/
CODE_80303(80303, "码格式错误"),
/**
* 该码未激活
*/
CODE_80304(80304, "该码未激活"),
/**
* 激活失败
*/
CODE_80305(80305, "激活失败"),
/**
* 码索引超出申请范围
*/
CODE_80306(80306, "码索引超出申请范围"),
/**
* 申请已存在
*/
CODE_80307(80307, "申请已存在"),
/**
* 子任务未完成
*/
CODE_80308(80308, "子任务未完成"),
/**
* 子任务文件过期
*/
CODE_80309(80309, "子任务文件过期"),
/**
* 子任务不存在
*/
CODE_80310(80310, "子任务不存在"),
/**
* 获取文件失败
*/
CODE_80311(80311, "获取文件失败"),
/**
* 加密数据失败
*/
CODE_80312(80312, "加密数据失败"),
/**
* 加密数据密钥不存在,请联系接口人申请
*/
CODE_80313(80313, "加密数据密钥不存在,请联系接口人申请"),
/**
* can not set page_id in AddGiftCardPage
*/
CODE_81000(81000, "can not set page_id in AddGiftCardPage"),
/**
* card_list is empty
*/
CODE_81001(81001, "card_list is empty"),
/**
* card_id is not giftcard
*/
CODE_81002(81002, "card_id is not giftcard"),
/**
* banner_pic_url is empty
*/
CODE_81004(81004, "banner_pic_url is empty"),
/**
* banner_pic_url is not from cdn
*/
CODE_81005(81005, "banner_pic_url is not from cdn"),
/**
* giftcard_wrap_pic_url_list is empty
*/
CODE_81006(81006, "giftcard_wrap_pic_url_list is empty"),
/**
* giftcard_wrap_pic_url_list is not from cdn
*/
CODE_81007(81007, "giftcard_wrap_pic_url_list is not from cdn"),
/**
* address is empty
*/
CODE_81008(81008, "address is empty"),
/**
* service_phone is invalid
*/
CODE_81009(81009, "service_phone is invalid"),
/**
* biz_description is empty
*/
CODE_81010(81010, "biz_description is empty"),
/**
* invalid page_id
*/
CODE_81011(81011, "invalid page_id"),
/**
* invalid order_id
*/
CODE_81012(81012, "invalid order_id"),
/**
* invalid TIME_RANGE, begin_time + 31day must less than end_time
*/
CODE_81013(81013, "invalid TIME_RANGE, begin_time + 31day must less than end_time"),
/**
* invalid count! count must equal or less than 100
*/
CODE_81014(81014, "invalid count! count must equal or less than 100"),
/**
* invalid category_index OR category.title is empty OR is_banner but has_category_index
*/
CODE_81015(81015, "invalid category_index OR category.title is empty OR is_banner but has_category_index"),
/**
* is_banner is more than 1
*/
CODE_81016(81016, "is_banner is more than 1"),
/**
* order status error, please check pay status or gifting_status
*/
CODE_81017(81017, "order status error, please check pay status or gifting_status"),
/**
* refund reduplicate, the order is already refunded
*/
CODE_81018(81018, "refund reduplicate, the order is already refunded"),
/**
* lock order fail! the order is refunding by another request
*/
CODE_81019(81019, "lock order fail! the order is refunding by another request"),
/**
* Invalid Args! page_id.size!=0 but all==true, or page_id.size==0 but all==false.
*/
CODE_81020(81020, "Invalid Args! page_id.size!=0 but all==true, or page_id.size==0 but all==false."),
/**
* Empty theme_pic_url.
*/
CODE_81021(81021, "Empty theme_pic_url."),
/**
* Empty theme.title.
*/
CODE_81022(81022, "Empty theme.title."),
/**
* Empty theme.title_title.
*/
CODE_81023(81023, "Empty theme.title_title."),
/**
* Empty theme.item_list.
*/
CODE_81024(81024, "Empty theme.item_list."),
/**
* Empty theme.pic_item_list.
*/
CODE_81025(81025, "Empty theme.pic_item_list."),
/**
* Invalid theme.title.length .
*/
CODE_81026(81026, "Invalid theme.title.length ."),
/**
* Empty background_pic_url.
*/
CODE_81027(81027, "Empty background_pic_url."),
/**
* Empty default_gifting_msg.
*/
CODE_81028(81028, "Empty default_gifting_msg."),
/**
* Duplicate order_id
*/
CODE_81029(81029, "Duplicate order_id"),
/**
* PreAlloc code fail
*/
CODE_81030(81030, "PreAlloc code fail"),
/**
* Too many theme participate_activity
*/
CODE_81031(81031, "Too many theme participate_activity"),
/**
* biz_template_id not exist
*/
CODE_82000(82000, "biz_template_id not exist"),
/**
* result_page_style_id not exist
*/
CODE_82001(82001, "result_page_style_id not exist"),
/**
* deal_msg_style_id not exist
*/
CODE_82002(82002, "deal_msg_style_id not exist"),
/**
* card_style_id not exist
*/
CODE_82003(82003, "card_style_id not exist"),
/**
* biz template not audit OK
*/
CODE_82010(82010, "biz template not audit OK"),
/**
* biz template banned
*/
CODE_82011(82011, "biz template banned"),
/**
* user not use service first
*/
CODE_82020(82020, "user not use service first"),
/**
* exceed long period
*/
CODE_82021(82021, "exceed long period"),
/**
* exceed long period max send cnt
*/
CODE_82022(82022, "exceed long period max send cnt"),
/**
* exceed short period max send cnt
*/
CODE_82023(82023, "exceed short period max send cnt"),
/**
* exceed data size limit
*/
CODE_82024(82024, "exceed data size limit"),
/**
* invalid url
*/
CODE_82025(82025, "invalid url"),
/**
* service disabled
*/
CODE_82026(82026, "service disabled"),
/**
* invalid miniprogram appid
*/
CODE_82027(82027, "invalid miniprogram appid"),
/**
* wx_cs_code should not be empty.
*/
CODE_82100(82100, "wx_cs_code should not be empty."),
/**
* wx_cs_code is invalid.
*/
CODE_82101(82101, "wx_cs_code is invalid."),
/**
* wx_cs_code is expire.
*/
CODE_82102(82102, "wx_cs_code is expire."),
/**
* user_ip should not be empty.
*/
CODE_82103(82103, "user_ip should not be empty."),
/**
* 公众平台账号与服务id不匹配
*/
CODE_82200(82200, "公众平台账号与服务id不匹配"),
/**
* 该停车场已存在,请勿重复添加
*/
CODE_82201(82201, "该停车场已存在,请勿重复添加"),
/**
* 该停车场信息不存在,请先导入
*/
CODE_82202(82202, "该停车场信息不存在,请先导入"),
/**
* 停车场价格格式不正确
*/
CODE_82203(82203, "停车场价格格式不正确"),
/**
* appid与code不匹配
*/
CODE_82204(82204, "appid与code不匹配"),
/**
* wx_park_code字段为空
*/
CODE_82205(82205, "wx_park_code字段为空"),
/**
* wx_park_code无效或已过期
*/
CODE_82206(82206, "wx_park_code无效或已过期"),
/**
* 电话字段为空
*/
CODE_82207(82207, "电话字段为空"),
/**
* 关闭时间格式不正确
*/
CODE_82208(82208, "关闭时间格式不正确"),
/**
* 该appid不支持开通城市服务插件
*/
CODE_82300(82300, "该appid不支持开通城市服务插件"),
/**
* 添加插件失败
*/
CODE_82301(82301, "添加插件失败"),
/**
* 未添加城市服务插件
*/
CODE_82302(82302, "未添加城市服务插件"),
/**
* fileid无效
*/
CODE_82303(82303, "fileid无效"),
/**
* 临时文件过期
*/
CODE_82304(82304, "临时文件过期"),
/**
* there is some param not exist
*/
CODE_83000(83000, "there is some param not exist"),
/**
* system error
*/
CODE_83001(83001, "system error"),
/**
* create_url_sence_failed
*/
CODE_83002(83002, "create_url_sence_failed"),
/**
* appid maybe error or retry
*/
CODE_83003(83003, "appid maybe error or retry"),
/**
* create appid auth failed or retry
*/
CODE_83004(83004, "create appid auth failed or retry"),
/**
* wxwebencrytoken errro
*/
CODE_83005(83005, "wxwebencrytoken errro"),
/**
* wxwebencrytoken expired or no exist
*/
CODE_83006(83006, "wxwebencrytoken expired or no exist"),
/**
* wxwebencrytoken expired
*/
CODE_83007(83007, "wxwebencrytoken expired"),
/**
* wxwebencrytoken no auth
*/
CODE_83008(83008, "wxwebencrytoken no auth"),
/**
* wxwebencrytoken not the mate with openid
*/
CODE_83009(83009, "wxwebencrytoken not the mate with openid"),
/**
* no exist service
*/
CODE_83200(83200, "no exist service"),
/**
* uin has not the service
*/
CODE_83201(83201, "uin has not the service"),
/**
* params is not json or not json array
*/
CODE_83202(83202, "params is not json or not json array"),
/**
* params num exceed 10
*/
CODE_83203(83203, "params num exceed 10"),
/**
* object has not key
*/
CODE_83204(83204, "object has not key"),
/**
* key is not string
*/
CODE_83205(83205, "key is not string"),
/**
* object has not value
*/
CODE_83206(83206, "object has not value"),
/**
* value is not string
*/
CODE_83207(83207, "value is not string"),
/**
* key or value is empty
*/
CODE_83208(83208, "key or value is empty"),
/**
* key exist repeated
*/
CODE_83209(83209, "key exist repeated"),
/**
* invalid identify id
*/
CODE_84001(84001, "invalid identify id"),
/**
* user data expired
*/
CODE_84002(84002, "user data expired"),
/**
* user data not exist
*/
CODE_84003(84003, "user data not exist"),
/**
* video upload fail!
*/
CODE_84004(84004, "video upload fail!"),
/**
* video download fail! please try again
*/
CODE_84005(84005, "video download fail! please try again"),
/**
* name or id_card_number empty
*/
CODE_84006(84006, "name or id_card_number empty"),
/**
* 微信号不存在或微信号设置为不可搜索 user not exist or user cannot be searched
*/
CODE_85001(85001, "微信号不存在或微信号设置为不可搜索"),
/**
* 小程序绑定的体验者数量达到上限 number of tester reach bind limit
*/
CODE_85002(85002, "小程序绑定的体验者数量达到上限"),
/**
* 微信号绑定的小程序体验者达到上限 user already bind too many weapps
*/
CODE_85003(85003, "微信号绑定的小程序体验者达到上限"),
/**
* 微信号已经绑定 user already bind
*/
CODE_85004(85004, "微信号已经绑定"),
/**
* appid not bind weapp
*/
CODE_85005(85005, "appid not bind weapp"),
/**
* 标签格式错误 tag is in invalid format
*/
CODE_85006(85006, "标签格式错误"),
/**
* 页面路径错误 page is in invalid format
*/
CODE_85007(85007, "页面路径错误"),
/**
* 当前小程序没有已经审核通过的类目,请添加类目成功后重试 category is in invalid format
*/
CODE_85008(85008, "当前小程序没有已经审核通过的类目,请添加类目成功后重试"),
/**
* 已经有正在审核的版本 already submit a version under auditing
*/
CODE_85009(85009, "已经有正在审核的版本"),
/**
* item_list 有项目为空 missing required data
*/
CODE_85010(85010, "item_list 有项目为空"),
/**
* 标题填写错误 title is in invalid format
*/
CODE_85011(85011, "标题填写错误"),
/**
* 无效的审核 id invalid audit id
*/
CODE_85012(85012, "无效的审核 id"),
/**
* 无效的自定义配置 invalid ext_json, parse fail or containing invalid path
*/
CODE_85013(85013, "无效的自定义配置"),
/**
* 无效的模板编号 template not exist
*/
CODE_85014(85014, "无效的模板编号"),
/**
* 该账号不是小程序账号/版本输入错误
*/
CODE_85015(85015, "该账号不是小程序账号/版本输入错误"),
/**
* 版本输入错误
*/
// CODE_85015(85015, "版本输入错误"),
/**
* 域名数量超过限制 ,总数不能超过1000 exceed valid domain count
*/
CODE_85016(85016, "域名数量超过限制 ,总数不能超过1000"),
/**
* 没有新增域名,请确认小程序已经添加了域名或该域名是否没有在第三方平台添加 no domain to modify after filtered, please confirm the domain has been set in miniprogram or open
*/
CODE_85017(85017, "没有新增域名,请确认小程序已经添加了域名或该域名是否没有在第三方平台添加"),
/**
* 域名没有在第三方平台设置
*/
CODE_85018(85018, "域名没有在第三方平台设置"),
/**
* 没有审核版本 no version is under auditing
*/
CODE_85019(85019, "没有审核版本"),
/**
* 审核状态未满足发布 status not allowed
*/
CODE_85020(85020, "审核状态未满足发布"),
/**
* status not allowed
*/
CODE_85021(85021, "status not allowed"),
/**
* invalid action
*/
CODE_85022(85022, "invalid action"),
/**
* 审核列表填写的项目数不在 1-5 以内 item size is not in valid range
*/
CODE_85023(85023, "审核列表填写的项目数不在 1-5 以内"),
/**
* need complete material
*/
CODE_85024(85024, "need complete material"),
/**
* this phone reach bind limit
*/
CODE_85025(85025, "this phone reach bind limit"),
/**
* this wechat account reach bind limit
*/
CODE_85026(85026, "this wechat account reach bind limit"),
/**
* this idcard reach bind limit
*/
CODE_85027(85027, "this idcard reach bind limit"),
/**
* this contractor reach bind limit
*/
CODE_85028(85028, "this contractor reach bind limit"),
/**
* nickname has used
*/
CODE_85029(85029, "nickname has used"),
/**
* invalid nickname size(4-30)
*/
CODE_85030(85030, "invalid nickname size(4-30)"),
/**
* nickname is forbidden
*/
CODE_85031(85031, "nickname is forbidden"),
/**
* nickname is complained
*/
CODE_85032(85032, "nickname is complained"),
/**
* nickname is illegal
*/
CODE_85033(85033, "nickname is illegal"),
/**
* nickname is protected
*/
CODE_85034(85034, "nickname is protected"),
/**
* nickname is forbidden for different contractor
*/
CODE_85035(85035, "nickname is forbidden for different contractor"),
/**
* introduction is illegal
*/
CODE_85036(85036, "introduction is illegal"),
/**
* store has added
*/
CODE_85038(85038, "store has added"),
/**
* store has added by others
*/
CODE_85039(85039, "store has added by others"),
/**
* store has added by yourseld
*/
CODE_85040(85040, "store has added by yourseld"),
/**
* credential has used
*/
CODE_85041(85041, "credential has used"),
/**
* nearby reach limit
*/
CODE_85042(85042, "nearby reach limit"),
/**
* 模板错误 invalid template, something wrong?
*/
CODE_85043(85043, "模板错误"),
/**
* 代码包超过大小限制 package exceed max limit
*/
CODE_85044(85044, "代码包超过大小限制"),
/**
* ext_json 有不存在的路径 some path in ext_json not exist
*/
CODE_85045(85045, "ext_json 有不存在的路径"),
/**
* tabBar 中缺少 path pagepath missing in tabbar list
*/
CODE_85046(85046, "tabBar 中缺少 path"),
/**
* pages 字段为空 pages are empty
*/
CODE_85047(85047, "pages 字段为空"),
/**
* ext_json 解析失败 parse ext_json fail
*/
CODE_85048(85048, "ext_json 解析失败"),
/**
* reach headimg or introduction quota limit
*/
CODE_85049(85049, "reach headimg or introduction quota limit"),
/**
* verifying, don't apply again
*/
CODE_85050(85050, "verifying, don't apply again"),
/**
* version_desc或者preview_info超限 data too large
*/
CODE_85051(85051, "version_desc或者preview_info超限"),
/**
* app is already released
*/
CODE_85052(85052, "app is already released"),
/**
* please apply merchant first
*/
CODE_85053(85053, "please apply merchant first"),
/**
* poi_id is null, please upgrade first
*/
CODE_85054(85054, "poi_id is null, please upgrade first"),
/**
* map_poi_id is invalid
*/
CODE_85055(85055, "map_poi_id is invalid"),
/**
* mediaid is invalid
*/
CODE_85056(85056, "mediaid is invalid"),
/**
* invalid widget data format
*/
CODE_85057(85057, "invalid widget data format"),
/**
* no valid audit_id exist
*/
CODE_85058(85058, "no valid audit_id exist"),
/**
* overseas access deny
*/
CODE_85059(85059, "overseas access deny"),
/**
* invalid taskid
*/
CODE_85060(85060, "invalid taskid"),
/**
* this phone reach bind limit
*/
CODE_85061(85061, "this phone reach bind limit"),
/**
* this phone in black list
*/
CODE_85062(85062, "this phone in black list"),
/**
* idcard in black list
*/
CODE_85063(85063, "idcard in black list"),
/**
* 找不到模板 template not found
*/
CODE_85064(85064, "找不到模板"),
/**
* 模板库已满 template list is full
*/
CODE_85065(85065, "模板库已满"),
/**
* 链接错误 illegal prefix
*/
CODE_85066(85066, "链接错误"),
/**
* input data error
*/
CODE_85067(85067, "input data error"),
/**
* 测试链接不是子链接 test url is not the sub prefix
*/
CODE_85068(85068, "测试链接不是子链接"),
/**
* 校验文件失败 check confirm file fail
*/
CODE_85069(85069, "校验文件失败"),
/**
* 个人类型小程序无法设置二维码规则 prefix in black list
*/
CODE_85070(85070, "个人类型小程序无法设置二维码规则"),
/**
* 已添加该链接,请勿重复添加 prefix added repeated
*/
CODE_85071(85071, "已添加该链接,请勿重复添加"),
/**
* 该链接已被占用 prefix owned by other
*/
CODE_85072(85072, "该链接已被占用"),
/**
* 二维码规则已满 prefix beyond limit
*/
CODE_85073(85073, "二维码规则已满"),
/**
* 小程序未发布, 小程序必须先发布代码才可以发布二维码跳转规则 not published
*/
CODE_85074(85074, "小程序未发布, 小程序必须先发布代码才可以发布二维码跳转规则"),
/**
* 个人类型小程序无法设置二维码规则 can not access
*/
CODE_85075(85075, "个人类型小程序无法设置二维码规则"),
/**
* 小程序类目信息失效(类目中含有官方下架的类目,请重新选择类目) some category you choose is no longger supported, please choose other category
*/
CODE_85077(85077, "小程序类目信息失效(类目中含有官方下架的类目,请重新选择类目)"),
/**
* operator info error
*/
CODE_85078(85078, "operator info error"),
/**
* 小程序没有线上版本,不能进行灰度 miniprogram has no online release
*/
CODE_85079(85079, "小程序没有线上版本,不能进行灰度"),
/**
* 小程序提交的审核未审核通过 miniprogram commit not approved
*/
CODE_85080(85080, "小程序提交的审核未审核通过"),
/**
* 无效的发布比例 invalid gray percentage
*/
CODE_85081(85081, "无效的发布比例"),
/**
* 当前的发布比例需要比之前设置的高 gray percentage too low
*/
CODE_85082(85082, "当前的发布比例需要比之前设置的高"),
/**
* 搜索标记位被封禁,无法修改 search status is banned
*/
CODE_85083(85083, "搜索标记位被封禁,无法修改"),
/**
* 非法的 status 值,只能填 0 或者 1 search status invalid
*/
CODE_85084(85084, "非法的 status 值,只能填 0 或者 1"),
/**
* 小程序提审数量已达本月上限,请点击查看 submit audit reach limit pleasetry later
*/
CODE_85085(85085, "小程序提审数量已达本月上限,请点击查看"),
/**
* 提交代码审核之前需提前上传代码 must commit before submit audit
*/
CODE_85086(85086, "提交代码审核之前需提前上传代码"),
/**
* 小程序已使用 api navigateToMiniProgram,请声明跳转 appid 列表后再次提交 navigatetominiprogram appid list empty
*/
CODE_85087(85087, "小程序已使用 api navigateToMiniProgram,请声明跳转 appid 列表后再次提交"),
/**
* no qbase privilege
*/
CODE_85088(85088, "no qbase privilege"),
/**
* config not found
*/
CODE_85089(85089, "config not found"),
/**
* wait and commit for this exappid later
*/
CODE_85090(85090, "wait and commit for this exappid later"),
/**
* 小程序的搜索开关被关闭。请访问设置页面打开开关再重试 search status was turned off
*/
CODE_85091(85091, "小程序的搜索开关被关闭。请访问设置页面打开开关再重试"),
/**
* preview_info格式错误 invalid preview_info format
*/
CODE_85092(85092, "preview_info格式错误"),
/**
* preview_info 视频或者图片个数超限 invalid preview_info size
*/
CODE_85093(85093, "preview_info 视频或者图片个数超限"),
/**
* 需提供审核机制说明信息 need add ugc declare
*/
CODE_85094(85094, "需提供审核机制说明信息"),
/**
* 小程序不能发送该运动类型或运动类型不存在
*/
CODE_85101(85101, "小程序不能发送该运动类型或运动类型不存在"),
/**
* 数值异常
*/
CODE_85102(85102, "数值异常"),
/**
* 不是由第三方代小程序进行调用 should be called only from third party
*/
CODE_86000(86000, "不是由第三方代小程序进行调用"),
/**
* 不存在第三方的已经提交的代码 component experience version not exists
*/
CODE_86001(86001, "不存在第三方的已经提交的代码"),
/**
* 小程序还未设置昵称、头像、简介。请先设置完后再重新提交 miniprogram have not completed init procedure
*/
CODE_86002(86002, "小程序还未设置昵称、头像、简介。请先设置完后再重新提交"),
/**
* component do not has category mall
*/
CODE_86003(86003, "component do not has category mall"),
/**
* invalid wechat
*/
CODE_86004(86004, "invalid wechat"),
/**
* wechat limit frequency
*/
CODE_86005(86005, "wechat limit frequency"),
/**
* has no quota to send group msg
*/
CODE_86006(86006, "has no quota to send group msg"),
/**
* 小程序禁止提交
*/
CODE_86007(86007, "小程序禁止提交"),
/**
* 服务商被处罚,限制全部代码提审能力
*/
CODE_86008(86008, "服务商被处罚,限制全部代码提审能力"),
/**
* 服务商新增小程序代码提审能力被限制
*/
CODE_86009(86009, "服务商新增小程序代码提审能力被限制"),
/**
* 服务商迭代小程序代码提审能力被限制
*/
CODE_86010(86010, "服务商迭代小程序代码提审能力被限制"),
/**
* 小游戏不能提交 this is game miniprogram, submit audit is forbidden
*/
CODE_87006(87006, "小游戏不能提交"),
/**
* session_key is not existd or expired
*/
CODE_87007(87007, "session_key is not existd or expired"),
/**
* invalid sig_method
*/
CODE_87008(87008, "invalid sig_method"),
/**
* 无效的签名 invalid signature
*/
CODE_87009(87009, "无效的签名"),
/**
* invalid buffer size
*/
CODE_87010(87010, "invalid buffer size"),
/**
* 现网已经在灰度发布,不能进行版本回退 wxa has a gray release plan, forbid revert release
*/
CODE_87011(87011, "现网已经在灰度发布,不能进行版本回退"),
/**
* 该版本不能回退,可能的原因:1:无上一个线上版用于回退 2:此版本为已回退版本,不能回退 3:此版本为回退功能上线之前的版本,不能回退 forbid revert this version release
*/
CODE_87012(87012, "该版本不能回退,可能的原因:1:无上一个线上版用于回退 2:此版本为已回退版本,不能回退 3:此版本为回退功能上线之前的版本,不能回退"),
/**
* 撤回次数达到上限(每天5次,每个月 10 次) no quota to undo code
*/
CODE_87013(87013, "撤回次数达到上限(每天5次,每个月 10 次)"),
/**
* risky content
*/
CODE_87014(87014, "risky content"),
/**
* query timeout, try a content with less size
*/
CODE_87015(87015, "query timeout, try a content with less size"),
/**
* some key-value in list meet length exceed
*/
CODE_87016(87016, "some key-value in list meet length exceed"),
/**
* user storage size exceed, delete some keys and try again
*/
CODE_87017(87017, "user storage size exceed, delete some keys and try again"),
/**
* user has stored too much keys. delete some keys and try again
*/
CODE_87018(87018, "user has stored too much keys. delete some keys and try again"),
/**
* some keys in list meet length exceed
*/
CODE_87019(87019, "some keys in list meet length exceed"),
/**
* need friend
*/
CODE_87080(87080, "need friend"),
/**
* invalid openid
*/
CODE_87081(87081, "invalid openid"),
/**
* invalid key
*/
CODE_87082(87082, "invalid key"),
/**
* invalid operation
*/
CODE_87083(87083, "invalid operation"),
/**
* invalid opnum
*/
CODE_87084(87084, "invalid opnum"),
/**
* check fail
*/
CODE_87085(87085, "check fail"),
/**
* without comment privilege
*/
CODE_88000(88000, "without comment privilege"),
/**
* msg_data is not exists
*/
CODE_88001(88001, "msg_data is not exists"),
/**
* the article is limit for safety
*/
CODE_88002(88002, "the article is limit for safety"),
/**
* elected comment upper limit
*/
CODE_88003(88003, "elected comment upper limit"),
/**
* comment was deleted by user
*/
CODE_88004(88004, "comment was deleted by user"),
/**
* already reply
*/
CODE_88005(88005, "already reply"),
/**
* reply content beyond max len or content len is zero
*/
CODE_88007(88007, "reply content beyond max len or content len is zero"),
/**
* comment is not exists
*/
CODE_88008(88008, "comment is not exists"),
/**
* reply is not exists
*/
CODE_88009(88009, "reply is not exists"),
/**
* count range error. cout <= 0 or count > 50
*/
CODE_88010(88010, "count range error. cout <= 0 or count > 50"),
/**
* the article is limit for safety
*/
CODE_88011(88011, "the article is limit for safety"),
/**
* account has bound open,该公众号/小程序已经绑定了开放平台帐号 account has bound open
*/
CODE_89000(89000, "account has bound open,该公众号/小程序已经绑定了开放平台帐号"),
/**
* not same contractor,Authorizer 与开放平台帐号主体不相同 not same contractor
*/
CODE_89001(89001, "not same contractor,Authorizer 与开放平台帐号主体不相同"),
/**
* open not exists,该公众号/小程序未绑定微信开放平台帐号。 open not exists
*/
CODE_89002(89002, "open not exists,该公众号/小程序未绑定微信开放平台帐号。"),
/**
* 该开放平台帐号并非通过 api 创建,不允许操作 open is not created by api
*/
CODE_89003(89003, "该开放平台帐号并非通过 api 创建,不允许操作"),
/**
* 该开放平台帐号所绑定的公众号/小程序已达上限(100 个)
*/
CODE_89004(89004, "该开放平台帐号所绑定的公众号/小程序已达上限(100 个)"),
/**
* without add video ability, the ability was banned
*/
CODE_89005(89005, "without add video ability, the ability was banned"),
/**
* without upload video ability, the ability was banned
*/
CODE_89006(89006, "without upload video ability, the ability was banned"),
/**
* wxa quota limit
*/
CODE_89007(89007, "wxa quota limit"),
/**
* overseas account can not link
*/
CODE_89008(89008, "overseas account can not link"),
/**
* wxa reach link limit
*/
CODE_89009(89009, "wxa reach link limit"),
/**
* link message has sent
*/
CODE_89010(89010, "link message has sent"),
/**
* can not unlink nearby wxa
*/
CODE_89011(89011, "can not unlink nearby wxa"),
/**
* can not unlink store or mall
*/
CODE_89012(89012, "can not unlink store or mall"),
/**
* wxa is banned
*/
CODE_89013(89013, "wxa is banned"),
/**
* support version error
*/
CODE_89014(89014, "support version error"),
/**
* has linked wxa
*/
CODE_89015(89015, "has linked wxa"),
/**
* reach same realname quota
*/
CODE_89016(89016, "reach same realname quota"),
/**
* reach different realname quota
*/
CODE_89017(89017, "reach different realname quota"),
/**
* unlink message has sent
*/
CODE_89018(89018, "unlink message has sent"),
/**
* 业务域名无更改,无需重复设置 webview domain not change
*/
CODE_89019(89019, "业务域名无更改,无需重复设置"),
/**
* 尚未设置小程序业务域名,请先在第三方平台中设置小程序业务域名后在调用本接口 open's webview domain is null! Need to set open's webview domain first!
*/
CODE_89020(89020, "尚未设置小程序业务域名,请先在第三方平台中设置小程序业务域名后在调用本接口"),
/**
* 请求保存的域名不是第三方平台中已设置的小程序业务域名或子域名 request domain is not open's webview domain!
*/
CODE_89021(89021, "请求保存的域名不是第三方平台中已设置的小程序业务域名或子域名"),
/**
* delete domain is not exist!
*/
CODE_89022(89022, "delete domain is not exist!"),
/**
* 业务域名数量超过限制,最多可以添加100个业务域名 webview domain exceed limit
*/
CODE_89029(89029, "业务域名数量超过限制,最多可以添加100个业务域名"),
/**
* operation reach month limit
*/
CODE_89030(89030, "operation reach month limit"),
/**
* user bind reach limit
*/
CODE_89031(89031, "user bind reach limit"),
/**
* weapp bind members reach limit
*/
CODE_89032(89032, "weapp bind members reach limit"),
/**
* empty wx or openid
*/
CODE_89033(89033, "empty wx or openid"),
/**
* userstr is invalid
*/
CODE_89034(89034, "userstr is invalid"),
/**
* linking from mp
*/
CODE_89035(89035, "linking from mp"),
/**
* 个人小程序不支持调用 setwebviewdomain 接口 not support single
*/
CODE_89231(89231, "个人小程序不支持调用 setwebviewdomain 接口"),
/**
* hit black contractor
*/
CODE_89235(89235, "hit black contractor"),
/**
* 该插件不能申请 this plugin can not apply
*/
CODE_89236(89236, "该插件不能申请"),
/**
* 已经添加该插件 plugin has send apply message or already bind
*/
CODE_89237(89237, "已经添加该插件"),
/**
* 申请或使用的插件已经达到上限 plugin count reach limit
*/
CODE_89238(89238, "申请或使用的插件已经达到上限"),
/**
* 该插件不存在 plugin no exist
*/
CODE_89239(89239, "该插件不存在"),
/**
* only applying status can be agreed or refused
*/
CODE_89240(89240, "only applying status can be agreed or refused"),
/**
* only refused status can be deleted, please refused first
*/
CODE_89241(89241, "only refused status can be deleted, please refused first"),
/**
* appid is no in the apply list, make sure appid is right
*/
CODE_89242(89242, "appid is no in the apply list, make sure appid is right"),
/**
* 该申请为“待确认”状态,不可删除 can not delete apply request in 24 hours
*/
CODE_89243(89243, "该申请为“待确认”状态,不可删除"),
/**
* 不存在该插件 appid plugin appid is no in the plugin list, make sure plugin appid is right
*/
CODE_89244(89244, "不存在该插件 appid"),
/**
* mini program forbidden to link
*/
CODE_89245(89245, "mini program forbidden to link"),
/**
* plugins with special category are used only by specific apps
*/
CODE_89246(89246, "plugins with special category are used only by specific apps"),
/**
* 系统内部错误 inner error, retry after some while
*/
CODE_89247(89247, "系统内部错误"),
/**
* invalid code type
*/
CODE_89248(89248, "invalid code type"),
/**
* task running
*/
CODE_89249(89249, "task running"),
/**
* 内部错误 inner error, retry after some while
*/
CODE_89250(89250, "内部错误"),
/**
* 模板消息已下发,待法人人脸核身校验 legal person checking
*/
CODE_89251(89251, "模板消息已下发,待法人人脸核身校验"),
/**
* 法人&企业信息一致性校验中 front checking
*/
CODE_89253(89253, "法人&企业信息一致性校验中"),
/**
* lack of some component rights
*/
CODE_89254(89254, "lack of some component rights"),
/**
* code参数无效,请检查code长度以及内容是否正确;注意code_type的值不同需要传的code长度不一样 enterprise code invalid
*/
CODE_89255(89255, "code参数无效,请检查code长度以及内容是否正确;注意code_type的值不同需要传的code长度不一样"),
/**
* token 信息有误 no component info
*/
CODE_89256(89256, "token 信息有误"),
/**
* 该插件版本不支持快速更新 no such version
*/
CODE_89257(89257, "该插件版本不支持快速更新"),
/**
* 当前小程序帐号存在灰度发布中的版本,不可操作快速更新 code is gray online
*/
CODE_89258(89258, "当前小程序帐号存在灰度发布中的版本,不可操作快速更新"),
/**
* zhibo plugin is not allow to delete
*/
CODE_89259(89259, "zhibo plugin is not allow to delete"),
/**
* 订单无效 invalid trade
*/
CODE_89300(89300, "订单无效"),
/**
* 系统不稳定,请稍后再试,如多次失败请通过社区反馈
*/
CODE_89401(89401, "系统不稳定,请稍后再试,如多次失败请通过社区反馈"),
/**
* 该小程序不在待审核队列,请检查是否已提交审核或已审完
*/
CODE_89402(89402, "该小程序不在待审核队列,请检查是否已提交审核或已审完"),
/**
* 本单属于平台不支持加急种类,请等待正常审核流程
*/
CODE_89403(89403, "本单属于平台不支持加急种类,请等待正常审核流程"),
/**
* 本单已加速成功,请勿重复提交
*/
CODE_89404(89404, "本单已加速成功,请勿重复提交"),
/**
* 本月加急额度已用完,请提高提审质量以获取更多额度
*/
CODE_89405(89405, "本月加急额度已用完,请提高提审质量以获取更多额度"),
/**
* 公众号有未处理的确认请求,请稍候重试
*/
CODE_89501(89501, "公众号有未处理的确认请求,请稍候重试"),
/**
* 请耐心等待管理员确认
*/
CODE_89502(89502, "请耐心等待管理员确认"),
/**
* 此次调用需要管理员确认,请耐心等候
*/
CODE_89503(89503, "此次调用需要管理员确认,请耐心等候"),
/**
* 正在等管理员确认,请耐心等待
*/
CODE_89504(89504, "正在等管理员确认,请耐心等待"),
/**
* 正在等管理员确认,请稍候重试
*/
CODE_89505(89505, "正在等管理员确认,请稍候重试"),
/**
* 该IP调用求请求已被公众号管理员拒绝,请24小时后再试,建议调用前与管理员沟通确认
*/
CODE_89506(89506, "该IP调用求请求已被公众号管理员拒绝,请24小时后再试,建议调用前与管理员沟通确认"),
/**
* 该IP调用求请求已被公众号管理员拒绝,请1小时后再试,建议调用前与管理员沟通确认
*/
CODE_89507(89507, "该IP调用求请求已被公众号管理员拒绝,请1小时后再试,建议调用前与管理员沟通确认"),
/**
* invalid order id
*/
CODE_90001(90001, "invalid order id"),
/**
* invalid busi id
*/
CODE_90002(90002, "invalid busi id"),
/**
* invalid bill date
*/
CODE_90003(90003, "invalid bill date"),
/**
* invalid bill type
*/
CODE_90004(90004, "invalid bill type"),
/**
* invalid platform
*/
CODE_90005(90005, "invalid platform"),
/**
* bill not exists
*/
CODE_90006(90006, "bill not exists"),
/**
* invalid openid
*/
CODE_90007(90007, "invalid openid"),
/**
* mp_sig error
*/
CODE_90009(90009, "mp_sig error"),
/**
* no session
*/
CODE_90010(90010, "no session"),
/**
* sig error
*/
CODE_90011(90011, "sig error"),
/**
* order exist
*/
CODE_90012(90012, "order exist"),
/**
* balance not enough
*/
CODE_90013(90013, "balance not enough"),
/**
* order has been confirmed
*/
CODE_90014(90014, "order has been confirmed"),
/**
* order has been canceled
*/
CODE_90015(90015, "order has been canceled"),
/**
* order is being processed
*/
CODE_90016(90016, "order is being processed"),
/**
* no privilege
*/
CODE_90017(90017, "no privilege"),
/**
* invalid parameter
*/
CODE_90018(90018, "invalid parameter"),
/**
* 不是公众号快速创建的小程序 not fast register
*/
CODE_91001(91001, "不是公众号快速创建的小程序"),
/**
* 小程序发布后不可改名 has published
*/
CODE_91002(91002, "小程序发布后不可改名"),
/**
* 改名状态不合法 invalid change stat
*/
CODE_91003(91003, "改名状态不合法"),
/**
* 昵称不合法 invalid nickname
*/
CODE_91004(91004, "昵称不合法"),
/**
* 昵称 15 天主体保护 nickname protected
*/
CODE_91005(91005, "昵称 15 天主体保护"),
/**
* 昵称命中微信号 nickname used by username
*/
CODE_91006(91006, "昵称命中微信号"),
/**
* 昵称已被占用 nickname used
*/
CODE_91007(91007, "昵称已被占用"),
/**
* 昵称命中 7 天侵权保护期 nickname protected
*/
CODE_91008(91008, "昵称命中 7 天侵权保护期"),
/**
* 需要提交材料 nickname need proof
*/
CODE_91009(91009, "需要提交材料"),
/**
* 其他错误
*/
CODE_91010(91010, "其他错误"),
/**
* 查不到昵称修改审核单信息
*/
CODE_91011(91011, "查不到昵称修改审核单信息"),
/**
* 其它错误
*/
CODE_91012(91012, "其它错误"),
/**
* 占用名字过多 lock name too more
*/
CODE_91013(91013, "占用名字过多"),
/**
* +号规则 同一类型关联名主体不一致 diff master plus
*/
CODE_91014(91014, "+号规则 同一类型关联名主体不一致"),
/**
* 原始名不同类型主体不一致 diff master
*/
CODE_91015(91015, "原始名不同类型主体不一致"),
/**
* 名称占用者 ≥2 name more owner
*/
CODE_91016(91016, "名称占用者 ≥2"),
/**
* +号规则 不同类型关联名主体不一致 other diff master plus
*/
CODE_91017(91017, "+号规则 不同类型关联名主体不一致"),
/**
* 组织类型小程序发布后,侵权被清空昵称,需走认证改名
*/
CODE_91018(91018, "组织类型小程序发布后,侵权被清空昵称,需走认证改名"),
/**
* 小程序正在审核中
*/
CODE_91019(91019, "小程序正在审核中"),
/**
* 该经营资质已添加,请勿重复添加
*/
CODE_92000(92000, "该经营资质已添加,请勿重复添加"),
/**
* 附近地点添加数量达到上线,无法继续添加
*/
CODE_92002(92002, "附近地点添加数量达到上线,无法继续添加"),
/**
* 地点已被其它小程序占用
*/
CODE_92003(92003, "地点已被其它小程序占用"),
/**
* 附近功能被封禁
*/
CODE_92004(92004, "附近功能被封禁"),
/**
* 地点正在审核中
*/
CODE_92005(92005, "地点正在审核中"),
/**
* 地点正在展示小程序
*/
CODE_92006(92006, "地点正在展示小程序"),
/**
* 地点审核失败
*/
CODE_92007(92007, "地点审核失败"),
/**
* 小程序未展示在该地点
*/
CODE_92008(92008, "小程序未展示在该地点"),
/**
* 小程序未上架或不可见
*/
CODE_93009(93009, "小程序未上架或不可见"),
/**
* 地点不存在
*/
CODE_93010(93010, "地点不存在"),
/**
* 个人类型小程序不可用
*/
CODE_93011(93011, "个人类型小程序不可用"),
/**
* 非普通类型小程序(门店小程序、小店小程序等)不可用
*/
CODE_93012(93012, "非普通类型小程序(门店小程序、小店小程序等)不可用"),
/**
* 从腾讯地图获取地址详细信息失败
*/
CODE_93013(93013, "从腾讯地图获取地址详细信息失败"),
/**
* 同一资质证件号重复添加
*/
CODE_93014(93014, "同一资质证件号重复添加"),
/**
* 附近类目审核中
*/
CODE_93015(93015, "附近类目审核中"),
/**
* 服务标签个数超限制(官方最多5个,自定义最多4个)
*/
CODE_93016(93016, "服务标签个数超限制(官方最多5个,自定义最多4个)"),
/**
* 服务标签或者客服的名字不符合要求
*/
CODE_93017(93017, "服务标签或者客服的名字不符合要求"),
/**
* 服务能力中填写的小程序appid不是同主体小程序
*/
CODE_93018(93018, "服务能力中填写的小程序appid不是同主体小程序"),
/**
* 申请类目之后才能添加附近地点
*/
CODE_93019(93019, "申请类目之后才能添加附近地点"),
/**
* qualification_list无效
*/
CODE_93020(93020, "qualification_list无效"),
/**
* company_name字段为空
*/
CODE_93021(93021, "company_name字段为空"),
/**
* credential字段为空
*/
CODE_93022(93022, "credential字段为空"),
/**
* address字段为空
*/
CODE_93023(93023, "address字段为空"),
/**
* qualification_list字段为空
*/
CODE_93024(93024, "qualification_list字段为空"),
/**
* 服务appid对应的path不存在
*/
CODE_93025(93025, "服务appid对应的path不存在"),
/**
* missing cert_serialno
*/
CODE_94001(94001, "missing cert_serialno"),
/**
* use not register wechat pay
*/
CODE_94002(94002, "use not register wechat pay"),
/**
* invalid sign
*/
CODE_94003(94003, "invalid sign"),
/**
* user do not has real name info
*/
CODE_94004(94004, "user do not has real name info"),
/**
* invalid user token
*/
CODE_94005(94005, "invalid user token"),
/**
* appid unauthorized
*/
CODE_94006(94006, "appid unauthorized"),
/**
* appid unbind mchid
*/
CODE_94007(94007, "appid unbind mchid"),
/**
* invalid timestamp
*/
CODE_94008(94008, "invalid timestamp"),
/**
* invalid cert_serialno, cert_serialno's size should be 40
*/
CODE_94009(94009, "invalid cert_serialno, cert_serialno's size should be 40"),
/**
* invalid mch_id
*/
CODE_94010(94010, "invalid mch_id"),
/**
* timestamp expired
*/
CODE_94011(94011, "timestamp expired"),
/**
* appid和商户号的绑定关系不存在
*/
CODE_94012(94012, "appid和商户号的绑定关系不存在"),
/**
* wxcode decode fail
*/
CODE_95001(95001, "wxcode decode fail"),
/**
* wxcode recognize unautuorized
*/
CODE_95002(95002, "wxcode recognize unautuorized"),
/**
* get product by page args invalid
*/
CODE_95101(95101, "get product by page args invalid"),
/**
* get product materials by cond args invalid
*/
CODE_95102(95102, "get product materials by cond args invalid"),
/**
* material id list size out of limit
*/
CODE_95103(95103, "material id list size out of limit"),
/**
* import product frequence out of limit
*/
CODE_95104(95104, "import product frequence out of limit"),
/**
* mp is importing products, api is rejected to import
*/
CODE_95105(95105, "mp is importing products, api is rejected to import"),
/**
* api is rejected to import, need to set commission ratio on mp first
*/
CODE_95106(95106, "api is rejected to import, need to set commission ratio on mp first"),
/**
* invalid image url
*/
CODE_101000(101000, "无效图片链接"),
/**
* certificate not found
*/
CODE_101001(101001, "未找到证书"),
/**
* not enough market quota
*/
CODE_101002(101002, "not enough market quota"),
/**
* 入参错误
*/
CODE_200002(200002, "入参错误"),
/**
* 此账号已被封禁,无法操作
*/
CODE_200011(200011, "此账号已被封禁,无法操作"),
/**
* 个人模板数已达上限,上限25个
*/
CODE_200012(200012, "个人模板数已达上限,上限25个"),
/**
* 此模板已被封禁,无法选用
*/
CODE_200013(200013, "此模板已被封禁,无法选用"),
/**
* 模板 tid 参数错误
*/
CODE_200014(200014, "模板 tid 参数错误"),
/**
* start 参数错误
*/
CODE_200016(200016, "start 参数错误"),
/**
* limit 参数错误
*/
CODE_200017(200017, "limit 参数错误"),
/**
* 类目 ids 缺失
*/
CODE_200018(200018, "类目 ids 缺失"),
/**
* 类目 ids 不合法
*/
CODE_200019(200019, "类目 ids 不合法"),
/**
* 关键词列表 kidList 参数错误
*/
CODE_200020(200020, "关键词列表 kidList 参数错误"),
/**
* 场景描述 sceneDesc 参数错误
*/
CODE_200021(200021, "场景描述 sceneDesc 参数错误"),
/**
* 禁止创建/更新商品(如商品创建功能被封禁) 或 禁止编辑&更新房间
*/
CODE_300001(300001, "禁止创建/更新商品(如商品创建功能被封禁) 或 禁止编辑&更新房间"),
/**
* 名称长度不符合规则
*/
CODE_300002(300002, "名称长度不符合规则"),
/**
* 价格输入不合规(如现价比原价大、传入价格非数字等)
*/
CODE_300003(300003, "价格输入不合规(如现价比原价大、传入价格非数字等)"),
/**
* 商品名称存在违规违法内容
*/
CODE_300004(300004, "商品名称存在违规违法内容"),
/**
* 商品图片存在违规违法内容
*/
CODE_300005(300005, "商品图片存在违规违法内容"),
/**
* 图片上传失败(如mediaID过期)
*/
CODE_300006(300006, "图片上传失败(如mediaID过期)"),
/**
* 线上小程序版本不存在该链接
*/
CODE_300007(300007, "线上小程序版本不存在该链接"),
/**
* 添加商品失败
*/
CODE_300008(300008, "添加商品失败"),
/**
* 商品审核撤回失败
*/
CODE_300009(300009, "商品审核撤回失败"),
/**
* 商品审核状态不对(如商品审核中)
*/
CODE_300010(300010, "商品审核状态不对(如商品审核中)"),
/**
* 操作非法(API不允许操作非API创建的商品)
*/
CODE_300011(300011, "操作非法(API不允许操作非API创建的商品)"),
/**
* 没有提审额度(每天500次提审额度)
*/
CODE_300012(300012, "没有提审额度(每天500次提审额度)"),
/**
* 提审失败
*/
CODE_300013(300013, "提审失败"),
/**
* 审核中,无法删除(非零代表失败)
*/
CODE_300014(300014, "审核中,无法删除(非零代表失败)"),
/**
* 商品未提审
*/
CODE_300017(300017, "商品未提审"),
/**
* 商品添加成功,审核失败
*/
CODE_300021(300021, "商品添加成功,审核失败"),
/**
* 此房间号不存在
*/
CODE_300022(300022, "此房间号不存在"),
/**
* 房间状态 拦截(当前房间状态不允许此操作)
*/
CODE_300023(300023, "房间状态 拦截(当前房间状态不允许此操作)"),
/**
* 商品不存在
*/
CODE_300024(300024, "商品不存在"),
/**
* 商品审核未通过
*/
CODE_300025(300025, "商品审核未通过"),
/**
* 房间商品数量已经满额
*/
CODE_300026(300026, "房间商品数量已经满额"),
/**
* 导入商品失败
*/
CODE_300027(300027, "导入商品失败"),
/**
* 房间名称违规
*/
CODE_300028(300028, "房间名称违规"),
/**
* 主播昵称违规
*/
CODE_300029(300029, "主播昵称违规"),
/**
* 主播微信号不合法
*/
CODE_300030(300030, "主播微信号不合法"),
/**
* 直播间封面图不合规
*/
CODE_300031(300031, "直播间封面图不合规"),
/**
* 直播间分享图违规
*/
CODE_300032(300032, "直播间分享图违规"),
/**
* 添加商品超过直播间上限
*/
CODE_300033(300033, "添加商品超过直播间上限"),
/**
* 主播微信昵称长度不符合要求
*/
CODE_300034(300034, "主播微信昵称长度不符合要求"),
/**
* 主播微信号不存在
*/
CODE_300035(300035, "主播微信号不存在"),
/**
* 主播微信号未实名认证
*/
CODE_300036(300036, "主播微信号未实名认证"),
/**
* invalid file name
*/
CODE_600001(600001, "invalid file name"),
/**
* no permission to upload file
*/
CODE_600002(600002, "no permission to upload file"),
/**
* invalid size of source
*/
CODE_600003(600003, "invalid size of source"),
/**
* 票据已存在
*/
CODE_928000(928000, "票据已存在"),
/**
* 票据不存在
*/
CODE_928001(928001, "票据不存在"),
/**
* sysem error
*/
CODE_930555(930555, "sysem error"),
/**
* delivery timeout
*/
CODE_930556(930556, "delivery timeout"),
/**
* delivery system error
*/
CODE_930557(930557, "delivery system error"),
/**
* delivery logic error
*/
CODE_930558(930558, "delivery logic error"),
/**
* 沙盒环境openid无效 invaild openid
*/
CODE_930559(930559, "沙盒环境openid无效"),
/**
* shopid need bind first
*/
CODE_930560(930560, "shopid need bind first"),
/**
* 参数错误 args error
*/
CODE_930561(930561, "参数错误"),
/**
* order already exists
*/
CODE_930562(930562, "order already exists"),
/**
* 订单不存在 order not exists
*/
CODE_930563(930563, "订单不存在"),
/**
* 沙盒环境调用无配额 quota run out, try next day
*/
CODE_930564(930564, "沙盒环境调用无配额"),
/**
* order finished
*/
CODE_930565(930565, "order finished"),
/**
* not support, plz auth at mp.weixin.qq.com
*/
CODE_930566(930566, "not support, plz auth at mp.weixin.qq.com"),
/**
* shop arg error
*/
CODE_930567(930567, "shop arg error"),
/**
* 不支持个人类型小程序 not personal account
*/
CODE_930568(930568, "不支持个人类型小程序"),
/**
* 已经开通不需要再开通 already open
*/
CODE_930569(930569, "已经开通不需要再开通"),
/**
* cargo_first_class or cargo_second_class invalid
*/
CODE_930570(930570, "cargo_first_class or cargo_second_class invalid"),
/**
* 该商户没有内测权限,请先申请权限: https://wj.qq.com/s2/7243532/fcfb/
*/
CODE_930571(930571, "该商户没有内测权限,请先申请权限: https://wj.qq.com/s2/7243532/fcfb/"),
/**
* fee already set
*/
CODE_931010(931010, "fee already set"),
/**
* unbind download url
*/
CODE_6000100(6000100, "unbind download url"),
/**
* no response data
*/
CODE_6000101(6000101, "no response data"),
/**
* response data too big
*/
CODE_6000102(6000102, "response data too big"),
/**
* POST 数据参数不合法
*/
CODE_9001001(9001001, "POST 数据参数不合法"),
/**
* 远端服务不可用
*/
CODE_9001002(9001002, "远端服务不可用"),
/**
* Ticket 不合法
*/
CODE_9001003(9001003, "Ticket 不合法"),
/**
* 获取摇周边用户信息失败
*/
CODE_9001004(9001004, "获取摇周边用户信息失败"),
/**
* 获取商户信息失败
*/
CODE_9001005(9001005, "获取商户信息失败"),
/**
* 获取 OpenID 失败
*/
CODE_9001006(9001006, "获取 OpenID 失败"),
/**
* 上传文件缺失
*/
CODE_9001007(9001007, "上传文件缺失"),
/**
* 上传素材的文件类型不合法
*/
CODE_9001008(9001008, "上传素材的文件类型不合法"),
/**
* 上传素材的文件尺寸不合法
*/
CODE_9001009(9001009, "上传素材的文件尺寸不合法"),
/**
* 上传失败
*/
CODE_9001010(9001010, "上传失败"),
/**
* 帐号不合法
*/
CODE_9001020(9001020, "帐号不合法"),
/**
* 已有设备激活率低于 50% ,不能新增设备
*/
CODE_9001021(9001021, "已有设备激活率低于 50% ,不能新增设备"),
/**
* 设备申请数不合法,必须为大于 0 的数字
*/
CODE_9001022(9001022, "设备申请数不合法,必须为大于 0 的数字"),
/**
* 已存在审核中的设备 ID 申请
*/
CODE_9001023(9001023, "已存在审核中的设备 ID 申请"),
/**
* 一次查询设备 ID 数量不能超过 50
*/
CODE_9001024(9001024, "一次查询设备 ID 数量不能超过 50"),
/**
* 设备 ID 不合法
*/
CODE_9001025(9001025, "设备 ID 不合法"),
/**
* 页面 ID 不合法
*/
CODE_9001026(9001026, "页面 ID 不合法"),
/**
* 页面参数不合法
*/
CODE_9001027(9001027, "页面参数不合法"),
/**
* 一次删除页面 ID 数量不能超过 10
*/
CODE_9001028(9001028, "一次删除页面 ID 数量不能超过 10"),
/**
* 页面已应用在设备中,请先解除应用关系再删除
*/
CODE_9001029(9001029, "页面已应用在设备中,请先解除应用关系再删除"),
/**
* 一次查询页面 ID 数量不能超过 50
*/
CODE_9001030(9001030, "一次查询页面 ID 数量不能超过 50"),
/**
* 时间区间不合法
*/
CODE_9001031(9001031, "时间区间不合法"),
/**
* 保存设备与页面的绑定关系参数错误
*/
CODE_9001032(9001032, "保存设备与页面的绑定关系参数错误"),
/**
* 门店 ID 不合法
*/
CODE_9001033(9001033, "门店 ID 不合法"),
/**
* 设备备注信息过长
*/
CODE_9001034(9001034, "设备备注信息过长"),
/**
* 设备申请参数不合法
*/
CODE_9001035(9001035, "设备申请参数不合法"),
/**
* 查询起始值 begin 不合法
*/
CODE_9001036(9001036, "查询起始值 begin 不合法"),
/**
* params invalid
*/
CODE_9002008(9002008, "params invalid"),
/**
* shop id not exist
*/
CODE_9002009(9002009, "shop id not exist"),
/**
* ssid or password should start with "WX"
*/
CODE_9002010(9002010, "ssid or password should start with \"WX\""),
/**
* ssid can not include chinese
*/
CODE_9002011(9002011, "ssid can not include chinese"),
/**
* passsword can not include chinese
*/
CODE_9002012(9002012, "passsword can not include chinese"),
/**
* password must be between 8 and 24 characters
*/
CODE_9002013(9002013, "password must be between 8 and 24 characters"),
/**
* device exist
*/
CODE_9002016(9002016, "device exist"),
/**
* device not exist
*/
CODE_9002017(9002017, "device not exist"),
/**
* the size of query list reach limit
*/
CODE_9002026(9002026, "the size of query list reach limit"),
/**
* not allowed to modify, ensure you are an certified or component account
*/
CODE_9002041(9002041, "not allowed to modify, ensure you are an certified or component account"),
/**
* invalid ssid, can not include none utf8 characters, and should be between 1 and 32 bytes
*/
CODE_9002044(9002044, "invalid ssid, can not include none utf8 characters, and should be between 1 and 32 bytes"),
/**
* shop id has not be audited, this bar type is not enable
*/
CODE_9002052(9002052, "shop id has not be audited, this bar type is not enable"),
/**
* protocol type is not same with the exist device
*/
CODE_9007003(9007003, "protocol type is not same with the exist device"),
/**
* ssid not exist
*/
CODE_9007004(9007004, "ssid not exist"),
/**
* device count limit
*/
CODE_9007005(9007005, "device count limit"),
/**
* card info not exist
*/
CODE_9008001(9008001, "card info not exist"),
/**
* card expiration time is invalid
*/
CODE_9008002(9008002, "card expiration time is invalid"),
/**
* url size invalid, keep less than 255
*/
CODE_9008003(9008003, "url size invalid, keep less than 255"),
/**
* url can not include chinese
*/
CODE_9008004(9008004, "url can not include chinese"),
/**
* order_id not exist
*/
CODE_9200001(9200001, "order_id not exist"),
/**
* order of other biz
*/
CODE_9200002(9200002, "order of other biz"),
/**
* blocked
*/
CODE_9200003(9200003, "blocked"),
/**
* payment notice disabled
*/
CODE_9200211(9200211, "payment notice disabled"),
/**
* payment notice not exist
*/
CODE_9200231(9200231, "payment notice not exist"),
/**
* payment notice paid
*/
CODE_9200232(9200232, "payment notice paid"),
/**
* payment notice canceled
*/
CODE_9200233(9200233, "payment notice canceled"),
/**
* payment notice expired
*/
CODE_9200235(9200235, "payment notice expired"),
/**
* bank not allow
*/
CODE_9200236(9200236, "bank not allow"),
/**
* freq limit
*/
CODE_9200295(9200295, "freq limit"),
/**
* suspend payment at current time
*/
CODE_9200297(9200297, "suspend payment at current time"),
/**
* 3rd resp decrypt error
*/
CODE_9200298(9200298, "3rd resp decrypt error"),
/**
* 3rd resp system error
*/
CODE_9200299(9200299, "3rd resp system error"),
/**
* 3rd resp sign error
*/
CODE_9200300(9200300, "3rd resp sign error"),
/**
* desc empty
*/
CODE_9201000(9201000, "desc empty"),
/**
* fee not equal items'
*/
CODE_9201001(9201001, "fee not equal items'"),
/**
* payment info incorrect
*/
CODE_9201002(9201002, "payment info incorrect"),
/**
* fee is 0
*/
CODE_9201003(9201003, "fee is 0"),
/**
* payment expire date format error
*/
CODE_9201004(9201004, "payment expire date format error"),
/**
* appid error
*/
CODE_9201005(9201005, "appid error"),
/**
* payment order id error
*/
CODE_9201006(9201006, "payment order id error"),
/**
* openid error
*/
CODE_9201007(9201007, "openid error"),
/**
* return_url error
*/
CODE_9201008(9201008, "return_url error"),
/**
* ip error
*/
CODE_9201009(9201009, "ip error"),
/**
* order_id error
*/
CODE_9201010(9201010, "order_id error"),
/**
* reason error
*/
CODE_9201011(9201011, "reason error"),
/**
* mch_id error
*/
CODE_9201012(9201012, "mch_id error"),
/**
* bill_date error
*/
CODE_9201013(9201013, "bill_date error"),
/**
* bill_type error
*/
CODE_9201014(9201014, "bill_type error"),
/**
* trade_type error
*/
CODE_9201015(9201015, "trade_type error"),
/**
* bank_id error
*/
CODE_9201016(9201016, "bank_id error"),
/**
* bank_account error
*/
CODE_9201017(9201017, "bank_account error"),
/**
* payment_notice_no error
*/
CODE_9201018(9201018, "payment_notice_no error"),
/**
* department_code error
*/
CODE_9201019(9201019, "department_code error"),
/**
* payment_notice_type error
*/
CODE_9201020(9201020, "payment_notice_type error"),
/**
* region_code error
*/
CODE_9201021(9201021, "region_code error"),
/**
* department_name error
*/
CODE_9201022(9201022, "department_name error"),
/**
* fee not equal finance's
*/
CODE_9201023(9201023, "fee not equal finance's"),
/**
* refund_out_id error
*/
CODE_9201024(9201024, "refund_out_id error"),
/**
* not combined order_id
*/
CODE_9201026(9201026, "not combined order_id"),
/**
* partial sub order is test
*/
CODE_9201027(9201027, "partial sub order is test"),
/**
* desc too long
*/
CODE_9201029(9201029, "desc too long"),
/**
* sub order list size error
*/
CODE_9201031(9201031, "sub order list size error"),
/**
* sub order repeated
*/
CODE_9201032(9201032, "sub order repeated"),
/**
* auth_code empty
*/
CODE_9201033(9201033, "auth_code empty"),
/**
* bank_id empty but mch_id not empty
*/
CODE_9201034(9201034, "bank_id empty but mch_id not empty"),
/**
* sum of other fees exceed total fee
*/
CODE_9201035(9201035, "sum of other fees exceed total fee"),
/**
* other user paying
*/
CODE_9202000(9202000, "other user paying"),
/**
* pay process not finish
*/
CODE_9202001(9202001, "pay process not finish"),
/**
* no refund permission
*/
CODE_9202002(9202002, "no refund permission"),
/**
* ip limit
*/
CODE_9202003(9202003, "ip limit"),
/**
* freq limit
*/
CODE_9202004(9202004, "freq limit"),
/**
* user weixin account abnormal
*/
CODE_9202005(9202005, "user weixin account abnormal"),
/**
* account balance not enough
*/
CODE_9202006(9202006, "account balance not enough"),
/**
* refund request repeated
*/
CODE_9202010(9202010, "refund request repeated"),
/**
* has refunded
*/
CODE_9202011(9202011, "has refunded"),
/**
* refund exceed total fee
*/
CODE_9202012(9202012, "refund exceed total fee"),
/**
* busi_id dup
*/
CODE_9202013(9202013, "busi_id dup"),
/**
* not check sign
*/
CODE_9202016(9202016, "not check sign"),
/**
* check sign failed
*/
CODE_9202017(9202017, "check sign failed"),
/**
* sub order error
*/
CODE_9202018(9202018, "sub order error"),
/**
* order status error
*/
CODE_9202020(9202020, "order status error"),
/**
* unified order repeatedly
*/
CODE_9202021(9202021, "unified order repeatedly"),
/**
* request to notification url fail
*/
CODE_9203000(9203000, "request to notification url fail"),
/**
* http request fail
*/
CODE_9203001(9203001, "http request fail"),
/**
* http response data error
*/
CODE_9203002(9203002, "http response data error"),
/**
* http response data RSA decrypt fail
*/
CODE_9203003(9203003, "http response data RSA decrypt fail"),
/**
* http response data AES decrypt fail
*/
CODE_9203004(9203004, "http response data AES decrypt fail"),
/**
* system busy, please try again later
*/
CODE_9203999(9203999, "system busy, please try again later"),
/**
* getrealname token error
*/
CODE_9204000(9204000, "getrealname token error"),
/**
* getrealname user or token error
*/
CODE_9204001(9204001, "getrealname user or token error"),
/**
* getrealname appid or token error
*/
CODE_9204002(9204002, "getrealname appid or token error"),
/**
* finance conf not exist
*/
CODE_9205000(9205000, "finance conf not exist"),
/**
* bank conf not exist
*/
CODE_9205001(9205001, "bank conf not exist"),
/**
* wei ban ju conf not exist
*/
CODE_9205002(9205002, "wei ban ju conf not exist"),
/**
* symmetric key conf not exist
*/
CODE_9205010(9205010, "symmetric key conf not exist"),
/**
* out order id not exist
*/
CODE_9205101(9205101, "out order id not exist"),
/**
* bill not exist
*/
CODE_9205201(9205201, "bill not exist"),
/**
* 3rd resp pay_channel empty
*/
CODE_9206000(9206000, "3rd resp pay_channel empty"),
/**
* 3rd resp order_id empty
*/
CODE_9206001(9206001, "3rd resp order_id empty"),
/**
* 3rd resp bill_type_code empty
*/
CODE_9206002(9206002, "3rd resp bill_type_code empty"),
/**
* 3rd resp bill_no empty
*/
CODE_9206003(9206003, "3rd resp bill_no empty"),
/**
* 3rd resp empty
*/
CODE_9206200(9206200, "3rd resp empty"),
/**
* 3rd resp not json
*/
CODE_9206201(9206201, "3rd resp not json"),
/**
* connect 3rd error
*/
CODE_9206900(9206900, "connect 3rd error"),
/**
* connect 3rd timeout
*/
CODE_9206901(9206901, "connect 3rd timeout"),
/**
* read 3rd resp error
*/
CODE_9206910(9206910, "read 3rd resp error"),
/**
* read 3rd resp timeout
*/
CODE_9206911(9206911, "read 3rd resp timeout"),
/**
* boss error
*/
CODE_9207000(9207000, "boss error"),
/**
* wechat pay error
*/
CODE_9207001(9207001, "wechat pay error"),
/**
* boss param error
*/
CODE_9207002(9207002, "boss param error"),
/**
* pay error
*/
CODE_9207003(9207003, "pay error"),
/**
* auth_code expired
*/
CODE_9207004(9207004, "auth_code expired"),
/**
* user balance not enough
*/
CODE_9207005(9207005, "user balance not enough"),
/**
* card not support
*/
CODE_9207006(9207006, "card not support"),
/**
* order reversed
*/
CODE_9207007(9207007, "order reversed"),
/**
* user paying, need input password
*/
CODE_9207008(9207008, "user paying, need input password"),
/**
* auth_code error
*/
CODE_9207009(9207009, "auth_code error"),
/**
* auth_code invalid
*/
CODE_9207010(9207010, "auth_code invalid"),
/**
* not allow to reverse when user paying
*/
CODE_9207011(9207011, "not allow to reverse when user paying"),
/**
* order paid
*/
CODE_9207012(9207012, "order paid"),
/**
* order closed
*/
CODE_9207013(9207013, "order closed"),
/**
* vehicle not exists
*/
CODE_9207028(9207028, "vehicle not exists"),
/**
* vehicle request blocked
*/
CODE_9207029(9207029, "vehicle request blocked"),
/**
* vehicle auth error
*/
CODE_9207030(9207030, "vehicle auth error"),
/**
* contract over limit
*/
CODE_9207031(9207031, "contract over limit"),
/**
* trade error
*/
CODE_9207032(9207032, "trade error"),
/**
* trade time invalid
*/
CODE_9207033(9207033, "trade time invalid"),
/**
* channel type invalid
*/
CODE_9207034(9207034, "channel type invalid"),
/**
* expire_time range error
*/
CODE_9207050(9207050, "expire_time range error"),
/**
* query finance error
*/
CODE_9210000(9210000, "query finance error"),
/**
* openid error
*/
CODE_9291000(9291000, "openid error"),
/**
* openid appid not match
*/
CODE_9291001(9291001, "openid appid not match"),
/**
* app_appid not exist
*/
CODE_9291002(9291002, "app_appid not exist"),
/**
* app_appid not app
*/
CODE_9291003(9291003, "app_appid not app"),
/**
* appid empty
*/
CODE_9291004(9291004, "appid empty"),
/**
* appid not match access_token
*/
CODE_9291005(9291005, "appid not match access_token"),
/**
* invalid sign
*/
CODE_9291006(9291006, "invalid sign"),
/**
* backend logic error
*/
CODE_9299999(9299999, "backend logic error"),
/**
* begin_time can not before now
*/
CODE_9300001(9300001, "begin_time can not before now"),
/**
* end_time can not before now
*/
CODE_9300002(9300002, "end_time can not before now"),
/**
* begin_time must less than end_time
*/
CODE_9300003(9300003, "begin_time must less than end_time"),
/**
* end_time - begin_time > 1year
*/
CODE_9300004(9300004, "end_time - begin_time > 1year"),
/**
* invalid max_partic_times
*/
CODE_9300005(9300005, "invalid max_partic_times"),
/**
* invalid activity status
*/
CODE_9300006(9300006, "invalid activity status"),
/**
* gift_num must >0 and <=15
*/
CODE_9300007(9300007, "gift_num must >0 and <=15"),
/**
* invalid tiny appid
*/
CODE_9300008(9300008, "invalid tiny appid"),
/**
* activity can not finish
*/
CODE_9300009(9300009, "activity can not finish"),
/**
* card_info_list must >= 2
*/
CODE_9300010(9300010, "card_info_list must >= 2"),
/**
* invalid card_id
*/
CODE_9300011(9300011, "invalid card_id"),
/**
* card_id must belong this appid
*/
CODE_9300012(9300012, "card_id must belong this appid"),
/**
* card_id is not swipe_card or pay.cash
*/
CODE_9300013(9300013, "card_id is not swipe_card or pay.cash"),
/**
* some card_id is out of stock
*/
CODE_9300014(9300014, "some card_id is out of stock"),
/**
* some card_id is invalid status
*/
CODE_9300015(9300015, "some card_id is invalid status"),
/**
* membership or new/old tinyapp user only support one
*/
CODE_9300016(9300016, "membership or new/old tinyapp user only support one"),
/**
* invalid logic for membership
*/
CODE_9300017(9300017, "invalid logic for membership"),
/**
* invalid logic for tinyapp new/old user
*/
CODE_9300018(9300018, "invalid logic for tinyapp new/old user"),
/**
* invalid activity type
*/
CODE_9300019(9300019, "invalid activity type"),
/**
* invalid activity_id
*/
CODE_9300020(9300020, "invalid activity_id"),
/**
* invalid help_max_times
*/
CODE_9300021(9300021, "invalid help_max_times"),
/**
* invalid cover_url
*/
CODE_9300022(9300022, "invalid cover_url"),
/**
* invalid gen_limit
*/
CODE_9300023(9300023, "invalid gen_limit"),
/**
* card's end_time cannot early than act's end_time
*/
CODE_9300024(9300024, "card's end_time cannot early than act's end_time"),
/**
* 快递侧逻辑错误,详细原因需要看 delivery_resultcode, 请先确认一下编码方式,python建议 json.dumps(b, ensure_ascii=False),php建议 json_encode($arr, JSON_UNESCAPED_UNICODE) Delivery side error
*/
CODE_9300501(9300501, "快递侧逻辑错误,详细原因需要看 delivery_resultcode, 请先确认一下编码方式,python建议 json.dumps(b, ensure_ascii=False),php建议 json_encode($arr, JSON_UNESCAPED_UNICODE)"),
/**
* 快递公司系统错误 Delivery side sys error
*/
CODE_9300502(9300502, "快递公司系统错误"),
/**
* delivery_id 不存在 Specified delivery id is not registerred
*/
CODE_9300503(9300503, "delivery_id 不存在"),
/**
* service_type 不存在 Specified delivery id has beed banned
*/
CODE_9300504(9300504, "service_type 不存在"),
/**
* Shop banned
*/
CODE_9300505(9300505, "Shop banned"),
/**
* 运单 ID 已经存在轨迹,不可取消 Order can't cancel
*/
CODE_9300506(9300506, "运单 ID 已经存在轨迹,不可取消"),
/**
* Token 不正确 invalid token, can't decryption or decryption result is different from the plaintext
*/
CODE_9300507(9300507, "Token 不正确"),
/**
* order id has been used
*/
CODE_9300508(9300508, "order id has been used"),
/**
* speed limit, retry too fast
*/
CODE_9300509(9300509, "speed limit, retry too fast"),
/**
* invalid service type
*/
CODE_9300510(9300510, "invalid service type"),
/**
* invalid branch id
*/
CODE_9300511(9300511, "invalid branch id"),
/**
* 模板格式错误,渲染失败 invalid waybill template format
*/
CODE_9300512(9300512, "模板格式错误,渲染失败"),
/**
* out of quota
*/
CODE_9300513(9300513, "out of quota"),
/**
* add net branch fail, try update branch api
*/
CODE_9300514(9300514, "add net branch fail, try update branch api"),
/**
* wxa appid not exist
*/
CODE_9300515(9300515, "wxa appid not exist"),
/**
* wxa appid and current bizuin is not linked or not the same owner
*/
CODE_9300516(9300516, "wxa appid and current bizuin is not linked or not the same owner"),
/**
* update_type 不正确,请使用"bind" 或者“unbind” invalid update_type, please use [bind] or [unbind]
*/
CODE_9300517(9300517, "update_type 不正确,请使用\"bind\" 或者“unbind”"),
/**
* invalid delivery id
*/
CODE_9300520(9300520, "invalid delivery id"),
/**
* the orderid is in our system, and waybill is generating
*/
CODE_9300521(9300521, "the orderid is in our system, and waybill is generating"),
/**
* this orderid is repeated
*/
CODE_9300522(9300522, "this orderid is repeated"),
/**
* quota is not enough; go to charge please
*/
CODE_9300523(9300523, "quota is not enough; go to charge please"),
/**
* 订单已取消(一般为重复取消订单) order already canceled
*/
CODE_9300524(9300524, "订单已取消(一般为重复取消订单)"),
/**
* bizid未绑定 biz id not bind
*/
CODE_9300525(9300525, "bizid未绑定"),
/**
* 参数字段长度不正确 arg size exceed limit
*/
CODE_9300526(9300526, "参数字段长度不正确"),
/**
* delivery does not support quota
*/
CODE_9300527(9300527, "delivery does not support quota"),
/**
* invalid waybill_id
*/
CODE_9300528(9300528, "invalid waybill_id"),
/**
* 账号已绑定过 biz_id already binded
*/
CODE_9300529(9300529, "账号已绑定过"),
/**
* 解绑的biz_id不存在 biz_id is not exist
*/
CODE_9300530(9300530, "解绑的biz_id不存在"),
/**
* bizid无效 或者密码错误 invalid biz_id or password
*/
CODE_9300531(9300531, "bizid无效 或者密码错误"),
/**
* 绑定已提交,审核中 bind submit, and is checking
*/
CODE_9300532(9300532, "绑定已提交,审核中"),
/**
* invalid tagid_list
*/
CODE_9300533(9300533, "invalid tagid_list"),
/**
* add_source=2时,wx_appid和当前小程序不同主体 invalid appid, not same body
*/
CODE_9300534(9300534, "add_source=2时,wx_appid和当前小程序不同主体"),
/**
* shop字段商品缩略图 url、商品名称为空或者非法,或者商品数量为0 invalid shop arg
*/
CODE_9300535(9300535, "shop字段商品缩略图 url、商品名称为空或者非法,或者商品数量为0"),
/**
* add_source=2时,wx_appid无效 invalid wxa_appid
*/
CODE_9300536(9300536, "add_source=2时,wx_appid无效"),
/**
* freq limit
*/
CODE_9300537(9300537, "freq limit"),
/**
* input task empty
*/
CODE_9300538(9300538, "input task empty"),
/**
* too many task
*/
CODE_9300539(9300539, "too many task"),
/**
* task not exist
*/
CODE_9300540(9300540, "task not exist"),
/**
* delivery callback error
*/
CODE_9300541(9300541, "delivery callback error"),
/**
* id_card_no is invalid
*/
CODE_9300601(9300601, "id_card_no is invalid"),
/**
* name is invalid
*/
CODE_9300602(9300602, "name is invalid"),
/**
* plate_no is invalid
*/
CODE_9300603(9300603, "plate_no is invalid"),
/**
* auth_key decode error
*/
CODE_9300604(9300604, "auth_key decode error"),
/**
* auth_key is expired
*/
CODE_9300605(9300605, "auth_key is expired"),
/**
* auth_key and appinfo not match
*/
CODE_9300606(9300606, "auth_key and appinfo not match"),
/**
* user not confirm
*/
CODE_9300607(9300607, "user not confirm"),
/**
* user confirm is expired
*/
CODE_9300608(9300608, "user confirm is expired"),
/**
* api exceed limit
*/
CODE_9300609(9300609, "api exceed limit"),
/**
* car license info is invalid
*/
CODE_9300610(9300610, "car license info is invalid"),
/**
* varification type not support
*/
CODE_9300611(9300611, "varification type not support"),
/**
* input param error
*/
CODE_9300701(9300701, "input param error"),
/**
* this code has been used
*/
CODE_9300702(9300702, "this code has been used"),
/**
* invalid date
*/
CODE_9300703(9300703, "invalid date"),
/**
* not currently available
*/
CODE_9300704(9300704, "not currently available"),
/**
* code not exist or expired
*/
CODE_9300705(9300705, "code not exist or expired"),
/**
* code not exist or expired
*/
CODE_9300706(9300706, "code not exist or expired"),
/**
* wxpay error
*/
CODE_9300707(9300707, "wxpay error"),
/**
* wxpay overlimit
*/
CODE_9300708(9300708, "wxpay overlimit"),
/**
* 无效的微信号
*/
CODE_9300801(9300801, "无效的微信号"),
/**
* 服务号未开通导购功能
*/
CODE_9300802(9300802, "服务号未开通导购功能"),
/**
* 微信号已经绑定为导购
*/
CODE_9300803(9300803, "微信号已经绑定为导购"),
/**
* 该微信号不是导购
*/
CODE_9300804(9300804, "该微信号不是导购"),
/**
* 微信号已经被其他账号绑定为导购
*/
CODE_9300805(9300805, "微信号已经被其他账号绑定为导购"),
/**
* 粉丝和导购不存在绑定关系
*/
CODE_9300806(9300806, "粉丝和导购不存在绑定关系"),
/**
* 标签值无效,不是可选标签值
*/
CODE_9300807(9300807, "标签值无效,不是可选标签值"),
/**
* 标签值不存在
*/
CODE_9300808(9300808, "标签值不存在"),
/**
* 展示标签值不存在
*/
CODE_9300809(9300809, "展示标签值不存在"),
/**
* 导购昵称太长,最多16个字符
*/
CODE_9300810(9300810, "导购昵称太长,最多16个字符"),
/**
* 只支持mmbiz.qpic.cn域名的图片
*/
CODE_9300811(9300811, "只支持mmbiz.qpic.cn域名的图片"),
/**
* 达到导购绑定个数限制
*/
CODE_9300812(9300812, "达到导购绑定个数限制"),
/**
* 达到导购粉丝绑定个数限制
*/
CODE_9300813(9300813, "达到导购粉丝绑定个数限制"),
/**
* 敏感词个数超过上限
*/
CODE_9300814(9300814, "敏感词个数超过上限"),
/**
* 快捷回复个数超过上限
*/
CODE_9300815(9300815, "快捷回复个数超过上限"),
/**
* 文字素材个数超过上限
*/
CODE_9300816(9300816, "文字素材个数超过上限"),
/**
* 小程序卡片素材个数超过上限
*/
CODE_9300817(9300817, "小程序卡片素材个数超过上限"),
/**
* 图片素材个数超过上限
*/
CODE_9300818(9300818, "图片素材个数超过上限"),
/**
* mediaid 有误
*/
CODE_9300819(9300819, "mediaid 有误"),
/**
* 可查询标签类别超过上限
*/
CODE_9300820(9300820, "可查询标签类别超过上限"),
/**
* 小程序卡片内appid不符合要求
*/
CODE_9300821(9300821, "小程序卡片内appid不符合要求"),
/**
* 标签类别的名字无效
*/
CODE_9300822(9300822, "标签类别的名字无效"),
/**
* 查询聊天记录时间参数有误
*/
CODE_9300823(9300823, "查询聊天记录时间参数有误"),
/**
* 自动回复字数太长
*/
CODE_9300824(9300824, "自动回复字数太长"),
/**
* 导购群组id错误
*/
CODE_9300825(9300825, "导购群组id错误"),
/**
* 维护中
*/
CODE_9300826(9300826, "维护中"),
/**
* invalid parameter
*/
CODE_9301001(9301001, "invalid parameter"),
/**
* call api service failed
*/
CODE_9301002(9301002, "call api service failed"),
/**
* internal exception
*/
CODE_9301003(9301003, "internal exception"),
/**
* save data error
*/
CODE_9301004(9301004, "save data error"),
/**
* invalid appid
*/
CODE_9301006(9301006, "invalid appid"),
/**
* invalid api config
*/
CODE_9301007(9301007, "invalid api config"),
/**
* invalid api info
*/
CODE_9301008(9301008, "invalid api info"),
/**
* add result check failed
*/
CODE_9301009(9301009, "add result check failed"),
/**
* consumption failure
*/
CODE_9301010(9301010, "consumption failure"),
/**
* frequency limit reached
*/
CODE_9301011(9301011, "frequency limit reached"),
/**
* service timeout
*/
CODE_9301012(9301012, "service timeout"),
/**
* 该开发小程序已开通小程序直播权限,不支持发布版本。如需发版,请解绑开发小程序后再操作。
*/
CODE_9400001(9400001, "该开发小程序已开通小程序直播权限,不支持发布版本。如需发版,请解绑开发小程序后再操作。"),
/**
* 商品已存在
*/
CODE_9401001(9401001, "商品已存在"),
/**
* 商品不存在
*/
CODE_9401002(9401002, "商品不存在"),
/**
* 类目已存在
*/
CODE_9401003(9401003, "类目已存在"),
/**
* 类目不存在
*/
CODE_9401004(9401004, "类目不存在"),
/**
* SKU已存在
*/
CODE_9401005(9401005, "SKU已存在"),
/**
* SKU不存在
*/
CODE_9401006(9401006, "SKU不存在"),
/**
* 属性已存在
*/
CODE_9401007(9401007, "属性已存在"),
/**
* 属性不存在
*/
CODE_9401008(9401008, "属性不存在"),
/**
* 非法参数
*/
CODE_9401020(9401020, "非法参数"),
/**
* 没有商品权限
*/
CODE_9401021(9401021, "没有商品权限"),
/**
* SPU NOT ALLOW
*/
CODE_9401022(9401022, "SPU NOT ALLOW"),
/**
* SPU_NOT_ALLOW_EDIT
*/
CODE_9401023(9401023, "SPU_NOT_ALLOW_EDIT"),
/**
* SKU NOT ALLOW
*/
CODE_9401024(9401024, "SKU NOT ALLOW"),
/**
* SKU_NOT_ALLOW_EDIT
*/
CODE_9401025(9401025, "SKU_NOT_ALLOW_EDIT"),
/**
* limit too large
*/
CODE_9402001(9402001, "limit too large"),
/**
* single send been blocked
*/
CODE_9402002(9402002, "single send been blocked"),
/**
* all send been blocked
*/
CODE_9402003(9402003, "all send been blocked"),
/**
* invalid msg id
*/
CODE_9402004(9402004, "invalid msg id"),
/**
* send msg too quick
*/
CODE_9402005(9402005, "send msg too quick"),
/**
* send to single user too quick
*/
CODE_9402006(9402006, "send to single user too quick"),
/**
* send to all user too quick
*/
CODE_9402007(9402007, "send to all user too quick"),
/**
* send type error
*/
CODE_9402008(9402008, "send type error"),
/**
* can not send this msg
*/
CODE_9402009(9402009, "can not send this msg"),
/**
* content too long or no content
*/
CODE_9402010(9402010, "content too long or no content"),
/**
* path not exist
*/
CODE_9402011(9402011, "path not exist"),
/**
* contain evil word
*/
CODE_9402012(9402012, "contain evil word"),
/**
* path need html suffix
*/
CODE_9402013(9402013, "path need html suffix"),
/**
* not open to personal body type
*/
CODE_9402014(9402014, "not open to personal body type"),
/**
* not open to violation body type
*/
CODE_9402015(9402015, "not open to violation body type"),
/**
* not open to low quality provider
*/
CODE_9402016(9402016, "not open to low quality provider"),
/**
* invalid product_id
*/
CODE_9402101(9402101, "invalid product_id"),
/**
* device_id count more than limit
*/
CODE_9402102(9402102, "device_id count more than limit"),
/**
* 请勿频繁提交,待上一次操作完成后再提交 concurrent limit
*/
CODE_9402202(9402202, "请勿频繁提交,待上一次操作完成后再提交"),
/**
* user not book this ad id
*/
CODE_9402301(9402301, "user not book this ad id"),
/**
* 消息类型错误!
*/
CODE_9403000(9403000, "消息类型错误!"),
/**
* 消息字段的内容过长!
*/
CODE_9403001(9403001, "消息字段的内容过长!"),
/**
* 消息字段的内容违规!
*/
CODE_9403002(9403002, "消息字段的内容违规!"),
/**
* 发送的微信号太多!
*/
CODE_9403003(9403003, "发送的微信号太多!"),
/**
* 存在错误的微信号!
*/
CODE_9403004(9403004, "存在错误的微信号!"),
/**
* 直播间列表为空 live room not exsits
*/
CODE_9410000(9410000, "直播间列表为空"),
/**
* 获取房间失败 inner error: get room fail
*/
CODE_9410001(9410001, "获取房间失败"),
/**
* 获取商品失败 inner error: get goods fail
*/
CODE_9410002(9410002, "获取商品失败"),
/**
* 获取回放失败 inner error: get replay url fail
*/
CODE_9410003(9410003, "获取回放失败");
private final int code;
private final String msg;
WxOpenErrorMsgEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
static final Map<Integer, String> valueMap = Maps.newHashMap();
static {
for (WxOpenErrorMsgEnum value : WxOpenErrorMsgEnum.values()) {
valueMap.put(value.code, value.msg);
}
}
/**
* 通过错误代码查找其中文含义.
*/
public static String findMsgByCode(int code) {
return valueMap.getOrDefault(code, null);
}
}
| Wechat-Group/WxJava | weixin-java-common/src/main/java/me/chanjar/weixin/common/error/WxOpenErrorMsgEnum.java |
45,316 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2011 The ZAP Development Team
*
* 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.zaproxy.zap.extension.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.apache.commons.httpclient.URI;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.network.HttpHeader;
import org.zaproxy.zap.extension.api.API.Format;
import org.zaproxy.zap.extension.api.API.RequestType;
public class WebUI {
private API api;
private boolean isDevTestNonce = false; // Manually change here to test nonces with the web UI
private static final String PAC_FILE_API_PATH = "/OTHER/network/other/proxy.pac/";
private static final String ROOT_CA_CERT_API_PATH = "/OTHER/network/other/rootCaCert/";
public WebUI(API api) {
this.api = api;
}
private ApiElement getElement(ApiImplementor impl, String name, RequestType reqType)
throws ApiException {
if (RequestType.action.equals(reqType) && name != null) {
// Action form
List<ApiAction> actionList = impl.getApiActions();
ApiAction action = null;
for (ApiAction act : actionList) {
if (name.equals(act.getName())) {
action = act;
break;
}
}
if (action == null) {
throw new ApiException(ApiException.Type.BAD_ACTION);
}
return action;
} else if (RequestType.other.equals(reqType) && name != null) {
// Other form
List<ApiOther> otherList = impl.getApiOthers();
ApiOther other = null;
for (ApiOther oth : otherList) {
if (name.equals(oth.getName())) {
other = oth;
break;
}
}
if (other == null) {
throw new ApiException(ApiException.Type.BAD_OTHER);
}
return other;
} else if (RequestType.view.equals(reqType) && name != null) {
List<ApiView> viewList = impl.getApiViews();
ApiView view = null;
for (ApiView v : viewList) {
if (name.equals(v.getName())) {
view = v;
break;
}
}
if (view == null) {
throw new ApiException(ApiException.Type.BAD_VIEW);
}
return view;
} else if (RequestType.pconn.equals(reqType) && name != null) {
List<ApiPersistentConnection> pconnList = impl.getApiPersistentConnections();
ApiPersistentConnection pconn = null;
for (ApiPersistentConnection pc : pconnList) {
if (name.equals(pc.getName())) {
pconn = pc;
break;
}
}
if (pconn == null) {
throw new ApiException(ApiException.Type.BAD_PCONN);
}
return pconn;
} else {
throw new ApiException(ApiException.Type.BAD_TYPE);
}
}
private void appendElements(
StringBuilder sb, String component, String type, List<ApiElement> elementList) {
Collections.sort(
elementList,
new Comparator<ApiElement>() {
@Override
public int compare(ApiElement ae1, ApiElement ae2) {
return ae1.getName().compareTo(ae2.getName());
}
});
sb.append("\n<table>\n");
for (ApiElement element : elementList) {
sb.append("<tr>");
sb.append("<td>");
sb.append("<a href=\"/");
sb.append(Format.UI.name());
sb.append('/');
sb.append(component);
sb.append('/');
sb.append(type);
sb.append('/');
sb.append(element.getName());
sb.append("/\">");
sb.append(element.getName());
if (!element.getParameters().isEmpty()) {
sb.append(" (");
for (ApiParameter parameter : element.getParameters()) {
sb.append(parameter.getName());
if (parameter.isRequired()) {
sb.append('*');
}
sb.append(' ');
}
sb.append(") ");
}
sb.append("</a>");
sb.append("</td><td>");
if (element.isDeprecated()) {
sb.append(Constant.messages.getString("api.html.deprecated.endpoint"));
sb.append("<br />");
String text = element.getDeprecatedDescription();
if (text != null && !text.isEmpty()) {
sb.append(text);
sb.append("<br />");
}
}
String descTag = element.getDescriptionTag();
if (Constant.messages.containsKey(descTag)) {
sb.append(Constant.messages.getString(descTag));
} else {
// Uncomment to see what tags are missing via the UI
// sb.append(descTag);
}
sb.append("</td>");
sb.append("</tr>\n");
}
sb.append("</table>\n");
}
private void appendShortcuts(StringBuilder sb, String component, List<String> shortcutList) {
Collections.sort(shortcutList);
sb.append("\n<table>\n");
for (String shortcut : shortcutList) {
sb.append("<tr>");
sb.append("<td>");
sb.append("<a href=\"/");
sb.append(shortcut);
sb.append("/?");
sb.append(API.API_NONCE_PARAM);
sb.append("=");
sb.append(api.getOneTimeNonce("/" + shortcut + "/"));
sb.append("\">");
sb.append(shortcut);
sb.append("</a>");
sb.append("</td><td>");
sb.append("</td>");
sb.append("</tr>\n");
}
sb.append("</table>\n");
}
public String handleRequest(
String component, ApiImplementor impl, RequestType reqType, String name)
throws ApiException {
// Generate HTML UI
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html>\n");
sb.append("<head>\n");
sb.append("<title>");
sb.append(Constant.messages.getString("api.html.title"));
sb.append("</title>\n");
/* The script version prevents the cache being used if ZAP has been updated in the same day */
sb.append(
"<script src=\"/script.js/?v="
+ CoreAPI.API_SCRIPT_VERSION
+ "&"
+ API.API_NONCE_PARAM
+ "="
+ api.getOneTimeNonce("/script.js/")
+ "\" type=\"text/javascript\"></script>\n");
sb.append("</head>\n");
sb.append("<body>\n");
sb.append("<h1>");
sb.append("<a href=\"/");
sb.append(Format.UI.name());
sb.append("/\">");
sb.append(Constant.messages.getString("api.html.title"));
sb.append("</a>");
sb.append("</h1>\n");
if (impl != null) {
sb.append("<h2>");
sb.append("<a href=\"/");
sb.append(Format.UI.name());
sb.append("/");
sb.append(component);
sb.append("/\">");
sb.append(Constant.messages.getString("api.html.component"));
sb.append(component);
sb.append("</a>");
sb.append("</h2>\n");
if (name != null) {
ApiElement element = this.getElement(impl, name, reqType);
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html." + reqType.name()));
sb.append(element.getName());
sb.append("</h3>\n");
String descTag = element.getDescriptionTag();
if (Constant.messages.containsKey(descTag)) {
sb.append(Constant.messages.getString(descTag));
}
sb.append("\n<form id=\"zapform\" name=\"zapform\" action=\"override\"");
if (element.getName().equals("fileUpload")) {
sb.append(" enctype=\"");
sb.append(HttpHeader.FORM_MULTIPART_CONTENT_TYPE);
sb.append('"');
}
sb.append('>');
sb.append("<table>\n");
if (!RequestType.other.equals(reqType)) {
sb.append("<tr><td>");
sb.append(Constant.messages.getString("api.html.format"));
sb.append("</td><td>\n");
sb.append("<select id=\"zapapiformat\">\n");
sb.append("<option value=\"JSON\">JSON</option>\n");
if (getOptionsParamApi().isEnableJSONP()) {
sb.append("<option value=\"JSONP\">JSONP</option>\n");
} else {
sb.append("<option value=\"JSONP\" disabled>JSONP</option>\n");
}
sb.append("<option value=\"HTML\">HTML</option>\n");
sb.append("<option value=\"XML\">XML</option>\n");
sb.append("</select>\n");
sb.append("</td>");
sb.append("<td></td>");
sb.append("</tr>\n");
}
if (RequestType.action.equals(reqType)
|| RequestType.other.equals(reqType)
|| !getOptionsParamApi().isNoKeyForSafeOps()) {
String keyType = API.API_KEY_PARAM;
if (this.isDevTestNonce && RequestType.other.equals(reqType)) {
// We can use nonces as we know the return type
keyType = API.API_NONCE_PARAM;
}
if (!getOptionsParamApi().isDisableKey()) {
sb.append("<tr>");
sb.append("<td>");
sb.append(keyType);
sb.append("*</td>");
sb.append("<td>");
sb.append("<input id=\"");
sb.append(keyType);
sb.append("\" name=\"");
sb.append(keyType);
sb.append("\" value=\"");
if (this.isDevTestNonce && RequestType.other.equals(reqType)) {
sb.append(
api.getOneTimeNonce(
"/"
+ reqType.name().toUpperCase(Locale.ROOT)
+ "/"
+ impl.getPrefix()
+ "/"
+ reqType.name()
+ "/"
+ element.getName()
+ "/"));
} else {
if (getOptionsParamApi().isAutofillKey()) {
sb.append(getOptionsParamApi().getKey());
}
}
sb.append("\"/>");
sb.append("</td>");
sb.append("<td></td>");
sb.append("</tr>\n");
}
sb.append("<tr>");
sb.append("<td>");
sb.append(Constant.messages.getString("api.html.formMethod"));
sb.append("</td>");
sb.append("<td>");
sb.append("<select id=\"formMethod\">\n");
String getSelected = " selected";
String postSelected = "";
if (element.getName().equals("fileUpload")) {
getSelected = "";
postSelected = " selected";
}
sb.append("<option value=\"GET\"");
sb.append(getSelected);
sb.append(">GET</option>\n");
sb.append("<option value=\"POST\"");
sb.append(postSelected);
sb.append(">POST</option>\n");
sb.append("</select>\n");
sb.append("</td>");
sb.append("<td></td>");
sb.append("</tr>\n");
}
appendParams(sb, element.getParameters());
sb.append("<tr>");
sb.append("<td>");
sb.append("</td>");
sb.append("<td>");
sb.append("<input id=\"button\" value=\"");
sb.append(element.getName());
sb.append(
"\" type=\"submit\" zap-component=\""
+ component
+ "\" zap-type=\""
+ reqType
+ "\" zap-name=\""
+ name
+ "\"/>\n");
sb.append("</td>");
sb.append("<td></td>");
sb.append("</tr>\n");
sb.append("</table>\n");
sb.append("</form>\n");
} else {
if (Constant.messages.containsKey(impl.getDescriptionKey())) {
sb.append("<p>\n");
sb.append(Constant.messages.getString(impl.getDescriptionKey()));
sb.append("\n</p>\n");
}
List<ApiElement> elementList = new ArrayList<>();
List<ApiView> viewList = impl.getApiViews();
if (viewList != null && viewList.size() > 0) {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.views"));
sb.append("</h3>\n");
elementList.addAll(viewList);
this.appendElements(sb, component, RequestType.view.name(), elementList);
}
List<ApiAction> actionList = impl.getApiActions();
if (actionList != null && actionList.size() > 0) {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.actions"));
sb.append("</h3>\n");
elementList = new ArrayList<>();
elementList.addAll(actionList);
this.appendElements(sb, component, RequestType.action.name(), elementList);
}
List<ApiOther> otherList = impl.getApiOthers();
if (otherList != null && otherList.size() > 0) {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.others"));
sb.append("</h3>\n");
elementList = new ArrayList<>();
elementList.addAll(otherList);
this.appendElements(sb, component, RequestType.other.name(), elementList);
}
List<ApiPersistentConnection> pconnList = impl.getApiPersistentConnections();
if (pconnList != null && pconnList.size() > 0) {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.pconns"));
sb.append("</h3>\n");
elementList = new ArrayList<>();
elementList.addAll(pconnList);
this.appendElements(sb, component, RequestType.pconn.name(), elementList);
}
if (getOptionsParamApi().isDisableKey()
|| getOptionsParamApi().isAutofillKey()
|| this.isDevTestNonce) {
// Only show shortcuts if they will work without the user having to add a
// key/nonce
List<String> shortcutList = impl.getApiShortcuts();
if (shortcutList != null && shortcutList.size() > 0) {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.shortcuts"));
sb.append("</h3>\n");
elementList = new ArrayList<>();
elementList.addAll(otherList);
this.appendShortcuts(sb, component, shortcutList);
}
}
}
} else {
sb.append("<h3>");
sb.append(Constant.messages.getString("api.html.components"));
sb.append("</h3>\n");
List<ApiImplementor> components = new ArrayList<>(api.getImplementors().values());
Collections.sort(components, Comparator.comparing(ApiImplementor::getPrefix));
sb.append("<table>\n");
for (ApiImplementor cmp : components) {
sb.append("<tr>");
sb.append("<td>");
sb.append("<a href=\"/");
sb.append(Format.UI.name());
sb.append('/');
sb.append(cmp.getPrefix());
sb.append("/\">");
sb.append(cmp.getPrefix());
sb.append("</a>");
sb.append("</td>");
sb.append("<td>");
if (Constant.messages.containsKey(cmp.getDescriptionKey())) {
sb.append(Constant.messages.getString(cmp.getDescriptionKey()));
}
sb.append("</td>");
sb.append("</tr>\n");
}
sb.append("</table>\n");
}
sb.append("</body>\n");
return sb.toString();
}
private static void appendParams(StringBuilder sb, List<ApiParameter> params) {
for (ApiParameter param : params) {
sb.append("<tr>");
sb.append("<td>");
sb.append(param.getName());
if (param.isRequired()) {
sb.append('*');
}
sb.append("</td>");
sb.append("<td>");
sb.append("<input id=\"");
sb.append(param.getName());
sb.append("\" name=\"");
sb.append(param.getName());
sb.append("\"");
if (param.getName().equals("fileContents")) {
sb.append(" type=\"file\"");
}
sb.append("/>");
sb.append("</td><td>");
String descKey = param.getDescriptionKey();
if (Constant.messages.containsKey(descKey)) {
sb.append(Constant.messages.getString(descKey));
}
sb.append("</td>");
sb.append("</tr>\n");
}
}
public String handleRequest(URI uri, boolean apiEnabled) {
// Right now just generate a basic home page
StringBuilder sb = new StringBuilder();
sb.append("<head>\n");
sb.append("<title>");
sb.append(Constant.messages.getString("api.html.title"));
sb.append("</title>\n");
sb.append("</head>\n");
sb.append("<body>\n");
sb.append(Constant.messages.getString("api.home.topmsg"));
sb.append(
Constant.messages.getString(
"api.home.proxypac", getApiPathWithNonceParam(PAC_FILE_API_PATH)));
sb.append(
Constant.messages.getString(
"api.home.cacert", getApiPathWithNonceParam(ROOT_CA_CERT_API_PATH)));
sb.append(Constant.messages.getString("api.home.links.header"));
if (apiEnabled) {
sb.append(Constant.messages.getString("api.home.links.api.enabled"));
} else {
sb.append(Constant.messages.getString("api.home.links.api.disabled"));
}
sb.append(Constant.messages.getString("api.home.links.online"));
sb.append("</body>\n");
return sb.toString();
}
private static String getApiPathWithNonceParam(String path) {
return path + '?' + API.API_NONCE_PARAM + '=' + API.getInstance().getLongLivedNonce(path);
}
private OptionsParamApi getOptionsParamApi() {
return Model.getSingleton().getOptionsParam().getApiParam();
}
}
| zaproxy/zaproxy | zap/src/main/java/org/zaproxy/zap/extension/api/WebUI.java |
45,317 | /*
* Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.apple.eio;
import java.io.*;
/**
* Provides functionality to query and modify Mac-specific file attributes. The methods in this class are based on Finder
* attributes. These attributes in turn are dependent on HFS and HFS+ file systems. As such, it is important to recognize
* their limitation when writing code that must function well across multiple platforms.<p>
*
* In addition to file name suffixes, Mac OS X can use Finder attributes like file {@code type} and {@code creator} codes to
* identify and handle files. These codes are unique 4-byte identifiers. The file {@code type} is a string that describes the
* contents of a file. For example, the file type {@code APPL} identifies the file as an application and therefore
* executable. A file type of {@code TEXT} means that the file contains raw text. Any application that can read raw
* text can open a file of type {@code TEXT}. Applications that use proprietary file types might assign their files a proprietary
* file {@code type} code.
* <p>
* To identify the application that can handle a document, the Finder can look at the {@code creator}. For example, if a user
* double-clicks on a document with the {@code ttxt creator}, it opens up in Text Edit, the application registered
* with the {@code ttxt creator} code. Note that the {@code creator}
* code can be set to any application, not necessarily the application that created it. For example, if you
* use an editor to create an HTML document, you might want to assign a browser's {@code creator} code for the file rather than
* the HTML editor's {@code creator} code. Double-clicking on the document then opens the appropriate browser rather than the
*HTML editor.
*<p>
* If you plan to publicly distribute your application, you must register its creator and any proprietary file types with the Apple
* Developer Connection to avoid collisions with codes used by other developers. You can register a codes online at the
* <a target=_blank href=http://developer.apple.com/dev/cftype/>Creator Code Registration</a> site.
*
* @since 1.4
*/
public class FileManager {
static {
loadOSXLibrary();
}
@SuppressWarnings("removal")
private static void loadOSXLibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary("osx");
return null;
}
});
}
/**
* The default
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
public static final short kOnAppropriateDisk = -32767;
/**
* Read-only system hierarchy.
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
public static final short kSystemDomain = -32766;
/**
* All users of a single machine have access to these resources.
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
public static final short kLocalDomain = -32765;
/**
* All users configured to use a common network server has access to these resources.
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
public static final short kNetworkDomain = -32764;
/**
* Read/write. Resources that are private to the user.
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
public static final short kUserDomain = -32763;
/**
* Converts an OSType (e.g. "macs"
* from {@literal <CarbonCore/Folders.h>}) into an int.
*
* @param type the 4 character type to convert.
* @return an int representing the 4 character value
*
* @since Java for Mac OS X 10.5 - 1.5
* @since Java for Mac OS X 10.5 Update 1 - 1.6
*/
@SuppressWarnings("deprecation")
public static int OSTypeToInt(String type) {
int result = 0;
byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
int len = type.length();
if (len > 0) {
if (len > 4) len = 4;
type.getBytes(0, len, b, 4 - len);
}
for (int i = 0; i < len; i++) {
if (i > 0) result <<= 8;
result |= (b[i] & 0xff);
}
return result;
}
/**
* Sets the file {@code type} and {@code creator} codes for a file or folder.
*
* @since 1.4
*/
public static void setFileTypeAndCreator(String filename, int type, int creator) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(filename);
}
_setFileTypeAndCreator(filename, type, creator);
}
private static native void _setFileTypeAndCreator(String filename, int type, int creator) throws IOException;
/**
* Sets the file {@code type} code for a file or folder.
*
* @since 1.4
*/
public static void setFileType(String filename, int type) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(filename);
}
_setFileType(filename, type);
}
private static native void _setFileType(String filename, int type) throws IOException;
/**
* Sets the file {@code creator} code for a file or folder.
*
* @since 1.4
*/
public static void setFileCreator(String filename, int creator) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(filename);
}
_setFileCreator(filename, creator);
}
private static native void _setFileCreator(String filename, int creator) throws IOException;
/**
* Obtains the file {@code type} code for a file or folder.
*
* @since 1.4
*/
public static int getFileType(String filename) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(filename);
}
return _getFileType(filename);
}
private static native int _getFileType(String filename) throws IOException;
/**
* Obtains the file {@code creator} code for a file or folder.
*
* @since 1.4
*/
public static int getFileCreator(String filename) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(filename);
}
return _getFileCreator(filename);
}
private static native int _getFileCreator(String filename) throws IOException;
/**
* Locates a folder of a particular type. Mac OS X recognizes certain specific folders that have distinct purposes.
* For example, the user's desktop or temporary folder. These folders have corresponding codes. Given one of these codes,
* this method returns the path to that particular folder. Certain folders of a given type may appear in more than
* one domain. For example, although there is only one {@code root} folder, there are multiple {@code pref}
* folders. If this method is called to find the {@code pref} folder, it will return the first one it finds,
* the user's preferences folder in {@code ~/Library/Preferences}. To explicitly locate a folder in a certain
* domain use {@code findFolder(short domain, int folderType)} or
* {@code findFolder(short domain, int folderType, boolean createIfNeeded)}.
*
* @return the path to the folder searched for
*
* @since 1.4
*/
public static String findFolder(int folderType) throws FileNotFoundException {
return findFolder(kOnAppropriateDisk, folderType);
}
/**
* Locates a folder of a particular type, within a given domain. Similar to {@code findFolder(int folderType)}
* except that the domain to look in can be specified. Valid values for {@code domain} include:
* <dl>
* <dt>user</dt>
* <dd>The User domain contains resources specific to the user who is currently logged in</dd>
* <dt>local</dt>
* <dd>The Local domain contains resources shared by all users of the system but are not needed for the system
* itself to run.</dd>
* <dt>network</dt>
* <dd>The Network domain contains resources shared by users of a local area network.</dd>
* <dt>system</dt>
* <dd>The System domain contains the operating system resources installed by Apple.</dd>
* </dl>
*
* @return the path to the folder searched for
*
* @since 1.4
*/
public static String findFolder(short domain, int folderType) throws FileNotFoundException {
return findFolder(domain, folderType, false);
}
/**
* Locates a folder of a particular type within a given domain and optionally creating the folder if it does
* not exist. The behavior is similar to {@code findFolder(int folderType)} and
* {@code findFolder(short domain, int folderType)} except that it can create the folder if it does not already exist.
*
* @param createIfNeeded
* set to {@code true}, by setting to {@code false} the behavior will be the
* same as {@code findFolder(short domain, int folderType, boolean createIfNeeded)}
* @return the path to the folder searched for
*
* @since 1.4
*/
public static String findFolder(short domain, int folderType, boolean createIfNeeded) throws FileNotFoundException {
@SuppressWarnings("removal")
final SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new RuntimePermission("canExamineFileSystem"));
}
final String foundFolder = _findFolder(domain, folderType, createIfNeeded);
if (foundFolder == null) throw new FileNotFoundException("Can't find folder: " + Integer.toHexString(folderType));
return foundFolder;
}
private static native String _findFolder(short domain, int folderType, boolean createIfNeeded);
/**
* Opens the path specified by a URL in the appropriate application for that URL. HTTP URL's ({@code http://})
* open in the default browser as set in the Internet pane of System Preferences. File ({@code file://}) and
* FTP URL's ({@code ftp://}) open in the Finder. Note that opening an FTP URL will prompt the user for where
* they want to save the downloaded file(s).
*
* @param url
* the URL for the file you want to open, it can either be an HTTP, FTP, or file url
*
* @deprecated this functionality has been superseded by java.awt.Desktop.browse() and java.awt.Desktop.open()
*
* @since 1.4
*/
@Deprecated
public static void openURL(String url) throws IOException {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new RuntimePermission("canOpenURLs"));
}
_openURL(url);
}
private static native void _openURL(String url) throws IOException;
/**
* @return full pathname for the resource identified by a given name.
*
* @since 1.4
*/
public static String getResource(String resourceName) throws FileNotFoundException {
return getResourceFromBundle(resourceName, null, null);
}
/**
* @return full pathname for the resource identified by a given name and located in the specified bundle subdirectory.
*
* @since 1.4
*/
public static String getResource(String resourceName, String subDirName) throws FileNotFoundException {
return getResourceFromBundle(resourceName, subDirName, null);
}
/**
* Returns the full pathname for the resource identified by the given name and file extension
* and located in the specified bundle subdirectory.
*
* If extension is an empty string or null, the returned pathname is the first one encountered where the
* file name exactly matches name.
*
* If subpath is null, this method searches the top-level nonlocalized resource directory (typically Resources)
* and the top-level of any language-specific directories. For example, suppose you have a modern bundle and
* specify "Documentation" for the subpath parameter. This method would first look in the
* Contents/Resources/Documentation directory of the bundle, followed by the Documentation subdirectories of
* each language-specific .lproj directory. (The search order for the language-specific directories
* corresponds to the user's preferences.) This method does not recurse through any other subdirectories at
* any of these locations. For more details see the AppKit NSBundle documentation.
*
* @return full pathname for the resource identified by the given name and file extension and located in the specified bundle subdirectory.
*
* @since 1.4
*/
public static String getResource(String resourceName, String subDirName, String type) throws FileNotFoundException {
return getResourceFromBundle(resourceName, subDirName, type);
}
private static native String getNativeResourceFromBundle(String resourceName, String subDirName, String type) throws FileNotFoundException;
private static String getResourceFromBundle(String resourceName, String subDirName, String type) throws FileNotFoundException {
@SuppressWarnings("removal")
final SecurityManager security = System.getSecurityManager();
if (security != null) security.checkPermission(new RuntimePermission("canReadBundle"));
final String resourceFromBundle = getNativeResourceFromBundle(resourceName, subDirName, type);
if (resourceFromBundle == null) throw new FileNotFoundException(resourceName);
return resourceFromBundle;
}
/**
* Obtains the path to the current application's NSBundle, may not
* return a valid path if Java was launched from the command line.
*
* @return full pathname of the NSBundle of the current application executable.
*
* @since Java for Mac OS X 10.5 Update 1 - 1.6
* @since Java for Mac OS X 10.5 Update 2 - 1.5
*/
public static String getPathToApplicationBundle() {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) security.checkPermission(new RuntimePermission("canReadBundle"));
return getNativePathToApplicationBundle();
}
private static native String getNativePathToApplicationBundle();
/**
* Moves the specified file to the Trash
*
* @param file the file
* @return returns true if the NSFileManager successfully moved the file to the Trash.
* @throws FileNotFoundException
*
* @since Java for Mac OS X 10.6 Update 1 - 1.6
* @since Java for Mac OS X 10.5 Update 6 - 1.6, 1.5
*/
public static boolean moveToTrash(final File file) throws FileNotFoundException {
if (file == null) throw new FileNotFoundException();
final String fileName = file.getAbsolutePath();
@SuppressWarnings("removal")
final SecurityManager security = System.getSecurityManager();
if (security != null) security.checkDelete(fileName);
return _moveToTrash(fileName);
}
private static native boolean _moveToTrash(String fileName);
/**
* Reveals the specified file in the Finder
*
* @param file
* the file to reveal
* @return returns true if the NSFileManager successfully revealed the file in the Finder.
* @throws FileNotFoundException
*
* @since Java for Mac OS X 10.6 Update 1 - 1.6
* @since Java for Mac OS X 10.5 Update 6 - 1.6, 1.5
*/
public static boolean revealInFinder(final File file) throws FileNotFoundException {
if (file == null || !file.exists()) throw new FileNotFoundException();
final String fileName = file.getAbsolutePath();
@SuppressWarnings("removal")
final SecurityManager security = System.getSecurityManager();
if (security != null) security.checkRead(fileName);
return _revealInFinder(fileName);
}
private static native boolean _revealInFinder(String fileName);
}
| openjdk/jdk | src/java.desktop/macosx/classes/com/apple/eio/FileManager.java |
45,318 | /*
* This is the source code of Telegram for Android v. 1.3.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Cells;
import static org.telegram.messenger.AndroidUtilities.dp;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ReplacementSpan;
import android.text.style.StyleSpan;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
import androidx.collection.LongSparseArray;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ChatThemeController;
import org.telegram.messenger.CodeHighlighting;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.DownloadController;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.LiteMode;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.tl.TL_stories;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Adapters.DialogsAdapter;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AnimatedEmojiSpan;
import org.telegram.ui.Components.AnimatedFloat;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BubbleCounterPath;
import org.telegram.ui.Components.CanvasButton;
import org.telegram.ui.Components.CheckBox2;
import org.telegram.ui.Components.ColoredImageSpan;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.DialogCellTags;
import org.telegram.ui.Components.EmptyStubSpan;
import org.telegram.ui.Components.ForegroundColorSpanThemable;
import org.telegram.ui.Components.Forum.ForumBubbleDrawable;
import org.telegram.ui.Components.Forum.ForumUtilities;
import org.telegram.ui.Components.Premium.PremiumGradient;
import org.telegram.ui.Components.PullForegroundDrawable;
import org.telegram.ui.Components.QuoteSpan;
import org.telegram.ui.Components.RLottieDrawable;
import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble;
import org.telegram.ui.Components.StaticLayoutEx;
import org.telegram.ui.Components.StatusDrawable;
import org.telegram.ui.Components.SwipeGestureSettingsView;
import org.telegram.ui.Components.TextStyleSpan;
import org.telegram.ui.Components.TimerDrawable;
import org.telegram.ui.Components.TypefaceSpan;
import org.telegram.ui.Components.URLSpanNoUnderline;
import org.telegram.ui.Components.URLSpanNoUnderlineBold;
import org.telegram.ui.Components.VectorAvatarThumbDrawable;
import org.telegram.ui.Components.spoilers.SpoilerEffect;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.RightSlidingDialogContainer;
import org.telegram.ui.Stories.StoriesListPlaceProvider;
import org.telegram.ui.Stories.StoriesUtilities;
import org.telegram.ui.Stories.StoryViewer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Stack;
public class DialogCell extends BaseCell implements StoriesListPlaceProvider.AvatarOverlaysView {
public boolean drawingForBlur;
public boolean collapsed;
public boolean drawArchive = true;
public float rightFragmentOffset;
boolean moving;
private RLottieDrawable lastDrawTranslationDrawable;
private int lastDrawSwipeMessageStringId;
public boolean swipeCanceled;
public static final int SENT_STATE_NOTHING = -1;
public static final int SENT_STATE_PROGRESS = 0;
public static final int SENT_STATE_SENT = 1;
public static final int SENT_STATE_READ = 2;
public boolean drawAvatar = true;
public int avatarStart = 10;
public int messagePaddingStart = 72;
public int heightDefault = 72;
public int heightThreeLines = 78;
public int addHeightForTags = 3;
public int addForumHeightForTags = 11;
public TLRPC.TL_forumTopic forumTopic;
public boolean useFromUserAsAvatar;
private boolean isTopic;
private boolean twoLinesForName;
private boolean nameIsEllipsized;
private Paint topicCounterPaint;
private Paint counterPaintOutline;
public float chekBoxPaddingTop = 42;
private boolean needEmoji;
private boolean hasNameInMessage;
private TextPaint currentMessagePaint;
private Paint buttonBackgroundPaint;
CanvasButton canvasButton;
DialogCellDelegate delegate;
private boolean applyName;
private boolean lastTopicMessageUnread;
private boolean showTopicIconInName;
protected Drawable topicIconInName[];
private float rightFragmentOpenedProgress;
public boolean isTransitionSupport;
public boolean drawAvatarSelector;
public boolean inPreviewMode;
private boolean buttonCreated;
private int ttlPeriod;
private float ttlProgress;
private TimerDrawable timerDrawable;
private Paint timerPaint;
private Paint timerPaint2;
SharedResources sharedResources;
public boolean isSavedDialog;
public boolean isSavedDialogCell;
public DialogCellTags tags;
public final StoriesUtilities.AvatarStoryParams storyParams = new StoriesUtilities.AvatarStoryParams(false) {
@Override
public void openStory(long dialogId, Runnable onDone) {
if (delegate == null) {
return;
}
if (currentDialogFolderId != 0) {
delegate.openHiddenStories();
} else {
if (delegate != null) {
delegate.openStory(DialogCell.this, onDone);
}
}
}
@Override
public void onLongPress() {
if (delegate == null) {
return;
}
delegate.showChatPreview(DialogCell.this);
}
};
private Path thumbPath;
private SpoilerEffect thumbSpoiler = new SpoilerEffect();
private boolean drawForwardIcon;
private boolean visibleOnScreen = true;
private boolean updateLayout;
private boolean wasDrawnOnline;
public void setMoving(boolean moving) {
this.moving = moving;
}
public boolean isMoving() {
return moving;
}
public void setForumTopic(TLRPC.TL_forumTopic topic, long dialog_id, MessageObject messageObject, boolean showTopicIconInName, boolean animated) {
forumTopic = topic;
isTopic = forumTopic != null;
if (currentDialogId != dialog_id) {
lastStatusDrawableParams = -1;
}
if (messageObject.topicIconDrawable[0] instanceof ForumBubbleDrawable) {
((ForumBubbleDrawable) messageObject.topicIconDrawable[0]).setColor(topic.icon_color);
}
currentDialogId = dialog_id;
lastDialogChangedTime = System.currentTimeMillis();
message = messageObject;
isDialogCell = false;
this.showTopicIconInName = showTopicIconInName;
if (messageObject != null) {
lastMessageDate = messageObject.messageOwner.date;
currentEditDate = messageObject != null ? messageObject.messageOwner.edit_date : 0;
markUnread = false;
messageId = messageObject != null ? messageObject.getId() : 0;
lastUnreadState = messageObject != null && messageObject.isUnread();
}
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
if (!animated) {
lastStatusDrawableParams = -1;
}
if (topic != null) {
groupMessages = topic.groupedMessages;
}
if (forumTopic != null && forumTopic.id == 1) {
if (archivedChatsDrawable != null) {
archivedChatsDrawable.setCell(this);
}
}
update(0, animated);
}
public void setRightFragmentOpenedProgress(float rightFragmentOpenedProgress) {
if (this.rightFragmentOpenedProgress != rightFragmentOpenedProgress) {
this.rightFragmentOpenedProgress = rightFragmentOpenedProgress;
invalidate();
}
}
public void setIsTransitionSupport(boolean isTransitionSupport) {
this.isTransitionSupport = isTransitionSupport;
}
public float collapseOffset = 0;
public void checkHeight() {
if (getMeasuredHeight() > 0 && getMeasuredHeight() != computeHeight()) {
requestLayout();
}
}
public void setSharedResources(SharedResources sharedResources) {
this.sharedResources = sharedResources;
}
public void setVisible(boolean visibleOnScreen) {
if (this.visibleOnScreen == visibleOnScreen) {
return;
}
this.visibleOnScreen = visibleOnScreen;
if (visibleOnScreen) {
invalidate();
}
}
public static class FixedWidthSpan extends ReplacementSpan {
private int width;
public FixedWidthSpan(int w) {
width = w;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
if (fm == null) {
fm = paint.getFontMetricsInt();
}
if (fm != null) {
int h = fm.descent - fm.ascent;
fm.bottom = fm.descent = 1 - h;
fm.top = fm.ascent = -1;
}
return width;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
}
}
public static class CustomDialog {
public String name;
public String message;
public int id;
public int unread_count;
public boolean pinned;
public boolean muted;
public int type;
public int date;
public boolean verified;
public boolean isMedia;
public int sent = -1;
}
private int paintIndex;
private int currentAccount;
private CustomDialog customDialog;
private long currentDialogId;
private int currentDialogFolderId;
private int currentDialogFolderDialogsCount;
private int currentEditDate;
public boolean isDialogCell;
private int lastMessageDate;
private int unreadCount;
private boolean markUnread;
private int mentionCount;
private int reactionMentionCount;
private boolean lastUnreadState;
private int lastSendState;
private boolean dialogMuted;
private boolean topicMuted;
private boolean drawUnmute;
private float dialogMutedProgress;
private boolean hasUnmutedTopics = false;
private MessageObject message;
private boolean isForum;
private ArrayList<MessageObject> groupMessages;
private boolean clearingDialog;
private CharSequence lastMessageString;
private int dialogsType;
private int folderId;
private int messageId;
private boolean archiveHidden;
protected boolean forbidVerified;
protected boolean forbidDraft;
private float cornerProgress;
private long lastUpdateTime;
private float onlineProgress;
private float chatCallProgress;
private float innerProgress;
private int progressStage;
private float clipProgress;
private int topClip;
private int bottomClip;
protected float translationX;
private boolean isSliding;
private RLottieDrawable translationDrawable;
private boolean translationAnimationStarted;
private boolean drawRevealBackground;
private float currentRevealProgress;
private float currentRevealBounceProgress;
private float archiveBackgroundProgress;
protected boolean overrideSwipeAction = false;
protected int overrideSwipeActionBackgroundColorKey;
protected int overrideSwipeActionRevealBackgroundColorKey;
protected String overrideSwipeActionStringKey;
protected int overrideSwipeActionStringId;
protected RLottieDrawable overrideSwipeActionDrawable;
private int thumbsCount;
private boolean hasVideoThumb;
private Paint thumbBackgroundPaint;
private boolean[] thumbImageSeen = new boolean[3];
private ImageReceiver[] thumbImage = new ImageReceiver[3];
private boolean[] drawPlay = new boolean[3];
private boolean[] drawSpoiler = new boolean[3];
public ImageReceiver avatarImage = new ImageReceiver(this);
private AvatarDrawable avatarDrawable = new AvatarDrawable();
private boolean animatingArchiveAvatar;
private float animatingArchiveAvatarProgress;
private BounceInterpolator interpolator = new BounceInterpolator();
protected PullForegroundDrawable archivedChatsDrawable;
private TLRPC.User user;
private TLRPC.Chat chat;
private TLRPC.EncryptedChat encryptedChat;
private CharSequence lastPrintString;
private int printingStringType;
private boolean draftVoice;
private TLRPC.DraftMessage draftMessage;
private final AnimatedFloat premiumBlockedT = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT);
private boolean premiumBlocked;
public boolean isBlocked() {
return premiumBlocked;
}
protected CheckBox2 checkBox;
public boolean useForceThreeLines;
public boolean useSeparator;
public boolean fullSeparator;
public boolean fullSeparator2;
private boolean useMeForMyMessages;
private boolean hasCall;
private boolean showTtl;
private int nameLeft;
private int nameWidth;
private StaticLayout nameLayout;
private boolean nameLayoutFits;
private float nameLayoutTranslateX;
private boolean nameLayoutEllipsizeLeft;
private boolean nameLayoutEllipsizeByGradient;
private Paint fadePaint;
private Paint fadePaintBack;
private boolean drawNameLock;
private int nameMuteLeft;
private int nameLockLeft;
private int nameLockTop;
private int timeLeft;
private int timeTop;
private StaticLayout timeLayout;
private int lock2Left;
private boolean promoDialog;
private boolean drawCheck1;
private boolean drawCheck2;
private boolean drawClock;
private int checkDrawLeft;
private int checkDrawLeft1;
private int clockDrawLeft;
private int checkDrawTop;
private int halfCheckDrawLeft;
private int tagsLeft, tagsRight;
private int messageTop;
private int messageLeft;
private int buttonLeft;
private int typingLeft;
private StaticLayout messageLayout;
private StaticLayout typingLayout;
private int buttonTop;
private StaticLayout buttonLayout;
private Stack<SpoilerEffect> spoilersPool = new Stack<>();
private List<SpoilerEffect> spoilers = new ArrayList<>();
private Stack<SpoilerEffect> spoilersPool2 = new Stack<>();
private List<SpoilerEffect> spoilers2 = new ArrayList<>();
private AnimatedEmojiSpan.EmojiGroupedSpans animatedEmojiStack, animatedEmojiStack2, animatedEmojiStack3, animatedEmojiStackName;
private int messageNameTop;
private int messageNameLeft;
private StaticLayout messageNameLayout;
private boolean drawError;
private int errorTop;
private int errorLeft;
private boolean attachedToWindow;
private float reorderIconProgress;
private boolean drawReorder;
private boolean drawPinBackground;
private boolean drawPin;
private boolean drawPinForced;
private int pinTop;
private int pinLeft;
protected int translateY;
protected float xOffset;
private boolean drawCount;
private boolean drawCount2 = true;
private int countTop;
private int countLeft;
private int countWidth;
private int countWidthOld;
private int countLeftOld;
private boolean countAnimationIncrement;
private ValueAnimator countAnimator;
private ValueAnimator reactionsMentionsAnimator;
private float countChangeProgress = 1f;
private float reactionsMentionsChangeProgress = 1f;
private StaticLayout countLayout;
private StaticLayout countOldLayout;
private StaticLayout countAnimationStableLayout;
private StaticLayout countAnimationInLayout;
private boolean drawMention;
private boolean drawReactionMention;
private int mentionLeft;
private int reactionMentionLeft;
private int mentionWidth;
private StaticLayout mentionLayout;
private boolean drawVerified;
private boolean drawPremium;
private AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable emojiStatus;
private int drawScam;
private boolean isSelected;
private RectF rect = new RectF();
private DialogsAdapter.DialogsPreloader preloader;
private Path counterPath;
private RectF counterPathRect;
private int animateToStatusDrawableParams;
private int animateFromStatusDrawableParams;
private int lastStatusDrawableParams = -1;
private float statusDrawableProgress;
private boolean statusDrawableAnimationInProgress;
private ValueAnimator statusDrawableAnimator;
long lastDialogChangedTime;
private int statusDrawableLeft;
private DialogsActivity parentFragment;
private StaticLayout swipeMessageTextLayout;
private int swipeMessageTextId;
private int swipeMessageWidth;
private int readOutboxMaxId = -1;
private final DialogUpdateHelper updateHelper = new DialogUpdateHelper();
public static class BounceInterpolator implements Interpolator {
public float getInterpolation(float t) {
if (t < 0.33f) {
return 0.1f * (t / 0.33f);
} else {
t -= 0.33f;
if (t < 0.33f) {
return 0.1f - 0.15f * (t / 0.34f);
} else {
t -= 0.34f;
return -0.05f + 0.05f * (t / 0.33f);
}
}
}
}
public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines) {
this(fragment, context, needCheck, forceThreeLines, UserConfig.selectedAccount, null);
}
private final Theme.ResourcesProvider resourcesProvider;
public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines, int account, Theme.ResourcesProvider resourcesProvider) {
super(context);
storyParams.allowLongress = true;
this.resourcesProvider = resourcesProvider;
parentFragment = fragment;
Theme.createDialogsResources(context);
avatarImage.setRoundRadius(dp(28));
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i] = new ImageReceiver(this);
thumbImage[i].ignoreNotifications = true;
thumbImage[i].setRoundRadius(dp(2));
thumbImage[i].setAllowLoadingOnAttachedOnly(true);
}
useForceThreeLines = forceThreeLines;
currentAccount = account;
emojiStatus = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(this, dp(22));
avatarImage.setAllowLoadingOnAttachedOnly(true);
}
public void setDialog(TLRPC.Dialog dialog, int type, int folder) {
if (currentDialogId != dialog.id) {
if (statusDrawableAnimator != null) {
statusDrawableAnimator.removeAllListeners();
statusDrawableAnimator.cancel();
}
statusDrawableAnimationInProgress = false;
lastStatusDrawableParams = -1;
}
currentDialogId = dialog.id;
lastDialogChangedTime = System.currentTimeMillis();
isDialogCell = true;
if (dialog instanceof TLRPC.TL_dialogFolder) {
TLRPC.TL_dialogFolder dialogFolder = (TLRPC.TL_dialogFolder) dialog;
currentDialogFolderId = dialogFolder.folder.id;
if (archivedChatsDrawable != null) {
archivedChatsDrawable.setCell(this);
}
} else {
currentDialogFolderId = 0;
}
dialogsType = type;
showPremiumBlocked(dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD);
if (tags == null) {
tags = new DialogCellTags();
}
folderId = folder;
messageId = 0;
if (update(0, false)) {
requestLayout();
}
checkOnline();
checkGroupCall();
checkChatTheme();
checkTtl();
}
protected boolean drawLock2() {
return false;
}
public void setDialog(CustomDialog dialog) {
customDialog = dialog;
messageId = 0;
update(0);
checkOnline();
checkGroupCall();
checkChatTheme();
checkTtl();
}
private void checkOnline() {
if (user != null) {
TLRPC.User newUser = MessagesController.getInstance(currentAccount).getUser(user.id);
if (newUser != null) {
user = newUser;
}
}
boolean isOnline = isOnline();
onlineProgress = isOnline ? 1.0f : 0.0f;
}
private boolean isOnline() {
if (isForumCell()) {
return false;
}
if (user == null || user.self) {
return false;
}
if (user.status != null && user.status.expires <= 0) {
if (MessagesController.getInstance(currentAccount).onlinePrivacy.containsKey(user.id)) {
return true;
}
}
if (user.status != null && user.status.expires > ConnectionsManager.getInstance(currentAccount).getCurrentTime()) {
return true;
}
return false;
}
private void checkGroupCall() {
hasCall = chat != null && chat.call_active && chat.call_not_empty;
chatCallProgress = hasCall ? 1.0f : 0.0f;
}
private void checkTtl() {
showTtl = ttlPeriod > 0 && !hasCall && !isOnline() && !(checkBox != null && checkBox.isChecked());
ttlProgress = showTtl ? 1.0f : 0.0f;
}
private void checkChatTheme() {
if (message != null && message.messageOwner != null && message.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme && lastUnreadState) {
TLRPC.TL_messageActionSetChatTheme setThemeAction = (TLRPC.TL_messageActionSetChatTheme) message.messageOwner.action;
ChatThemeController.getInstance(currentAccount).setDialogTheme(currentDialogId, setThemeAction.emoticon,false);
}
}
public void setDialog(long dialog_id, MessageObject messageObject, int date, boolean useMe, boolean animated) {
if (currentDialogId != dialog_id) {
lastStatusDrawableParams = -1;
}
currentDialogId = dialog_id;
lastDialogChangedTime = System.currentTimeMillis();
message = messageObject;
useMeForMyMessages = useMe;
isDialogCell = false;
lastMessageDate = date;
currentEditDate = messageObject != null ? messageObject.messageOwner.edit_date : 0;
unreadCount = 0;
markUnread = false;
messageId = messageObject != null ? messageObject.getId() : 0;
mentionCount = 0;
reactionMentionCount = 0;
lastUnreadState = messageObject != null && messageObject.isUnread();
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
update(0, animated);
}
public long getDialogId() {
return currentDialogId;
}
public int getMessageId() {
return messageId;
}
public void setPreloader(DialogsAdapter.DialogsPreloader preloader) {
this.preloader = preloader;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
isSliding = false;
drawRevealBackground = false;
currentRevealProgress = 0.0f;
attachedToWindow = false;
reorderIconProgress = getIsPinned() && drawReorder ? 1.0f : 0.0f;
avatarImage.onDetachedFromWindow();
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].onDetachedFromWindow();
}
if (translationDrawable != null) {
translationDrawable.stop();
translationDrawable.setProgress(0.0f);
translationDrawable.setCallback(null);
translationDrawable = null;
translationAnimationStarted = false;
}
if (preloader != null) {
preloader.remove(currentDialogId);
}
if (emojiStatus != null) {
emojiStatus.detach();
}
AnimatedEmojiSpan.release(this, animatedEmojiStack);
AnimatedEmojiSpan.release(this, animatedEmojiStack2);
AnimatedEmojiSpan.release(this, animatedEmojiStack3);
AnimatedEmojiSpan.release(this, animatedEmojiStackName);
storyParams.onDetachFromWindow();
canvasButton = null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
avatarImage.onAttachedToWindow();
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].onAttachedToWindow();
}
resetPinnedArchiveState();
animatedEmojiStack = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack, messageLayout);
animatedEmojiStack2 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack2, messageNameLayout);
animatedEmojiStack3 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack3, buttonLayout);
animatedEmojiStackName = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStackName, nameLayout);
if (emojiStatus != null) {
emojiStatus.attach();
}
}
public void resetPinnedArchiveState() {
archiveHidden = SharedConfig.archiveHidden;
archiveBackgroundProgress = archiveHidden ? 0.0f : 1.0f;
avatarDrawable.setArchivedAvatarHiddenProgress(archiveBackgroundProgress);
clipProgress = 0.0f;
isSliding = false;
reorderIconProgress = getIsPinned() && drawReorder ? 1.0f : 0.0f;
attachedToWindow = true;
cornerProgress = 0.0f;
setTranslationX(0);
setTranslationY(0);
if (emojiStatus != null && attachedToWindow) {
emojiStatus.attach();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (checkBox != null) {
checkBox.measure(
MeasureSpec.makeMeasureSpec(dp(24), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dp(24), MeasureSpec.EXACTLY)
);
}
if (isTopic) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), dp((useForceThreeLines || SharedConfig.useThreeLinesLayout ? heightThreeLines : heightDefault) + (hasTags() && (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) ? (isForumCell() ? addForumHeightForTags : addHeightForTags) : 0)) + (useSeparator ? 1 : 0));
checkTwoLinesForName();
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), computeHeight());
topClip = 0;
bottomClip = getMeasuredHeight();
}
private int computeHeight() {
int height;
if (isForumCell() && !isTransitionSupport && !collapsed) {
height = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 86 : 91);
if (useSeparator) {
height += 1;
}
if (hasTags()) {
height += dp(addForumHeightForTags);
}
} else {
height = getCollapsedHeight();
}
return height;
}
private int getCollapsedHeight() {
int height = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? heightThreeLines : heightDefault);
if (useSeparator) {
height += 1;
}
if (twoLinesForName) {
height += dp(20);
}
if (hasTags() && (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell())) {
height += dp(isForumCell() ? addForumHeightForTags : addHeightForTags);
}
return height;
}
private void checkTwoLinesForName() {
twoLinesForName = false;
if (isTopic && !hasTags()) {
buildLayout();
if (nameIsEllipsized) {
twoLinesForName = true;
buildLayout();
}
}
}
int lastSize;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (currentDialogId == 0 && customDialog == null) {
return;
}
if (checkBox != null) {
int paddingStart = dp(messagePaddingStart - (useForceThreeLines || SharedConfig.useThreeLinesLayout ? 29 : 27));
int x, y;
if (inPreviewMode) {
x = dp(8);//LocaleController.isRTL ? (right - left) - paddingStart : paddingStart;
y = (getMeasuredHeight() - checkBox.getMeasuredHeight()) >> 1;
} else {
x = LocaleController.isRTL ? (right - left) - paddingStart : paddingStart;
y = dp(chekBoxPaddingTop + (useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 0));
}
checkBox.layout(x, y, x + checkBox.getMeasuredWidth(), y + checkBox.getMeasuredHeight());
}
int size = getMeasuredHeight() + getMeasuredWidth() << 16;
if (size != lastSize || updateLayout) {
updateLayout = false;
lastSize = size;
try {
buildLayout();
} catch (Exception e) {
FileLog.e(e);
}
}
}
public boolean isUnread() {
return (unreadCount != 0 || markUnread) && !dialogMuted;
}
public boolean getHasUnread() {
return (unreadCount != 0 || markUnread);
}
public boolean getIsMuted() {
return dialogMuted;
}
public boolean getIsPinned() {
return drawPin || drawPinForced;
}
public void setPinForced(boolean value) {
drawPinForced = value;
if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0) {
buildLayout();
}
invalidate();
}
private CharSequence formatArchivedDialogNames() {
final MessagesController messagesController = MessagesController.getInstance(currentAccount);
ArrayList<TLRPC.Dialog> dialogs = messagesController.getDialogs(currentDialogFolderId);
currentDialogFolderDialogsCount = dialogs.size();
SpannableStringBuilder builder = new SpannableStringBuilder();
for (int a = 0, N = dialogs.size(); a < N; a++) {
TLRPC.Dialog dialog = dialogs.get(a);
TLRPC.User currentUser = null;
TLRPC.Chat currentChat = null;
if (messagesController.isHiddenByUndo(dialog.id)) {
continue;
}
if (DialogObject.isEncryptedDialog(dialog.id)) {
TLRPC.EncryptedChat encryptedChat = messagesController.getEncryptedChat(DialogObject.getEncryptedChatId(dialog.id));
if (encryptedChat != null) {
currentUser = messagesController.getUser(encryptedChat.user_id);
}
} else {
if (DialogObject.isUserDialog(dialog.id)) {
currentUser = messagesController.getUser(dialog.id);
} else {
currentChat = messagesController.getChat(-dialog.id);
}
}
String title;
if (currentChat != null) {
title = currentChat.title.replace('\n', ' ');
} else if (currentUser != null) {
if (UserObject.isDeleted(currentUser)) {
title = LocaleController.getString("HiddenName", R.string.HiddenName);
} else {
title = ContactsController.formatName(currentUser.first_name, currentUser.last_name).replace('\n', ' ');
}
} else {
continue;
}
if (builder.length() > 0) {
builder.append(", ");
}
int boldStart = builder.length();
int boldEnd = boldStart + title.length();
builder.append(title);
if (dialog.unread_count > 0) {
builder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider)), boldStart, boldEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (builder.length() > 150) {
break;
}
}
if (MessagesController.getInstance(currentAccount).storiesController.getTotalStoriesCount(true) > 0) {
int totalCount;
totalCount = Math.max(1, MessagesController.getInstance(currentAccount).storiesController.getTotalStoriesCount(true));
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(LocaleController.formatPluralString("Stories", totalCount));
}
return Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false);
}
public boolean hasTags() {
return tags != null && !tags.isEmpty();
}
public boolean separateMessageNameLine() {
return (useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags();
}
int thumbSize;
public void buildLayout() {
if (isTransitionSupport) {
return;
}
if (isDialogCell) {
boolean needUpdate = updateHelper.update();
if (!needUpdate && currentDialogFolderId == 0 && encryptedChat == null) {
return;
}
}
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
Theme.dialogs_namePaint[0].setTextSize(dp(17));
Theme.dialogs_nameEncryptedPaint[0].setTextSize(dp(17));
Theme.dialogs_messagePaint[0].setTextSize(dp(16));
Theme.dialogs_messagePrintingPaint[0].setTextSize(dp(16));
Theme.dialogs_namePaint[1].setTextSize(dp(16));
Theme.dialogs_nameEncryptedPaint[1].setTextSize(dp(16));
Theme.dialogs_messagePaint[1].setTextSize(dp(15));
Theme.dialogs_messagePrintingPaint[1].setTextSize(dp(15));
Theme.dialogs_messagePaint[1].setColor(Theme.dialogs_messagePaint[1].linkColor = Theme.getColor(Theme.key_chats_message_threeLines, resourcesProvider));
paintIndex = 1;
thumbSize = 18;
} else {
Theme.dialogs_namePaint[0].setTextSize(dp(17));
Theme.dialogs_nameEncryptedPaint[0].setTextSize(dp(17));
Theme.dialogs_messagePaint[0].setTextSize(dp(16));
Theme.dialogs_messagePrintingPaint[0].setTextSize(dp(16));
Theme.dialogs_messagePaint[0].setColor(Theme.dialogs_messagePaint[0].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider));
paintIndex = 0;
thumbSize = 19;
}
currentDialogFolderDialogsCount = 0;
CharSequence nameString = "";
String timeString = "";
String countString = null;
String mentionString = null;
CharSequence messageString = "";
CharSequence typingString = "";
CharSequence messageNameString = null;
CharSequence printingString = null;
CharSequence buttonString = null;
if (!isForumCell() && (isDialogCell || isTopic)) {
printingString = MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true);
}
currentMessagePaint = Theme.dialogs_messagePaint[paintIndex];
boolean checkMessage = true;
drawNameLock = false;
drawVerified = false;
drawPremium = false;
drawForwardIcon = false;
drawScam = 0;
drawPinBackground = false;
thumbsCount = 0;
hasVideoThumb = false;
nameLayoutEllipsizeByGradient = false;
int offsetName = 0;
boolean showChecks = !UserObject.isUserSelf(user) && !useMeForMyMessages;
boolean drawTime = true;
printingStringType = -1;
int printingStringReplaceIndex = -1;
if (!isForumCell()) {
buttonLayout = null;
}
int messageFormatType;
if (Build.VERSION.SDK_INT >= 18) {
if ((!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) || isForumCell() || hasTags()) {
//1 - "%2$s: \u2068%1$s\u2069";
messageFormatType = 1;
hasNameInMessage = true;
} else {
//2 - "\u2068%1$s\u2069";
messageFormatType = 2;
hasNameInMessage = false;
}
} else {
if ((!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0) || isForumCell() || hasTags()) {
//3 - "%2$s: %1$s";
messageFormatType = 3;
hasNameInMessage = true;
} else {
//4 - "%1$s";
messageFormatType = 4;
hasNameInMessage = false;
}
}
if (message != null) {
message.updateTranslation();
}
CharSequence msgText = message != null ? message.messageText : null;
if (msgText instanceof Spannable) {
Spannable sp = new SpannableStringBuilder(msgText);
for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderlineBold.class))
sp.removeSpan(span);
for (Object span : sp.getSpans(0, sp.length(), URLSpanNoUnderline.class))
sp.removeSpan(span);
msgText = sp;
}
lastMessageString = msgText;
if (customDialog != null) {
if (customDialog.type == 2) {
drawNameLock = true;
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
nameLockTop = dp(12.5f);
if (!LocaleController.isRTL) {
nameLockLeft = dp(messagePaddingStart + 6);
nameLeft = dp(messagePaddingStart + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
nameLeft = dp(22);
}
} else {
nameLockTop = dp(16.5f);
if (!LocaleController.isRTL) {
nameLockLeft = dp(messagePaddingStart + 4);
nameLeft = dp(messagePaddingStart + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
nameLeft = dp(18);
}
}
} else {
drawVerified = !forbidVerified && customDialog.verified;
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
if (!LocaleController.isRTL) {
nameLeft = dp(messagePaddingStart + 6);
} else {
nameLeft = dp(22);
}
} else {
if (!LocaleController.isRTL) {
nameLeft = dp(messagePaddingStart + 4);
} else {
nameLeft = dp(18);
}
}
}
if (customDialog.type == 1) {
messageNameString = LocaleController.getString("FromYou", R.string.FromYou);
checkMessage = false;
SpannableStringBuilder stringBuilder;
if (customDialog.isMedia) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
stringBuilder = formatInternal(messageFormatType, message.messageText, null);
stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
String mess = customDialog.message;
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
stringBuilder = formatInternal(messageFormatType, mess, messageNameString);
} else {
stringBuilder = formatInternal(messageFormatType, mess.replace('\n', ' '), messageNameString);
}
}
messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false);
} else {
messageString = customDialog.message;
if (customDialog.isMedia) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
}
}
timeString = LocaleController.stringForMessageListDate(customDialog.date);
if (customDialog.unread_count != 0) {
drawCount = true;
countString = String.format("%d", customDialog.unread_count);
} else {
drawCount = false;
}
if (customDialog.sent == SENT_STATE_PROGRESS) {
drawClock = true;
drawCheck1 = false;
drawCheck2 = false;
} else if (customDialog.sent == SENT_STATE_READ) {
drawCheck1 = true;
drawCheck2 = true;
drawClock = false;
} else if (customDialog.sent == SENT_STATE_SENT) {
drawCheck1 = false;
drawCheck2 = true;
drawClock = false;
} else {
drawClock = false;
drawCheck1 = false;
drawCheck2 = false;
}
drawError = false;
nameString = customDialog.name;
} else {
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
if (!LocaleController.isRTL) {
nameLeft = dp(messagePaddingStart + 6);
} else {
nameLeft = dp(22);
}
} else {
if (!LocaleController.isRTL) {
nameLeft = dp(messagePaddingStart + 4);
} else {
nameLeft = dp(18);
}
}
if (encryptedChat != null) {
if (currentDialogFolderId == 0) {
drawNameLock = true;
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
nameLockTop = dp(12.5f);
if (!LocaleController.isRTL) {
nameLockLeft = dp(messagePaddingStart + 6);
nameLeft = dp(messagePaddingStart + 10) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 6) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
nameLeft = dp(22);
}
} else {
nameLockTop = dp(16.5f);
if (!LocaleController.isRTL) {
nameLockLeft = dp(messagePaddingStart + 4);
nameLeft = dp(messagePaddingStart + 8) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = getMeasuredWidth() - dp(messagePaddingStart + 4) - Theme.dialogs_lockDrawable.getIntrinsicWidth();
nameLeft = dp(18);
}
}
}
} else {
if (currentDialogFolderId == 0) {
if (chat != null) {
if (chat.scam) {
drawScam = 1;
Theme.dialogs_scamDrawable.checkText();
} else if (chat.fake) {
drawScam = 2;
Theme.dialogs_fakeDrawable.checkText();
} else if (DialogObject.getEmojiStatusDocumentId(chat.emoji_status) != 0) {
drawPremium = true;
nameLayoutEllipsizeByGradient = true;
emojiStatus.center = LocaleController.isRTL;
emojiStatus.set(DialogObject.getEmojiStatusDocumentId(chat.emoji_status), false);
} else {
drawVerified = !forbidVerified && chat.verified;
}
} else if (user != null) {
if (user.scam) {
drawScam = 1;
Theme.dialogs_scamDrawable.checkText();
} else if (user.fake) {
drawScam = 2;
Theme.dialogs_fakeDrawable.checkText();
} else {
drawVerified =!forbidVerified && user.verified;
}
drawPremium = MessagesController.getInstance(currentAccount).isPremiumUser(user) && UserConfig.getInstance(currentAccount).clientUserId != user.id && user.id != 0;
if (drawPremium) {
Long emojiStatusId = UserObject.getEmojiStatusDocumentId(user);
emojiStatus.center = LocaleController.isRTL;
if (emojiStatusId != null) {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(emojiStatusId, false);
} else {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, false);
}
}
}
}
}
int lastDate = lastMessageDate;
if (lastMessageDate == 0 && message != null) {
lastDate = message.messageOwner.date;
}
if (isTopic) {
draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null;
draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, getTopicId()) : null;
if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) {
draftMessage = null;
}
} else if (isDialogCell || isSavedDialogCell) {
draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null;
draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, 0) : null;
} else {
draftVoice = false;
draftMessage = null;
}
if ((draftVoice || draftMessage != null) && (!draftVoice && draftMessage != null && TextUtils.isEmpty(draftMessage.message) && (draftMessage.reply_to == null || draftMessage.reply_to.reply_to_msg_id == 0) || draftMessage != null && lastDate > draftMessage.date && unreadCount != 0) ||
ChatObject.isChannel(chat) && !chat.megagroup && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) ||
chat != null && (chat.left || chat.kicked) || forbidDraft || ChatObject.isForum(chat) && !isTopic) {
draftMessage = null;
draftVoice = false;
}
if (isForumCell()) {
draftMessage = null;
draftVoice = false;
needEmoji = true;
updateMessageThumbs();
messageNameString = getMessageNameString();
messageString = formatTopicsNames();
String restrictionReason = message != null ? MessagesController.getRestrictionReason(message.messageOwner.restriction_reason) : null;
buttonString = message != null ? getMessageStringFormatted(messageFormatType, restrictionReason, messageNameString, true) : "";
if (applyName && buttonString.length() >= 0 && messageNameString != null) {
SpannableStringBuilder spannableStringBuilder = SpannableStringBuilder.valueOf(buttonString);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_name, resourcesProvider), 0, Math.min(spannableStringBuilder.length(), messageNameString.length() + 1), 0);
buttonString = spannableStringBuilder;
}
currentMessagePaint = Theme.dialogs_messagePaint[paintIndex];
} else {
if (printingString != null) {
lastPrintString = printingString;
printingStringType = MessagesController.getInstance(currentAccount).getPrintingStringType(currentDialogId, getTopicId());
StatusDrawable statusDrawable = Theme.getChatStatusDrawable(printingStringType);
int startPadding = 0;
if (statusDrawable != null) {
startPadding = statusDrawable.getIntrinsicWidth() + dp(3);
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
printingString = TextUtils.replace(printingString, new String[]{"..."}, new String[]{""});
if (printingStringType == 5) {
printingStringReplaceIndex = printingString.toString().indexOf("**oo**");
}
if (printingStringReplaceIndex >= 0) {
spannableStringBuilder.append(printingString).setSpan(new FixedWidthSpan(Theme.getChatStatusDrawable(printingStringType).getIntrinsicWidth()), printingStringReplaceIndex, printingStringReplaceIndex + 6, 0);
} else {
spannableStringBuilder.append(" ").append(printingString).setSpan(new FixedWidthSpan(startPadding), 0, 1, 0);
}
typingString = spannableStringBuilder;
checkMessage = false;
} else {
lastPrintString = null;
printingStringType = -1;
}
if (draftVoice || draftMessage != null) {
checkMessage = false;
messageNameString = LocaleController.getString("Draft", R.string.Draft);
if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) {
if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) {
messageString = "";
} else {
SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(messageNameString);
stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
messageString = stringBuilder;
}
} else {
String mess;
if (draftVoice) {
mess = LocaleController.getString(R.string.AttachAudio);
} else if (draftMessage != null) {
mess = draftMessage.message;
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
} else {
mess = "";
}
Spannable messSpan = new SpannableStringBuilder(mess);
if (draftMessage != null) {
MediaDataController.addTextStyleRuns(draftMessage, messSpan, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE);
if (draftMessage != null && draftMessage.entities != null) {
MediaDataController.addAnimatedEmojiSpans(draftMessage.entities, messSpan, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt());
}
} else if (draftVoice) {
messSpan.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_actionMessage, resourcesProvider), 0, messSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
SpannableStringBuilder stringBuilder = formatInternal(messageFormatType, AndroidUtilities.replaceNewLines(messSpan), messageNameString);
if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags()) {
stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false);
}
} else {
if (clearingDialog) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
messageString = LocaleController.getString("HistoryCleared", R.string.HistoryCleared);
} else if (message == null) {
if (currentDialogFolderId != 0) {
messageString = formatArchivedDialogNames();
} else if (encryptedChat != null) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
messageString = LocaleController.getString("EncryptionProcessing", R.string.EncryptionProcessing);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
messageString = LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, UserObject.getFirstName(user));
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
if (encryptedChat.admin_id == UserConfig.getInstance(currentAccount).getClientUserId()) {
messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, UserObject.getFirstName(user));
} else {
messageString = LocaleController.getString("EncryptedChatStartedIncoming", R.string.EncryptedChatStartedIncoming);
}
}
} else {
if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && UserObject.isUserSelf(user)) {
messageString = LocaleController.getString(parentFragment != null && parentFragment.isQuote ? R.string.SavedMessagesInfoQuote : R.string.SavedMessagesInfo);
showChecks = false;
drawTime = false;
} else {
messageString = "";
}
}
} else {
String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason);
TLRPC.User fromUser = null;
TLRPC.Chat fromChat = null;
long fromId = message.getFromChatId();
if (DialogObject.isUserDialog(fromId)) {
fromUser = MessagesController.getInstance(currentAccount).getUser(fromId);
} else {
fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId);
}
drawCount2 = true;
boolean lastMessageIsReaction = false;
if (dialogsType == 0 && currentDialogId > 0 && message.isOutOwner() && message.messageOwner.reactions != null && message.messageOwner.reactions.recent_reactions != null && !message.messageOwner.reactions.recent_reactions.isEmpty() && reactionMentionCount > 0) {
TLRPC.MessagePeerReaction lastReaction = message.messageOwner.reactions.recent_reactions.get(0);
if (lastReaction.unread && lastReaction.peer_id.user_id != 0 &&lastReaction.peer_id.user_id != UserConfig.getInstance(currentAccount).clientUserId) {
lastMessageIsReaction = true;
ReactionsLayoutInBubble.VisibleReaction visibleReaction = ReactionsLayoutInBubble.VisibleReaction.fromTLReaction(lastReaction.reaction);
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
if (visibleReaction.emojicon != null) {
messageString = LocaleController.formatString("ReactionInDialog", R.string.ReactionInDialog, visibleReaction.emojicon);
} else {
String string = LocaleController.formatString("ReactionInDialog", R.string.ReactionInDialog, "**reaction**");
int i = string.indexOf("**reaction**");
string = string.replace("**reaction**", "d");
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(string);
spannableStringBuilder.setSpan(new AnimatedEmojiSpan(visibleReaction.documentId, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt()), i, i + 1, 0);
messageString = spannableStringBuilder;
}
}
}
if (lastMessageIsReaction) {
} else if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO) {
if (chat != null) {
if (ChatObject.isChannel(chat) && !chat.megagroup) {
if (chat.participants_count != 0) {
messageString = LocaleController.formatPluralStringComma("Subscribers", chat.participants_count);
} else {
if (!ChatObject.isPublic(chat)) {
messageString = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate).toLowerCase();
} else {
messageString = LocaleController.getString("ChannelPublic", R.string.ChannelPublic).toLowerCase();
}
}
} else {
if (chat.participants_count != 0) {
messageString = LocaleController.formatPluralStringComma("Members", chat.participants_count);
} else {
if (chat.has_geo) {
messageString = LocaleController.getString("MegaLocation", R.string.MegaLocation);
} else if (!ChatObject.isPublic(chat)) {
messageString = LocaleController.getString("MegaPrivate", R.string.MegaPrivate).toLowerCase();
} else {
messageString = LocaleController.getString("MegaPublic", R.string.MegaPublic).toLowerCase();
}
}
}
} else {
messageString = "";
}
drawCount2 = false;
showChecks = false;
drawTime = false;
} else if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && UserObject.isUserSelf(user)) {
messageString = LocaleController.getString(parentFragment != null && parentFragment.isQuote ? R.string.SavedMessagesInfoQuote : R.string.SavedMessagesInfo);
showChecks = false;
drawTime = false;
} else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout && currentDialogFolderId != 0) {
checkMessage = false;
messageString = formatArchivedDialogNames();
} else if (message.messageOwner instanceof TLRPC.TL_messageService && (!MessageObject.isTopicActionMessage(message) || message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate)) {
if (ChatObject.isChannelAndNotMegaGroup(chat) && (message.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom)) {
messageString = "";
showChecks = false;
} else {
messageString = msgText;
}
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
if (message.type == MessageObject.TYPE_SUGGEST_PHOTO) {
updateMessageThumbs();
messageString = applyThumbs(messageString);
}
} else {
needEmoji = true;
updateMessageThumbs();
String triedMessageName = null;
if (!isSavedDialog && user != null && user.self && !message.isOutOwner()) {
triedMessageName = getMessageNameString();
}
if (isSavedDialog && user != null && !user.self && message != null && message.isOutOwner() || triedMessageName != null || chat != null && chat.id > 0 && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat)) && !ForumUtilities.isTopicCreateMessage(message)) {
messageNameString = triedMessageName != null ? triedMessageName : getMessageNameString();
if (chat != null && chat.forum && !isTopic && !useFromUserAsAvatar) {
CharSequence topicName = MessagesController.getInstance(currentAccount).getTopicsController().getTopicIconName(chat, message, currentMessagePaint);
if (!TextUtils.isEmpty(topicName)) {
SpannableStringBuilder arrowSpan = new SpannableStringBuilder("-");
ColoredImageSpan coloredImageSpan = new ColoredImageSpan(ContextCompat.getDrawable(ApplicationLoader.applicationContext, R.drawable.msg_mini_forumarrow).mutate());
coloredImageSpan.setColorKey(useForceThreeLines || SharedConfig.useThreeLinesLayout ? -1 : Theme.key_chats_nameMessage);
arrowSpan.setSpan(coloredImageSpan, 0, 1, 0);
SpannableStringBuilder nameSpannableString = new SpannableStringBuilder();
nameSpannableString.append(messageNameString).append(arrowSpan).append(topicName);
messageNameString = nameSpannableString;
}
}
checkMessage = false;
SpannableStringBuilder stringBuilder = getMessageStringFormatted(messageFormatType, restrictionReason, messageNameString, false);
int thumbInsertIndex = 0;
if (!useFromUserAsAvatar && (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0 && stringBuilder.length() > 0)) {
try {
stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage, resourcesProvider), 0, thumbInsertIndex = messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
offsetName = thumbInsertIndex;
} catch (Exception e) {
FileLog.e(e);
}
}
messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(20), false);
if (message.hasHighlightedWords()) {
CharSequence messageH = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
if (messageH != null) {
messageString = messageH;
}
}
if (thumbsCount > 0) {
if (!(messageString instanceof SpannableStringBuilder)) {
messageString = new SpannableStringBuilder(messageString);
}
checkMessage = false;
SpannableStringBuilder builder = (SpannableStringBuilder) messageString;
if (thumbInsertIndex >= builder.length()) {
builder.append(" ");
builder.setSpan(new FixedWidthSpan(dp(thumbsCount * (thumbSize + 2) - 2 + 5)), builder.length() - 1, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
builder.insert(thumbInsertIndex, " ");
builder.setSpan(new FixedWidthSpan(dp(thumbsCount * (thumbSize + 2) - 2 + 5)), thumbInsertIndex, thumbInsertIndex + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} else {
if (!TextUtils.isEmpty(restrictionReason)) {
messageString = restrictionReason;
} else if (MessageObject.isTopicActionMessage(message)) {
if (message.messageTextShort != null && (!(message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate) || !isTopic)) {
messageString = message.messageTextShort;
} else {
messageString = message.messageText;
}
if (message.topicIconDrawable[0] instanceof ForumBubbleDrawable) {
TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-message.getDialogId(), MessageObject.getTopicId(currentAccount, message.messageOwner, true));
if (topic != null) {
((ForumBubbleDrawable) message.topicIconDrawable[0]).setColor(topic.icon_color);
}
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty && message.messageOwner.media.ttl_seconds != 0) {
messageString = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired);
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && (message.messageOwner.media.document instanceof TLRPC.TL_documentEmpty || message.messageOwner.media.document == null) && message.messageOwner.media.ttl_seconds != 0) {
if (message.messageOwner.media.voice) {
messageString = LocaleController.getString(R.string.AttachVoiceExpired);
} else if (message.messageOwner.media.round) {
messageString = LocaleController.getString(R.string.AttachRoundExpired);
} else {
messageString = LocaleController.getString(R.string.AttachVideoExpired);
}
} else if (getCaptionMessage() != null) {
MessageObject message = getCaptionMessage();
String emoji;
if (!needEmoji) {
emoji = "";
} else if (message.isVideo()) {
emoji = "\uD83D\uDCF9 ";
} else if (message.isVoice()) {
emoji = "\uD83C\uDFA4 ";
} else if (message.isMusic()) {
emoji = "\uD83C\uDFA7 ";
} else if (message.isPhoto()) {
emoji = "\uD83D\uDDBC ";
} else {
emoji = "\uD83D\uDCCE ";
}
if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
CharSequence text = message.messageTrimmedToHighlight;
int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 24);
if (hasNameInMessage) {
if (!TextUtils.isEmpty(messageNameString)) {
w -= currentMessagePaint.measureText(messageNameString.toString());
}
w -= currentMessagePaint.measureText(": ");
}
if (w > 0) {
text = AndroidUtilities.ellipsizeCenterEnd(text, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
}
messageString = new SpannableStringBuilder(emoji).append(text);
} else {
SpannableStringBuilder msgBuilder = new SpannableStringBuilder(message.caption);
if (message != null && message.messageOwner != null) {
if (message != null) {
message.spoilLoginCode();
}
MediaDataController.addTextStyleRuns(message.messageOwner.entities, message.caption, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE);
MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, msgBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt());
}
messageString = new SpannableStringBuilder(emoji).append(msgBuilder);
}
} else if (thumbsCount > 1) {
if (hasVideoThumb) {
messageString = LocaleController.formatPluralString("Media", groupMessages == null ? 0 : groupMessages.size());
} else {
messageString = LocaleController.formatPluralString("Photos", groupMessages == null ? 0 : groupMessages.size());
}
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
} else {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGiveaway) {
boolean isChannel;
if (message.messageOwner.fwd_from != null && message.messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerChannel) {
isChannel = ChatObject.isChannelAndNotMegaGroup(message.messageOwner.fwd_from.from_id.channel_id, currentAccount);
} else {
isChannel = ChatObject.isChannelAndNotMegaGroup(chat);
}
messageString = LocaleController.getString(isChannel ? R.string.BoostingGiveawayChannelStarted : R.string.BoostingGiveawayGroupStarted);
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGiveawayResults) {
messageString = LocaleController.getString("BoostingGiveawayResults", R.string.BoostingGiveawayResults);
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) {
SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text);
MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText);
MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt());
messageString = new SpannableStringBuilder("\uD83D\uDCCA ").append(questionText);
} else {
messageString = "\uD83D\uDCCA " + mediaPoll.poll.question.text;
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
messageString = "\uD83C\uDFAE " + message.messageOwner.media.game.title;
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) {
messageString = message.messageOwner.media.title;
} else if (message.type == MessageObject.TYPE_MUSIC) {
messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle());
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaStory && message.messageOwner.media.via_mention) {
if (message.isOut()) {
long did = message.getDialogId();
String username = "";
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did);
if (user != null) {
username = UserObject.getFirstName(user);
int index;
if ((index = username.indexOf(' ')) >= 0) {
username = username.substring(0, index);
}
}
messageString = LocaleController.formatString("StoryYouMentionInDialog", R.string.StoryYouMentionInDialog, username);
} else {
messageString = LocaleController.getString("StoryMentionInDialog", R.string.StoryMentionInDialog);
}
} else {
if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)){
messageString = message.messageTrimmedToHighlight;
if (message.messageTrimmedToHighlight != null) {
messageString = message.messageTrimmedToHighlight;
}
int w = getMeasuredWidth() - dp(messagePaddingStart + 23 );
messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130);
} else {
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(msgText);
if (message != null) {
message.spoilLoginCode();
}
MediaDataController.addTextStyleRuns(message, stringBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE);
if (message != null && message.messageOwner != null) {
MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, stringBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt());
}
messageString = stringBuilder;
}
AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
}
if (message.messageOwner.media != null && !message.isMediaEmpty()) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
}
}
if (message.isReplyToStory()) {
SpannableStringBuilder builder = new SpannableStringBuilder(messageString);
builder.insert(0, "d ");
builder.setSpan(new ColoredImageSpan(ContextCompat.getDrawable(getContext(), R.drawable.msg_mini_replystory).mutate()), 0, 1, 0);
messageString = builder;
}
if (thumbsCount > 0) {
if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
messageString = message.messageTrimmedToHighlight;
if (message.messageTrimmedToHighlight != null) {
messageString = message.messageTrimmedToHighlight;
}
int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + (thumbSize + 2) * thumbsCount - 2 + 5);
messageString = AndroidUtilities.ellipsizeCenterEnd(messageString, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
} else {
if (messageString.length() > 150) {
messageString = messageString.subSequence(0, 150);
}
messageString = AndroidUtilities.replaceNewLines(messageString);
}
if (!(messageString instanceof SpannableStringBuilder)) {
messageString = new SpannableStringBuilder(messageString);
}
checkMessage = false;
SpannableStringBuilder builder = (SpannableStringBuilder) messageString;
builder.insert(0, " ");
builder.setSpan(new FixedWidthSpan(dp((thumbSize + 2) * thumbsCount - 2 + 5)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false);
if (message.hasHighlightedWords()) {
CharSequence s = AndroidUtilities.highlightText(builder, message.highlightedWords, resourcesProvider);
if (s != null) {
messageString = s;
}
}
}
if (message.isForwarded() && message.needDrawForwarded()) {
drawForwardIcon = true;
SpannableStringBuilder builder = new SpannableStringBuilder(messageString);
builder.insert(0, "d ");
ColoredImageSpan coloredImageSpan = new ColoredImageSpan(ContextCompat.getDrawable(getContext(), R.drawable.mini_forwarded).mutate());
coloredImageSpan.setAlpha(0.9f);
builder.setSpan(coloredImageSpan, 0, 1, 0);
messageString = builder;
}
}
}
if (currentDialogFolderId != 0) {
messageNameString = formatArchivedDialogNames();
}
}
}
}
if (draftMessage != null) {
timeString = LocaleController.stringForMessageListDate(draftMessage.date);
} else if (lastMessageDate != 0) {
timeString = LocaleController.stringForMessageListDate(lastMessageDate);
} else if (message != null) {
timeString = LocaleController.stringForMessageListDate(message.messageOwner.date);
}
if (message == null || isSavedDialog) {
drawCheck1 = false;
drawCheck2 = false;
drawClock = message != null && message.isSending() && currentDialogId == UserConfig.getInstance(currentAccount).getClientUserId();
drawCount = false;
drawMention = false;
drawReactionMention = false;
drawError = false;
} else {
if (currentDialogFolderId != 0) {
if (unreadCount + mentionCount > 0) {
if (unreadCount > mentionCount) {
drawCount = true;
drawMention = false;
countString = String.format("%d", unreadCount + mentionCount);
} else {
drawCount = false;
drawMention = true;
mentionString = String.format("%d", unreadCount + mentionCount);
}
} else {
drawCount = false;
drawMention = false;
}
drawReactionMention = false;
} else {
if (clearingDialog) {
drawCount = false;
showChecks = false;
} else if (unreadCount != 0 && (unreadCount != 1 || unreadCount != mentionCount || message == null || !message.messageOwner.mentioned)) {
drawCount = true;
countString = String.format("%d", unreadCount);
} else if (markUnread) {
drawCount = true;
countString = "";
} else {
drawCount = false;
}
if (mentionCount != 0) {
drawMention = true;
mentionString = "@";
} else {
drawMention = false;
}
if (reactionMentionCount > 0) {
drawReactionMention = true;
} else {
drawReactionMention = false;
}
}
if (message.isOut() && draftMessage == null && showChecks && !(message.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear)) {
if (message.isSending()) {
drawCheck1 = false;
drawCheck2 = false;
drawClock = true;
drawError = false;
} else if (message.isSendError()) {
drawCheck1 = false;
drawCheck2 = false;
drawClock = false;
drawError = true;
drawCount = false;
drawMention = false;
} else if (message.isSent()) {
if (forumTopic != null) {
drawCheck1 = forumTopic.read_outbox_max_id >= message.getId();
} else if (isDialogCell) {
drawCheck1 = (readOutboxMaxId > 0 && readOutboxMaxId >= message.getId()) || !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup;
} else {
drawCheck1 = !message.isUnread() || ChatObject.isChannel(chat) && !chat.megagroup;
}
drawCheck2 = true;
drawClock = false;
drawError = false;
}
} else {
drawCheck1 = false;
drawCheck2 = false;
drawClock = false;
drawError = false;
}
}
promoDialog = false;
MessagesController messagesController = MessagesController.getInstance(currentAccount);
if (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT && messagesController.isPromoDialog(currentDialogId, true)) {
drawPinBackground = true;
promoDialog = true;
if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PROXY) {
timeString = LocaleController.getString("UseProxySponsor", R.string.UseProxySponsor);
} else if (messagesController.promoDialogType == MessagesController.PROMO_TYPE_PSA) {
timeString = LocaleController.getString("PsaType_" + messagesController.promoPsaType);
if (TextUtils.isEmpty(timeString)) {
timeString = LocaleController.getString("PsaTypeDefault", R.string.PsaTypeDefault);
}
if (!TextUtils.isEmpty(messagesController.promoPsaMessage)) {
messageString = messagesController.promoPsaMessage;
thumbsCount = 0;
}
}
}
if (currentDialogFolderId != 0) {
nameString = LocaleController.getString("ArchivedChats", R.string.ArchivedChats);
} else {
if (chat != null) {
if (useFromUserAsAvatar) {
if (topicIconInName == null) {
topicIconInName = new Drawable[1];
}
topicIconInName[0] = null;
nameString = MessagesController.getInstance(currentAccount).getTopicsController().getTopicIconName(chat, message, currentMessagePaint, topicIconInName);
if (nameString == null) {
nameString = "";
}
} else if (isTopic) {
if (topicIconInName == null) {
topicIconInName = new Drawable[1];
}
topicIconInName[0] = null;
nameString = showTopicIconInName ? ForumUtilities.getTopicSpannedName(forumTopic, Theme.dialogs_namePaint[paintIndex], topicIconInName, false) : forumTopic.title;
} else {
nameString = chat.title;
}
} else if (user != null) {
if (UserObject.isReplyUser(user)) {
nameString = LocaleController.getString("RepliesTitle", R.string.RepliesTitle);
} else if (UserObject.isAnonymous(user)) {
nameString = LocaleController.getString(R.string.AnonymousForward);
} else if (UserObject.isUserSelf(user)) {
if (isSavedDialog) {
nameString = LocaleController.getString(R.string.MyNotes);
} else if (useMeForMyMessages) {
nameString = LocaleController.getString("FromYou", R.string.FromYou);
} else {
if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD) {
drawPinBackground = true;
}
nameString = LocaleController.getString("SavedMessages", R.string.SavedMessages);
}
} else {
nameString = UserObject.getUserName(user);
}
}
if (nameString != null && nameString.length() == 0) {
nameString = LocaleController.getString("HiddenName", R.string.HiddenName);
}
}
}
int timeWidth;
if (drawTime) {
timeWidth = (int) Math.ceil(Theme.dialogs_timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, Theme.dialogs_timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!LocaleController.isRTL) {
timeLeft = getMeasuredWidth() - dp(15) - timeWidth;
} else {
timeLeft = dp(15);
}
} else {
timeWidth = 0;
timeLayout = null;
timeLeft = 0;
}
int timeLeftOffset = 0;
if (drawLock2()) {
if (LocaleController.isRTL) {
lock2Left = timeLeft + timeWidth + dp(4);
} else {
lock2Left = timeLeft - Theme.dialogs_lock2Drawable.getIntrinsicWidth() - dp(4);
}
timeLeftOffset += Theme.dialogs_lock2Drawable.getIntrinsicWidth() + dp(4);
timeWidth += timeLeftOffset;
}
if (!LocaleController.isRTL) {
nameWidth = getMeasuredWidth() - nameLeft - dp(14 + 8) - timeWidth;
} else {
nameWidth = getMeasuredWidth() - nameLeft - dp(messagePaddingStart + 5 + 8) - timeWidth;
nameLeft += timeWidth;
}
if (drawNameLock) {
nameWidth -= dp(LocaleController.isRTL ? 8 : 4) + Theme.dialogs_lockDrawable.getIntrinsicWidth();
}
if (drawClock) {
int w = Theme.dialogs_clockDrawable.getIntrinsicWidth() + dp(5);
nameWidth -= w;
if (!LocaleController.isRTL) {
clockDrawLeft = timeLeft - timeLeftOffset - w;
} else {
clockDrawLeft = timeLeft + timeWidth + dp(5);
nameLeft += w;
}
} else if (drawCheck2) {
int w = Theme.dialogs_checkDrawable.getIntrinsicWidth() + dp(5);
nameWidth -= w;
if (drawCheck1) {
nameWidth -= Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - dp(8);
if (!LocaleController.isRTL) {
halfCheckDrawLeft = timeLeft - timeLeftOffset - w;
checkDrawLeft = halfCheckDrawLeft - dp(5.5f);
} else {
checkDrawLeft = timeLeft + timeWidth + dp(5);
halfCheckDrawLeft = checkDrawLeft + dp(5.5f);
nameLeft += w + Theme.dialogs_halfCheckDrawable.getIntrinsicWidth() - dp(8);
}
} else {
if (!LocaleController.isRTL) {
checkDrawLeft1 = timeLeft - timeLeftOffset - w;
} else {
checkDrawLeft1 = timeLeft + timeWidth + dp(5);
nameLeft += w;
}
}
}
if (drawPremium && emojiStatus.getDrawable() != null) {
int w = dp(6 + 24 + 6);
nameWidth -= w;
if (LocaleController.isRTL) {
nameLeft += w;
}
} else if ((dialogMuted || drawUnmute) && !drawVerified && drawScam == 0) {
int w = dp(6) + Theme.dialogs_muteDrawable.getIntrinsicWidth();
nameWidth -= w;
if (LocaleController.isRTL) {
nameLeft += w;
}
} else if (drawVerified) {
int w = dp(6) + Theme.dialogs_verifiedDrawable.getIntrinsicWidth();
nameWidth -= w;
if (LocaleController.isRTL) {
nameLeft += w;
}
} else if (drawPremium) {
int w = dp(6 + 24 + 6);
nameWidth -= w;
if (LocaleController.isRTL) {
nameLeft += w;
}
} else if (drawScam != 0) {
int w = dp(6) + (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth();
nameWidth -= w;
if (LocaleController.isRTL) {
nameLeft += w;
}
}
try {
int ellipsizeWidth = nameWidth - dp(12);
if (ellipsizeWidth < 0) {
ellipsizeWidth = 0;
}
if (nameString instanceof String) {
nameString = ((String) nameString).replace('\n', ' ');
}
CharSequence nameStringFinal = nameString;
if (nameLayoutEllipsizeByGradient) {
nameLayoutFits = nameStringFinal.length() == TextUtils.ellipsize(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, TextUtils.TruncateAt.END).length();
ellipsizeWidth += dp(48);
}
nameIsEllipsized = Theme.dialogs_namePaint[paintIndex].measureText(nameStringFinal.toString()) > ellipsizeWidth;
if (!twoLinesForName) {
nameStringFinal = TextUtils.ellipsize(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, TextUtils.TruncateAt.END);
}
nameStringFinal = Emoji.replaceEmoji(nameStringFinal, Theme.dialogs_namePaint[paintIndex].getFontMetricsInt(), dp(20), false);
if (message != null && message.hasHighlightedWords()) {
CharSequence s = AndroidUtilities.highlightText(nameStringFinal, message.highlightedWords, resourcesProvider);
if (s != null) {
nameStringFinal = s;
}
}
if (twoLinesForName) {
nameLayout = StaticLayoutEx.createStaticLayout(nameStringFinal, Theme.dialogs_namePaint[paintIndex], ellipsizeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, ellipsizeWidth, 2);
} else {
nameLayout = new StaticLayout(nameStringFinal, Theme.dialogs_namePaint[paintIndex], Math.max(ellipsizeWidth, nameWidth), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
nameLayoutTranslateX = nameLayoutEllipsizeByGradient && nameLayout.isRtlCharAt(0) ? -dp(36) : 0;
nameLayoutEllipsizeLeft = nameLayout.isRtlCharAt(0);
} catch (Exception e) {
FileLog.e(e);
}
animatedEmojiStackName = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStackName, nameLayout);
int messageWidth;
int avatarLeft;
int avatarTop;
int thumbLeft;
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
avatarTop = dp(11);
messageNameTop = dp(32);
timeTop = dp(13);
errorTop = dp(43);
pinTop = dp(43);
countTop = dp(43);
checkDrawTop = dp(13);
messageWidth = getMeasuredWidth() - dp(messagePaddingStart + 21);
if (LocaleController.isRTL) {
buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(16);
avatarLeft = getMeasuredWidth() - dp(56 + avatarStart);
thumbLeft = avatarLeft - dp(13 + 18);
} else {
buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(messagePaddingStart + 6);
avatarLeft = dp(avatarStart);
thumbLeft = avatarLeft + dp(56 + 13);
}
storyParams.originalAvatarRect.set(avatarLeft, avatarTop, avatarLeft + dp(56), avatarTop + dp(56));
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageCoords(thumbLeft + (thumbSize + 2) * i, avatarTop + dp(31) + (twoLinesForName ? dp(20) : 0) - (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) && tags != null && !tags.isEmpty() ? dp(9) : 0), dp(18), dp(18));
}
} else {
avatarTop = dp(9);
messageNameTop = dp(31);
timeTop = dp(16);
errorTop = dp(39);
pinTop = dp(39);
countTop = isTopic ? dp(36) : dp(39);
checkDrawTop = dp(17);
messageWidth = getMeasuredWidth() - dp(messagePaddingStart + 23 - (LocaleController.isRTL ? 0 : 12));
if (LocaleController.isRTL) {
buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(22);
avatarLeft = getMeasuredWidth() - dp(54 + avatarStart);
thumbLeft = avatarLeft - dp(11 + (thumbsCount * (thumbSize + 2) - 2));
} else {
buttonLeft = typingLeft = messageLeft = messageNameLeft = dp(messagePaddingStart + 4);
avatarLeft = dp(avatarStart);
thumbLeft = avatarLeft + dp(56 + 11);
}
storyParams.originalAvatarRect.set(avatarLeft, avatarTop, avatarLeft + dp(54), avatarTop + dp(54));
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageCoords(thumbLeft + (thumbSize + 2) * i, avatarTop + dp(30) + (twoLinesForName ? dp(20) : 0) - (!(useForceThreeLines || SharedConfig.useThreeLinesLayout) && tags != null && !tags.isEmpty() ? dp(9) : 0), dp(thumbSize), dp(thumbSize));
}
}
if (LocaleController.isRTL) {
tagsRight = getMeasuredWidth() - dp(messagePaddingStart);
tagsLeft = dp(64);
} else {
tagsLeft = messageLeft;
tagsRight = getMeasuredWidth() - dp(64);
}
if (twoLinesForName) {
messageNameTop += dp(20);
}
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && tags != null && !tags.isEmpty()) {
timeTop -= dp(6);
checkDrawTop -= dp(6);
}
if (getIsPinned()) {
if (!LocaleController.isRTL) {
pinLeft = getMeasuredWidth() - Theme.dialogs_pinnedDrawable.getIntrinsicWidth() - dp(14);
} else {
pinLeft = dp(14);
}
}
if (drawError) {
int w = dp(23 + 8);
messageWidth -= w;
if (!LocaleController.isRTL) {
errorLeft = getMeasuredWidth() - dp(23 + 11);
} else {
errorLeft = dp(11);
messageLeft += w;
typingLeft += w;
buttonLeft += w;
messageNameLeft += w;
}
} else if (countString != null || mentionString != null || drawReactionMention) {
if (countString != null) {
countWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(countString)));
countLayout = new StaticLayout(countString, Theme.dialogs_countTextPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
int w = countWidth + dp(18);
messageWidth -= w;
if (!LocaleController.isRTL) {
countLeft = getMeasuredWidth() - countWidth - dp(20);
} else {
countLeft = dp(20);
messageLeft += w;
typingLeft += w;
buttonLeft += w;
messageNameLeft += w;
}
drawCount = true;
} else {
countWidth = 0;
}
if (mentionString != null) {
if (currentDialogFolderId != 0) {
mentionWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(mentionString)));
mentionLayout = new StaticLayout(mentionString, Theme.dialogs_countTextPaint, mentionWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
} else {
mentionWidth = dp(12);
}
int w = mentionWidth + dp(18);
messageWidth -= w;
if (!LocaleController.isRTL) {
mentionLeft = getMeasuredWidth() - mentionWidth - dp(20) - (countWidth != 0 ? countWidth + dp(18) : 0);
} else {
mentionLeft = dp(20) + (countWidth != 0 ? countWidth + dp(18) : 0);
messageLeft += w;
typingLeft += w;
buttonLeft += w;
messageNameLeft += w;
}
drawMention = true;
} else {
mentionWidth = 0;
}
if (drawReactionMention) {
int w = dp(24);
messageWidth -= w;
if (!LocaleController.isRTL) {
reactionMentionLeft = getMeasuredWidth() - dp(32);
if (drawMention) {
reactionMentionLeft -= (mentionWidth != 0 ? (mentionWidth + dp(18)) : 0);
}
if (drawCount) {
reactionMentionLeft -= (countWidth != 0 ? countWidth + dp(18) : 0);
}
} else {
reactionMentionLeft = dp(20);
if (drawMention) {
reactionMentionLeft += (mentionWidth != 0 ? (mentionWidth + dp(18)) : 0);
}
if (drawCount) {
reactionMentionLeft += (countWidth != 0 ? (countWidth + dp(18)) : 0);
}
messageLeft += w;
typingLeft += w;
buttonLeft += w;
messageNameLeft += w;
}
}
} else {
if (getIsPinned()) {
int w = Theme.dialogs_pinnedDrawable.getIntrinsicWidth() + dp(8);
messageWidth -= w;
if (LocaleController.isRTL) {
messageLeft += w;
typingLeft += w;
buttonLeft += w;
messageNameLeft += w;
}
}
drawCount = false;
drawMention = false;
}
if (checkMessage) {
if (messageString == null) {
messageString = "";
}
CharSequence mess = messageString;
if (mess.length() > 150) {
mess = mess.subSequence(0, 150);
}
if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags() || messageNameString != null) {
mess = AndroidUtilities.replaceNewLines(mess);
} else {
mess = AndroidUtilities.replaceTwoNewLinesToOne(mess);
}
messageString = Emoji.replaceEmoji(mess, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), dp(17), false);
if (message != null) {
CharSequence s = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider);
if (s != null) {
messageString = s;
}
}
}
messageWidth = Math.max(dp(12), messageWidth);
buttonTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 58 : 62);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
buttonTop -= dp(isForumCell() ? 10 : 12);
}
if (isForumCell()) {
messageTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 34 : 39);
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageY(buttonTop);
}
} else if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags() && messageNameString != null && (currentDialogFolderId == 0 || currentDialogFolderDialogsCount == 1)) {
try {
if (message != null && message.hasHighlightedWords()) {
CharSequence s = AndroidUtilities.highlightText(messageNameString, message.highlightedWords, resourcesProvider);
if (s != null) {
messageNameString = s;
}
}
messageNameLayout = StaticLayoutEx.createStaticLayout(messageNameString, Theme.dialogs_messageNamePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false, TextUtils.TruncateAt.END, messageWidth, 1);
} catch (Exception e) {
FileLog.e(e);
}
messageTop = dp(32 + 19);
int yoff = nameIsEllipsized && isTopic ? dp(20) : 0;
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageY(avatarTop + yoff + dp(40));
}
} else {
messageNameLayout = null;
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
messageTop = dp(32);
int yoff = nameIsEllipsized && isTopic ? dp(20) : 0;
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageY(avatarTop + yoff + dp(21));
}
} else {
messageTop = dp(39);
}
}
if (twoLinesForName) {
messageTop += dp(20);
}
animatedEmojiStack2 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack2, messageNameLayout);
try {
buttonCreated = false;
if (!TextUtils.isEmpty(buttonString)) {
buttonString = Emoji.replaceEmoji(buttonString, currentMessagePaint.getFontMetricsInt(), dp(17), false);
CharSequence buttonStringFinal = TextUtils.ellipsize(buttonString, currentMessagePaint, messageWidth - dp(26), TextUtils.TruncateAt.END);
buttonLayout = new StaticLayout(buttonStringFinal, currentMessagePaint, messageWidth - dp(20), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
spoilersPool2.addAll(spoilers2);
spoilers2.clear();
SpoilerEffect.addSpoilers(this, buttonLayout, spoilersPool2, spoilers2);
} else {
buttonLayout = null;
}
} catch (Exception e) {
}
animatedEmojiStack3 = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack3, buttonLayout);
try {
if (!TextUtils.isEmpty(typingString)) {
if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) {
typingLayout = StaticLayoutEx.createStaticLayout(typingString, Theme.dialogs_messagePrintingPaint[paintIndex], messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, dp(1), false, TextUtils.TruncateAt.END, messageWidth, typingString != null ? 1 : 2);
} else {
typingString = TextUtils.ellipsize(typingString, currentMessagePaint, messageWidth - dp(12), TextUtils.TruncateAt.END);
typingLayout = new StaticLayout(typingString, Theme.dialogs_messagePrintingPaint[paintIndex], messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
}
} catch (Exception e) {
FileLog.e(e);
}
try {
CharSequence messageStringFinal;
// Removing links and bold spans to get rid of underlining and boldness
if (messageString instanceof Spannable) {
Spannable messageStringSpannable = (Spannable) messageString;
for (Object span : messageStringSpannable.getSpans(0, messageStringSpannable.length(), Object.class)) {
if (span instanceof ClickableSpan || span instanceof CodeHighlighting.Span || !isFolderCell() && span instanceof TypefaceSpan || span instanceof CodeHighlighting.ColorSpan || span instanceof QuoteSpan || span instanceof QuoteSpan.QuoteStyleSpan || (span instanceof StyleSpan && ((StyleSpan) span).getStyle() == android.graphics.Typeface.BOLD)) {
messageStringSpannable.removeSpan(span);
}
}
}
if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags() && currentDialogFolderId != 0 && currentDialogFolderDialogsCount > 1) {
messageStringFinal = messageNameString;
messageNameString = null;
currentMessagePaint = Theme.dialogs_messagePaint[paintIndex];
} else if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || hasTags() || messageNameString != null) {
if (!isForumCell() && messageString instanceof Spanned && ((Spanned) messageString).getSpans(0, messageString.length(), FixedWidthSpan.class).length <= 0) {
messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - dp(12 + (thumbsCount * (thumbSize + 2) - 2) + 5), TextUtils.TruncateAt.END);
} else {
messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - dp(12), TextUtils.TruncateAt.END);
}
} else {
messageStringFinal = messageString;
}
Layout.Alignment align = isForum && LocaleController.isRTL ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL;
if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && !hasTags()) {
if (thumbsCount > 0 && messageNameString != null) {
messageWidth += dp(5);
}
messageLayout = StaticLayoutEx.createStaticLayout(messageStringFinal, currentMessagePaint, messageWidth, align, 1.0f, dp(1), false, TextUtils.TruncateAt.END, messageWidth, messageNameString != null ? 1 : 2);
} else {
if (thumbsCount > 0) {
messageWidth += dp((thumbsCount * (thumbSize + 2) - 2) + 5);
if (LocaleController.isRTL && !isForumCell()) {
messageLeft -= dp((thumbsCount * (thumbSize + 2) - 2) + 5);
}
}
messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, align, 1.0f, 0.0f, false);
}
spoilersPool.addAll(spoilers);
spoilers.clear();
SpoilerEffect.addSpoilers(this, messageLayout, -2, -2, spoilersPool, spoilers);
} catch (Exception e) {
messageLayout = null;
FileLog.e(e);
}
animatedEmojiStack = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, animatedEmojiStack, messageLayout);
double widthpx;
float left;
if (LocaleController.isRTL) {
if (nameLayout != null && nameLayout.getLineCount() > 0) {
left = nameLayout.getLineLeft(0);
widthpx = Math.ceil(nameLayout.getLineWidth(0));
nameLeft += dp(12);
if (nameLayoutEllipsizeByGradient) {
widthpx = Math.min(nameWidth, widthpx);
}
if ((dialogMuted || drawUnmute) && !drawVerified && drawScam == 0) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_muteDrawable.getIntrinsicWidth());
} else if (drawVerified) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_verifiedDrawable.getIntrinsicWidth());
} else if (drawPremium) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx - left) - dp(24));
} else if (drawScam != 0) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - (drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).getIntrinsicWidth());
} else {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - dp(6) - Theme.dialogs_muteDrawable.getIntrinsicWidth());
}
if (left == 0) {
if (widthpx < nameWidth) {
nameLeft += (nameWidth - widthpx);
}
}
}
if (messageLayout != null) {
int lineCount = messageLayout.getLineCount();
if (lineCount > 0) {
int w = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
left = messageLayout.getLineLeft(a);
if (left == 0) {
widthpx = Math.ceil(messageLayout.getLineWidth(a));
w = Math.min(w, (int) (messageWidth - widthpx));
} else {
w = 0;
break;
}
}
if (w != Integer.MAX_VALUE) {
messageLeft += w;
}
}
}
if (typingLayout != null) {
int lineCount = typingLayout.getLineCount();
if (lineCount > 0) {
int w = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
left = typingLayout.getLineLeft(a);
if (left == 0) {
widthpx = Math.ceil(typingLayout.getLineWidth(a));
w = Math.min(w, (int) (messageWidth - widthpx));
} else {
w = 0;
break;
}
}
if (w != Integer.MAX_VALUE) {
typingLeft += w;
}
}
}
if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) {
left = messageNameLayout.getLineLeft(0);
if (left == 0) {
widthpx = Math.ceil(messageNameLayout.getLineWidth(0));
if (widthpx < messageWidth) {
messageNameLeft += (messageWidth - widthpx);
}
}
}
if (buttonLayout != null) {
int lineCount = buttonLayout.getLineCount();
if (lineCount > 0) {
int rightpad = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
rightpad = (int) Math.min(rightpad, buttonLayout.getWidth() - buttonLayout.getLineRight(a));
}
buttonLeft += rightpad;
}
}
} else {
if (nameLayout != null && nameLayout.getLineCount() > 0) {
left = nameLayout.getLineRight(0);
if (nameLayoutEllipsizeByGradient) {
left = Math.min(nameWidth, left);
}
if (left == nameWidth) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (nameLayoutEllipsizeByGradient) {
widthpx = Math.min(nameWidth, widthpx);
// widthpx -= dp(36);
// left += dp(36);
}
if (widthpx < nameWidth) {
nameLeft -= (nameWidth - widthpx);
}
}
if ((dialogMuted || true) || drawUnmute || drawVerified || drawPremium || drawScam != 0) {
nameMuteLeft = (int) (nameLeft + left + dp(6));
}
}
if (messageLayout != null) {
int lineCount = messageLayout.getLineCount();
if (lineCount > 0) {
left = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
left = Math.min(left, messageLayout.getLineLeft(a));
}
messageLeft -= left;
}
}
if (buttonLayout != null) {
int lineCount = buttonLayout.getLineCount();
if (lineCount > 0) {
left = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
left = Math.min(left, buttonLayout.getLineLeft(a));
}
buttonLeft -= left;
}
}
if (typingLayout != null) {
int lineCount = typingLayout.getLineCount();
if (lineCount > 0) {
left = Integer.MAX_VALUE;
for (int a = 0; a < lineCount; a++) {
left = Math.min(left, typingLayout.getLineLeft(a));
}
typingLeft -= left;
}
}
if (messageNameLayout != null && messageNameLayout.getLineCount() > 0) {
messageNameLeft -= messageNameLayout.getLineLeft(0);
}
}
if (typingLayout != null && printingStringType >= 0 && typingLayout.getText().length() > 0) {
float x1, x2;
if (printingStringReplaceIndex >= 0 && printingStringReplaceIndex + 1 < typingLayout.getText().length() ){
x1 = typingLayout.getPrimaryHorizontal(printingStringReplaceIndex);
x2 = typingLayout.getPrimaryHorizontal(printingStringReplaceIndex + 1);
} else {
x1 = typingLayout.getPrimaryHorizontal(0);
x2 = typingLayout.getPrimaryHorizontal(1);
}
if (x1 < x2) {
statusDrawableLeft = (int) (typingLeft + x1);
} else {
statusDrawableLeft = (int) (typingLeft + x2 + dp(3));
}
}
updateThumbsPosition();
}
private SpannableStringBuilder formatInternal(int messageFormatType, CharSequence s1, CharSequence s2) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
switch (messageFormatType) {
case 1:
//"%2$s: \u2068%1$s\u2069"
spannableStringBuilder.append(s2).append(": \u2068").append(s1).append("\u2069");
break;
case 2:
//"\u2068%1$s\u2069"
spannableStringBuilder.append("\u2068").append(s1).append("\u2069");
break;
case 3:
//"%2$s: %1$s"
spannableStringBuilder.append(s2).append(": ").append(s1);
break;
case 4:
//"%1$s"
spannableStringBuilder.append(s1);
break;
}
return spannableStringBuilder;
}
private void updateThumbsPosition() {
if (thumbsCount > 0) {
StaticLayout layout = isForumCell() ? buttonLayout : messageLayout;
int left = isForumCell() ? buttonLeft : messageLeft;
if (layout == null) {
return;
}
try {
CharSequence text = layout.getText();
if (text instanceof Spanned) {
FixedWidthSpan[] spans = ((Spanned) text).getSpans(0, text.length(), FixedWidthSpan.class);
if (spans != null && spans.length > 0) {
int spanOffset = ((Spanned) text).getSpanStart(spans[0]);
if (spanOffset < 0) {
spanOffset = 0;
}
float x1 = layout.getPrimaryHorizontal(spanOffset);
float x2 = layout.getPrimaryHorizontal(spanOffset + 1);
int offset = (int) Math.ceil(Math.min(x1, x2));
if (offset != 0 && !drawForwardIcon) {
offset += dp(3);
}
for (int i = 0; i < thumbsCount; ++i) {
thumbImage[i].setImageX(left + offset + dp((thumbSize + 2) * i));
thumbImageSeen[i] = true;
}
} else {
for (int i = 0; i < 3; ++i) {
thumbImageSeen[i] = false;
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
private CharSequence applyThumbs(CharSequence string) {
if (thumbsCount > 0) {
SpannableStringBuilder builder = SpannableStringBuilder.valueOf(string);
builder.insert(0, " ");
builder.setSpan(new FixedWidthSpan(dp((thumbSize + 2) * thumbsCount - 2 + 5)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return builder;
}
return string;
}
int topMessageTopicStartIndex;
int topMessageTopicEndIndex;
private CharSequence formatTopicsNames() {
ForumFormattedNames forumFormattedNames = null;
if (sharedResources != null) {
forumFormattedNames = sharedResources.formattedTopicNames.get(getDialogId());
}
if (forumFormattedNames == null) {
forumFormattedNames = new ForumFormattedNames();
if (sharedResources != null) {
sharedResources.formattedTopicNames.put(getDialogId(), forumFormattedNames);
}
}
forumFormattedNames.formatTopicsNames(currentAccount, message, chat);
topMessageTopicStartIndex = forumFormattedNames.topMessageTopicStartIndex;
topMessageTopicEndIndex = forumFormattedNames.topMessageTopicEndIndex;
lastTopicMessageUnread = forumFormattedNames.lastTopicMessageUnread;
return forumFormattedNames.formattedNames;
}
public boolean isForumCell() {
return !isDialogFolder() && chat != null && chat.forum && !isTopic;
}
private void drawCheckStatus(Canvas canvas, boolean drawClock, boolean drawCheck1, boolean drawCheck2, boolean moveCheck, float alpha) {
if (alpha == 0 && !moveCheck) {
return;
}
float scale = 0.5f + 0.5f * alpha;
if (drawClock) {
setDrawableBounds(Theme.dialogs_clockDrawable, clockDrawLeft, checkDrawTop);
if (alpha != 1f) {
canvas.save();
canvas.scale(scale, scale, Theme.dialogs_clockDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY());
Theme.dialogs_clockDrawable.setAlpha((int) (255 * alpha));
}
Theme.dialogs_clockDrawable.draw(canvas);
if (alpha != 1f) {
canvas.restore();
Theme.dialogs_clockDrawable.setAlpha(255);
}
invalidate();
} else if (drawCheck2) {
if (drawCheck1) {
setDrawableBounds(Theme.dialogs_halfCheckDrawable, halfCheckDrawLeft, checkDrawTop);
if (moveCheck) {
canvas.save();
canvas.scale(scale, scale, Theme.dialogs_halfCheckDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY());
Theme.dialogs_halfCheckDrawable.setAlpha((int) (255 * alpha));
}
if (!moveCheck && alpha != 0) {
canvas.save();
canvas.scale(scale, scale, Theme.dialogs_halfCheckDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY());
Theme.dialogs_halfCheckDrawable.setAlpha((int) (255 * alpha));
Theme.dialogs_checkReadDrawable.setAlpha((int) (255 * alpha));
}
Theme.dialogs_halfCheckDrawable.draw(canvas);
if (moveCheck) {
canvas.restore();
canvas.save();
canvas.translate(dp(4) * (1f - alpha), 0);
}
setDrawableBounds(Theme.dialogs_checkReadDrawable, checkDrawLeft, checkDrawTop);
Theme.dialogs_checkReadDrawable.draw(canvas);
if (moveCheck) {
canvas.restore();
Theme.dialogs_halfCheckDrawable.setAlpha(255);
}
if (!moveCheck && alpha != 0) {
canvas.restore();
Theme.dialogs_halfCheckDrawable.setAlpha(255);
Theme.dialogs_checkReadDrawable.setAlpha(255);
}
} else {
setDrawableBounds(Theme.dialogs_checkDrawable, checkDrawLeft1, checkDrawTop);
if (alpha != 1f) {
canvas.save();
canvas.scale(scale, scale, Theme.dialogs_checkDrawable.getBounds().centerX(), Theme.dialogs_halfCheckDrawable.getBounds().centerY());
Theme.dialogs_checkDrawable.setAlpha((int) (255 * alpha));
}
Theme.dialogs_checkDrawable.draw(canvas);
if (alpha != 1f) {
canvas.restore();
Theme.dialogs_checkDrawable.setAlpha(255);
}
}
}
}
public boolean isPointInsideAvatar(float x, float y) {
if (!LocaleController.isRTL) {
return x >= 0 && x < dp(60);
} else {
return x >= getMeasuredWidth() - dp(60) && x < getMeasuredWidth();
}
}
public void setDialogSelected(boolean value) {
if (isSelected != value) {
invalidate();
}
isSelected = value;
}
public boolean checkCurrentDialogIndex(boolean frozen) {
return false;
}
public void animateArchiveAvatar() {
if (avatarDrawable.getAvatarType() != AvatarDrawable.AVATAR_TYPE_ARCHIVED) {
return;
}
animatingArchiveAvatar = true;
animatingArchiveAvatarProgress = 0.0f;
Theme.dialogs_archiveAvatarDrawable.setProgress(0.0f);
Theme.dialogs_archiveAvatarDrawable.start();
invalidate();
}
public void setChecked(boolean checked, boolean animated) {
if (checkBox == null && !checked) {
return;
}
if (checkBox == null) {
checkBox = new CheckBox2(getContext(), 21, resourcesProvider) {
@Override
public void invalidate() {
super.invalidate();
DialogCell.this.invalidate();
}
};
checkBox.setColor(-1, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck);
checkBox.setDrawUnchecked(false);
checkBox.setDrawBackgroundAsArc(3);
addView(checkBox);
}
checkBox.setChecked(checked, animated);
checkTtl();
}
private MessageObject findFolderTopMessage() {
if (parentFragment == null) {
return null;
}
MessageObject maxMessage = null;
ArrayList<TLRPC.Dialog> dialogs = parentFragment.getDialogsArray(currentAccount, dialogsType, currentDialogFolderId, false);
if (dialogs != null && !dialogs.isEmpty()) {
for (int a = 0, N = dialogs.size(); a < N; a++) {
TLRPC.Dialog dialog = dialogs.get(a);
LongSparseArray<ArrayList<MessageObject>> dialogMessage = MessagesController.getInstance(currentAccount).dialogMessage;
if (dialogMessage != null) {
ArrayList<MessageObject> groupMessages = dialogMessage.get(dialog.id);
MessageObject object = groupMessages != null && !groupMessages.isEmpty() ? groupMessages.get(0) : null;
if (object != null && (maxMessage == null || object.messageOwner.date > maxMessage.messageOwner.date)) {
maxMessage = object;
}
if (dialog.pinnedNum == 0 && maxMessage != null) {
break;
}
}
}
}
return maxMessage;
}
public boolean isFolderCell() {
return currentDialogFolderId != 0;
}
public boolean update(int mask) {
return update(mask, true);
}
public boolean update(int mask, boolean animated) {
boolean requestLayout = false;
boolean rebuildLayout = false;
boolean invalidate = false;
boolean oldIsForumCell = isForumCell();
drawAvatarSelector = false;
ttlPeriod = 0;
if (customDialog != null) {
lastMessageDate = customDialog.date;
lastUnreadState = customDialog.unread_count != 0;
unreadCount = customDialog.unread_count;
drawPin = customDialog.pinned;
dialogMuted = customDialog.muted;
hasUnmutedTopics = false;
avatarDrawable.setInfo(customDialog.id, customDialog.name, null);
avatarImage.setImage(null, "50_50", avatarDrawable, null, 0);
for (int i = 0; i < thumbImage.length; ++i) {
thumbImage[i].setImageBitmap((BitmapDrawable) null);
}
avatarImage.setRoundRadius(dp(28));
drawUnmute = false;
} else {
int oldUnreadCount = unreadCount;
boolean oldHasReactionsMentions = reactionMentionCount != 0;
boolean oldMarkUnread = markUnread;
hasUnmutedTopics = false;
readOutboxMaxId = -1;
if (isDialogCell) {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId);
if (dialog != null) {
readOutboxMaxId = dialog.read_outbox_max_id;
ttlPeriod = dialog.ttl_period;
if (mask == 0) {
clearingDialog = MessagesController.getInstance(currentAccount).isClearingDialog(dialog.id);
groupMessages = MessagesController.getInstance(currentAccount).dialogMessage.get(dialog.id);
message = groupMessages != null && groupMessages.size() > 0 ? groupMessages.get(0) : null;
lastUnreadState = message != null && message.isUnread();
TLRPC.Chat localChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id);
boolean isForumCell = localChat != null && localChat.forum && !isTopic;
if (localChat != null && localChat.forum) {
int[] counts = MessagesController.getInstance(currentAccount).getTopicsController().getForumUnreadCount(localChat.id);
unreadCount = counts[0];
mentionCount = counts[1];
reactionMentionCount = counts[2];
hasUnmutedTopics = counts[3] != 0;
} else if (dialog instanceof TLRPC.TL_dialogFolder) {
unreadCount = MessagesStorage.getInstance(currentAccount).getArchiveUnreadCount();
mentionCount = 0;
reactionMentionCount = 0;
} else {
unreadCount = dialog.unread_count;
mentionCount = dialog.unread_mentions_count;
reactionMentionCount = dialog.unread_reactions_count;
}
markUnread = dialog.unread_mark;
currentEditDate = message != null ? message.messageOwner.edit_date : 0;
lastMessageDate = dialog.last_message_date;
if (dialogsType == 7 || dialogsType == 8) {
MessagesController.DialogFilter filter = MessagesController.getInstance(currentAccount).selectedDialogFilter[dialogsType == 8 ? 1 : 0];
drawPin = filter != null && filter.pinnedDialogs.indexOfKey(dialog.id) >= 0;
} else {
drawPin = currentDialogFolderId == 0 && dialog.pinned;
}
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
}
} else {
unreadCount = 0;
mentionCount = 0;
reactionMentionCount = 0;
currentEditDate = 0;
lastMessageDate = 0;
clearingDialog = false;
}
drawAvatarSelector = currentDialogId != 0 && currentDialogId == RightSlidingDialogContainer.fragmentDialogId;
} else {
drawPin = false;
}
if (forumTopic != null) {
unreadCount = forumTopic.unread_count;
mentionCount = forumTopic.unread_mentions_count;
reactionMentionCount = forumTopic.unread_reactions_count;
}
if (dialogsType == DialogsActivity.DIALOGS_TYPE_ADD_USERS_TO) {
drawPin = false;
}
if (tags != null) {
final boolean tagsWereEmpty = tags.isEmpty();
if (tags.update(currentAccount, dialogsType, currentDialogId)) {
if (tagsWereEmpty != tags.isEmpty()) {
rebuildLayout = true;
requestLayout = true;
}
invalidate = true;
}
}
if (mask != 0) {
boolean continueUpdate = false;
if (user != null && !MessagesController.isSupportUser(user) && !user.bot && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
user = MessagesController.getInstance(currentAccount).getUser(user.id);
if (wasDrawnOnline != isOnline()) {
invalidate = true;
}
}
if ((mask & MessagesController.UPDATE_MASK_EMOJI_STATUS) != 0) {
if (user != null) {
user = MessagesController.getInstance(currentAccount).getUser(user.id);
if (user != null && DialogObject.getEmojiStatusDocumentId(user.emoji_status) != 0) {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(DialogObject.getEmojiStatusDocumentId(user.emoji_status), animated);
} else {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, animated);
}
invalidate = true;
}
if (chat != null) {
chat = MessagesController.getInstance(currentAccount).getChat(chat.id);
if (chat != null && DialogObject.getEmojiStatusDocumentId(chat.emoji_status) != 0) {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(DialogObject.getEmojiStatusDocumentId(chat.emoji_status), animated);
} else {
nameLayoutEllipsizeByGradient = true;
emojiStatus.set(PremiumGradient.getInstance().premiumStarDrawableMini, animated);
}
invalidate = true;
}
}
if (isDialogCell || isTopic) {
if ((mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && !lastPrintString.equals(printString)) {
continueUpdate = true;
}
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_MESSAGE_TEXT) != 0) {
if (message != null && message.messageText != lastMessageString) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT) != 0 && chat != null) {
TLRPC.Chat newChat = MessagesController.getInstance(currentAccount).getChat(chat.id);
if ((newChat != null && newChat.call_active && newChat.call_not_empty) != hasCall) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_AVATAR) != 0) {
if (chat == null) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
if (chat == null) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0) {
if (user == null) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
if (user == null) {
continueUpdate = true;
}
}
if (!continueUpdate) {
if (message != null && lastUnreadState != message.isUnread()) {
lastUnreadState = message.isUnread();
continueUpdate = true;
}
if (isDialogCell) {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId);
int newCount;
int newMentionCount;
int newReactionCout = 0;
TLRPC.Chat localChat = dialog == null ? null : MessagesController.getInstance(currentAccount).getChat(-dialog.id);
if (localChat != null && localChat.forum) {
int[] counts = MessagesController.getInstance(currentAccount).getTopicsController().getForumUnreadCount(localChat.id);
newCount = counts[0];
newMentionCount = counts[1];
newReactionCout = counts[2];
hasUnmutedTopics = counts[3] != 0;
} else if (dialog instanceof TLRPC.TL_dialogFolder) {
newCount = MessagesStorage.getInstance(currentAccount).getArchiveUnreadCount();
newMentionCount = 0;
} else if (dialog != null) {
newCount = dialog.unread_count;
newMentionCount = dialog.unread_mentions_count;
newReactionCout = dialog.unread_reactions_count;
} else {
newCount = 0;
newMentionCount = 0;
}
if (dialog != null && (unreadCount != newCount || markUnread != dialog.unread_mark || mentionCount != newMentionCount || reactionMentionCount != newReactionCout)) {
unreadCount = newCount;
mentionCount = newMentionCount;
markUnread = dialog.unread_mark;
reactionMentionCount = newReactionCout;
continueUpdate = true;
}
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_SEND_STATE) != 0) {
if (message != null && lastSendState != message.messageOwner.send_state) {
lastSendState = message.messageOwner.send_state;
continueUpdate = true;
}
}
if (!continueUpdate) {
//if (invalidate) {
invalidate();
// }
return requestLayout;
}
}
user = null;
chat = null;
encryptedChat = null;
long dialogId;
if (currentDialogFolderId != 0) {
dialogMuted = false;
drawUnmute = false;
message = findFolderTopMessage();
if (message != null) {
dialogId = message.getDialogId();
} else {
dialogId = 0;
}
} else {
drawUnmute = false;
if (forumTopic != null) {
boolean allDialogMuted = MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, 0);
topicMuted = MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, forumTopic.id);
if (allDialogMuted == topicMuted) {
dialogMuted = false;
drawUnmute = false;
} else {
dialogMuted = topicMuted;
drawUnmute = !topicMuted;
}
} else {
dialogMuted = isDialogCell && MessagesController.getInstance(currentAccount).isDialogMuted(currentDialogId, getTopicId());
}
dialogId = currentDialogId;
}
if (dialogId != 0) {
if (DialogObject.isEncryptedDialog(dialogId)) {
encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId));
if (encryptedChat != null) {
user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id);
}
} else if (DialogObject.isUserDialog(dialogId)) {
user = MessagesController.getInstance(currentAccount).getUser(dialogId);
} else {
chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
if (!isDialogCell && chat != null && chat.migrated_to != null) {
TLRPC.Chat chat2 = MessagesController.getInstance(currentAccount).getChat(chat.migrated_to.channel_id);
if (chat2 != null) {
chat = chat2;
}
}
}
if (useMeForMyMessages && user != null && message.isOutOwner()) {
user = MessagesController.getInstance(currentAccount).getUser(UserConfig.getInstance(currentAccount).clientUserId);
}
}
if (currentDialogFolderId != 0) {
Theme.dialogs_archiveAvatarDrawable.setCallback(this);
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ARCHIVED);
avatarImage.setImage(null, null, avatarDrawable, null, user, 0);
} else {
if (useFromUserAsAvatar && message != null) {
avatarDrawable.setInfo(currentAccount, message.getFromPeerObject());
avatarImage.setForUserOrChat(message.getFromPeerObject(), avatarDrawable);
} else if (user != null) {
avatarDrawable.setInfo(currentAccount, user);
if (UserObject.isReplyUser(user)) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES);
avatarImage.setImage(null, null, avatarDrawable, null, user, 0);
} else if (UserObject.isAnonymous(user)) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ANONYMOUS);
avatarImage.setImage(null, null, avatarDrawable, null, user, 0);
} else if (UserObject.isUserSelf(user) && isSavedDialog) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_MY_NOTES);
avatarImage.setImage(null, null, avatarDrawable, null, user, 0);
} else if (UserObject.isUserSelf(user) && !useMeForMyMessages) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED);
avatarImage.setImage(null, null, avatarDrawable, null, user, 0);
} else {
avatarImage.setForUserOrChat(user, avatarDrawable, null, true, VectorAvatarThumbDrawable.TYPE_SMALL, false);
}
} else if (chat != null) {
avatarDrawable.setInfo(currentAccount, chat);
avatarImage.setForUserOrChat(chat, avatarDrawable);
}
}
if (animated && (oldUnreadCount != unreadCount || oldMarkUnread != markUnread) && (!isDialogCell || (System.currentTimeMillis() - lastDialogChangedTime) > 100)) {
if (countAnimator != null) {
countAnimator.cancel();
}
countAnimator = ValueAnimator.ofFloat(0, 1f);
countAnimator.addUpdateListener(valueAnimator -> {
countChangeProgress = (float) valueAnimator.getAnimatedValue();
invalidate();
});
countAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
countChangeProgress = 1f;
countOldLayout = null;
countAnimationStableLayout = null;
countAnimationInLayout = null;
invalidate();
}
});
if ((oldUnreadCount == 0 || markUnread) && !(!markUnread && oldMarkUnread)) {
countAnimator.setDuration(220);
countAnimator.setInterpolator(new OvershootInterpolator());
} else if (unreadCount == 0) {
countAnimator.setDuration(150);
countAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
} else {
countAnimator.setDuration(430);
countAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
}
if (drawCount && drawCount2 && countLayout != null) {
String oldStr = String.format("%d", oldUnreadCount);
String newStr = String.format("%d", unreadCount);
if (oldStr.length() == newStr.length()) {
SpannableStringBuilder oldSpannableStr = new SpannableStringBuilder(oldStr);
SpannableStringBuilder newSpannableStr = new SpannableStringBuilder(newStr);
SpannableStringBuilder stableStr = new SpannableStringBuilder(newStr);
for (int i = 0; i < oldStr.length(); i++) {
if (oldStr.charAt(i) == newStr.charAt(i)) {
oldSpannableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0);
newSpannableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0);
} else {
stableStr.setSpan(new EmptyStubSpan(), i, i + 1, 0);
}
}
int countOldWidth = Math.max(dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(oldStr)));
countOldLayout = new StaticLayout(oldSpannableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
countAnimationStableLayout = new StaticLayout(stableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
countAnimationInLayout = new StaticLayout(newSpannableStr, Theme.dialogs_countTextPaint, countOldWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
} else {
countOldLayout = countLayout;
}
}
countWidthOld = countWidth;
countLeftOld = countLeft;
countAnimationIncrement = unreadCount > oldUnreadCount;
countAnimator.start();
}
boolean newHasReactionsMentions = reactionMentionCount != 0;
if (animated && (newHasReactionsMentions != oldHasReactionsMentions)) {
if (reactionsMentionsAnimator != null) {
reactionsMentionsAnimator.cancel();
}
reactionsMentionsChangeProgress = 0;
reactionsMentionsAnimator = ValueAnimator.ofFloat(0, 1f);
reactionsMentionsAnimator.addUpdateListener(valueAnimator -> {
reactionsMentionsChangeProgress = (float) valueAnimator.getAnimatedValue();
invalidate();
});
reactionsMentionsAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
reactionsMentionsChangeProgress = 1f;
invalidate();
}
});
if (newHasReactionsMentions) {
reactionsMentionsAnimator.setDuration(220);
reactionsMentionsAnimator.setInterpolator(new OvershootInterpolator());
} else {
reactionsMentionsAnimator.setDuration(150);
reactionsMentionsAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
}
reactionsMentionsAnimator.start();
}
avatarImage.setRoundRadius(chat != null && chat.forum && currentDialogFolderId == 0 && !useFromUserAsAvatar || !isSavedDialog && user != null && user.self && MessagesController.getInstance(currentAccount).savedViewAsChats ? dp(16) : dp(28));
}
if (!isTopic && (getMeasuredWidth() != 0 || getMeasuredHeight() != 0)) {
rebuildLayout = true;
}
if (!invalidate) {
boolean currentStoriesIsEmpty = storyParams.currentState == StoriesUtilities.STATE_EMPTY;
boolean newStateStoriesIsEmpty = StoriesUtilities.getPredictiveUnreadState(MessagesController.getInstance(currentAccount).getStoriesController(), getDialogId()) == StoriesUtilities.STATE_EMPTY;
if (!newStateStoriesIsEmpty || (!currentStoriesIsEmpty && newStateStoriesIsEmpty)) {
invalidate = true;
}
}
if (!animated) {
dialogMutedProgress = (dialogMuted || drawUnmute) ? 1f : 0f;
if (countAnimator != null) {
countAnimator.cancel();
}
}
// if (invalidate) {
invalidate();
// }
if (isForumCell() != oldIsForumCell) {
requestLayout = true;
}
if (rebuildLayout) {
if (attachedToWindow) {
buildLayout();
} else {
updateLayout = true;
}
}
updatePremiumBlocked(animated);
return requestLayout;
}
private int getTopicId() {
return forumTopic == null ? 0 : forumTopic.id;
}
@Override
public float getTranslationX() {
return translationX;
}
@Override
public void setTranslationX(float value) {
if (value == translationX) {
return;
}
translationX = value;
if (translationDrawable != null && translationX == 0) {
translationDrawable.setProgress(0.0f);
translationAnimationStarted = false;
archiveHidden = SharedConfig.archiveHidden;
currentRevealProgress = 0;
isSliding = false;
}
if (translationX != 0) {
isSliding = true;
} else {
currentRevealBounceProgress = 0f;
currentRevealProgress = 0f;
drawRevealBackground = false;
}
if (isSliding && !swipeCanceled) {
boolean prevValue = drawRevealBackground;
drawRevealBackground = Math.abs(translationX) >= getMeasuredWidth() * 0.45f;
if (prevValue != drawRevealBackground && archiveHidden == SharedConfig.archiveHidden) {
try {
performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
} catch (Exception ignore) {}
}
}
invalidate();
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
if (currentDialogId == 0 && customDialog == null) {
return;
}
if (!visibleOnScreen && !drawingForBlur) {
return;
}
boolean needInvalidate = false;
if (drawArchive && (currentDialogFolderId != 0 || isTopic && forumTopic != null && forumTopic.id == 1) && archivedChatsDrawable != null && archivedChatsDrawable.outProgress == 0.0f && translationX == 0.0f) {
if (!drawingForBlur) {
canvas.save();
canvas.translate(0, -translateY - rightFragmentOffset);
canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight());
archivedChatsDrawable.draw(canvas);
canvas.restore();
}
return;
}
if (clipProgress != 0.0f && Build.VERSION.SDK_INT != 24) {
canvas.save();
canvas.clipRect(0, topClip * clipProgress, getMeasuredWidth(), getMeasuredHeight() - (int) (bottomClip * clipProgress));
}
int backgroundColor = 0;
if (translationX != 0 || cornerProgress != 0.0f) {
canvas.save();
canvas.translate(0, -translateY);
String swipeMessage;
int revealBackgroundColor;
int swipeMessageStringId;
if (overrideSwipeAction) {
backgroundColor = Theme.getColor(overrideSwipeActionBackgroundColorKey, resourcesProvider);
revealBackgroundColor = Theme.getColor(overrideSwipeActionRevealBackgroundColorKey, resourcesProvider);
swipeMessage = LocaleController.getString(overrideSwipeActionStringKey, swipeMessageStringId = overrideSwipeActionStringId);
translationDrawable = overrideSwipeActionDrawable;
} else if (currentDialogFolderId != 0) {
if (archiveHidden) {
backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider);
revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider);
swipeMessage = LocaleController.getString("UnhideFromTop", swipeMessageStringId = R.string.UnhideFromTop);
translationDrawable = Theme.dialogs_unpinArchiveDrawable;
} else {
backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider);
revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider);
swipeMessage = LocaleController.getString("HideOnTop", swipeMessageStringId = R.string.HideOnTop);
translationDrawable = Theme.dialogs_pinArchiveDrawable;
}
} else {
if (promoDialog) {
backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider);
revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider);
swipeMessage = LocaleController.getString("PsaHide", swipeMessageStringId = R.string.PsaHide);
translationDrawable = Theme.dialogs_hidePsaDrawable;
} else if (folderId == 0) {
backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider);
revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider);
if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_MUTE) {
if (dialogMuted) {
swipeMessage = LocaleController.getString("SwipeUnmute", swipeMessageStringId = R.string.SwipeUnmute);
translationDrawable = Theme.dialogs_swipeUnmuteDrawable;
} else {
swipeMessage = LocaleController.getString("SwipeMute", swipeMessageStringId = R.string.SwipeMute);
translationDrawable = Theme.dialogs_swipeMuteDrawable;
}
} else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_DELETE) {
swipeMessage = LocaleController.getString("SwipeDeleteChat", swipeMessageStringId = R.string.SwipeDeleteChat);
backgroundColor = Theme.getColor(Theme.key_dialogSwipeRemove, resourcesProvider);
translationDrawable = Theme.dialogs_swipeDeleteDrawable;
} else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_READ) {
if (unreadCount > 0 || markUnread) {
swipeMessage = LocaleController.getString("SwipeMarkAsRead", swipeMessageStringId = R.string.SwipeMarkAsRead);
translationDrawable = Theme.dialogs_swipeReadDrawable;
} else {
swipeMessage = LocaleController.getString("SwipeMarkAsUnread", swipeMessageStringId = R.string.SwipeMarkAsUnread);
translationDrawable = Theme.dialogs_swipeUnreadDrawable;
}
} else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_PIN) {
if (getIsPinned()) {
swipeMessage = LocaleController.getString("SwipeUnpin", swipeMessageStringId = R.string.SwipeUnpin);
translationDrawable = Theme.dialogs_swipeUnpinDrawable;
} else {
swipeMessage = LocaleController.getString("SwipePin", swipeMessageStringId = R.string.SwipePin);
translationDrawable = Theme.dialogs_swipePinDrawable;
}
} else {
swipeMessage = LocaleController.getString("Archive", swipeMessageStringId = R.string.Archive);
translationDrawable = Theme.dialogs_archiveDrawable;
}
} else {
backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider);
revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider);
swipeMessage = LocaleController.getString("Unarchive", swipeMessageStringId = R.string.Unarchive);
translationDrawable = Theme.dialogs_unarchiveDrawable;
}
}
if (swipeCanceled && lastDrawTranslationDrawable != null) {
translationDrawable = lastDrawTranslationDrawable;
swipeMessageStringId = lastDrawSwipeMessageStringId;
} else {
lastDrawTranslationDrawable = translationDrawable;
lastDrawSwipeMessageStringId = swipeMessageStringId;
}
if (!translationAnimationStarted && Math.abs(translationX) > dp(43)) {
translationAnimationStarted = true;
translationDrawable.setProgress(0.0f);
translationDrawable.setCallback(this);
translationDrawable.start();
}
float tx = getMeasuredWidth() + translationX;
if (currentRevealProgress < 1.0f) {
Theme.dialogs_pinnedPaint.setColor(backgroundColor);
canvas.drawRect(tx - dp(8), 0, getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint);
if (currentRevealProgress == 0) {
if (Theme.dialogs_archiveDrawableRecolored) {
Theme.dialogs_archiveDrawable.setLayerColor("Arrow.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground));
Theme.dialogs_archiveDrawableRecolored = false;
}
if (Theme.dialogs_hidePsaDrawableRecolored) {
Theme.dialogs_hidePsaDrawable.beginApplyLayerColors();
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 1.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground));
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 2.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground));
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 3.**", Theme.getNonAnimatedColor(Theme.key_chats_archiveBackground));
Theme.dialogs_hidePsaDrawable.commitApplyLayerColors();
Theme.dialogs_hidePsaDrawableRecolored = false;
}
}
}
int drawableX = getMeasuredWidth() - dp(43) - translationDrawable.getIntrinsicWidth() / 2;
int drawableY = (getMeasuredHeight() - dp(54)) / 2;
int drawableCx = drawableX + translationDrawable.getIntrinsicWidth() / 2;
int drawableCy = drawableY + translationDrawable.getIntrinsicHeight() / 2;
if (currentRevealProgress > 0.0f) {
canvas.save();
canvas.clipRect(tx - dp(8), 0, getMeasuredWidth(), getMeasuredHeight());
Theme.dialogs_pinnedPaint.setColor(revealBackgroundColor);
float rad = (float) Math.sqrt(drawableCx * drawableCx + (drawableCy - getMeasuredHeight()) * (drawableCy - getMeasuredHeight()));
canvas.drawCircle(drawableCx, drawableCy, rad * AndroidUtilities.accelerateInterpolator.getInterpolation(currentRevealProgress), Theme.dialogs_pinnedPaint);
canvas.restore();
if (!Theme.dialogs_archiveDrawableRecolored) {
Theme.dialogs_archiveDrawable.setLayerColor("Arrow.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground));
Theme.dialogs_archiveDrawableRecolored = true;
}
if (!Theme.dialogs_hidePsaDrawableRecolored) {
Theme.dialogs_hidePsaDrawable.beginApplyLayerColors();
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 1.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground));
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 2.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground));
Theme.dialogs_hidePsaDrawable.setLayerColor("Line 3.**", Theme.getNonAnimatedColor(Theme.key_chats_archivePinBackground));
Theme.dialogs_hidePsaDrawable.commitApplyLayerColors();
Theme.dialogs_hidePsaDrawableRecolored = true;
}
}
canvas.save();
canvas.translate(drawableX, drawableY);
if (currentRevealBounceProgress != 0.0f && currentRevealBounceProgress != 1.0f) {
float scale = 1.0f + interpolator.getInterpolation(currentRevealBounceProgress);
canvas.scale(scale, scale, translationDrawable.getIntrinsicWidth() / 2, translationDrawable.getIntrinsicHeight() / 2);
}
setDrawableBounds(translationDrawable, 0, 0);
translationDrawable.draw(canvas);
canvas.restore();
canvas.clipRect(tx, 0, getMeasuredWidth(), getMeasuredHeight());
int width = (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(swipeMessage));
if (swipeMessageTextId != swipeMessageStringId || swipeMessageWidth != getMeasuredWidth()) {
swipeMessageTextId = swipeMessageStringId;
swipeMessageWidth = getMeasuredWidth();
swipeMessageTextLayout = new StaticLayout(swipeMessage, Theme.dialogs_archiveTextPaint, Math.min(dp(80), width), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
if (swipeMessageTextLayout.getLineCount() > 1) {
swipeMessageTextLayout = new StaticLayout(swipeMessage, Theme.dialogs_archiveTextPaintSmall, Math.min(dp(82), width), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
}
}
if (swipeMessageTextLayout != null) {
canvas.save();
float yOffset = swipeMessageTextLayout.getLineCount() > 1 ? -dp(4) : 0;
canvas.translate(getMeasuredWidth() - dp(43) - swipeMessageTextLayout.getWidth() / 2f, drawableY + dp(54 - 16) + yOffset);
swipeMessageTextLayout.draw(canvas);
canvas.restore();
}
canvas.restore();
} else if (translationDrawable != null) {
translationDrawable.stop();
translationDrawable.setProgress(0.0f);
translationDrawable.setCallback(null);
translationDrawable = null;
translationAnimationStarted = false;
}
if (translationX != 0) {
canvas.save();
canvas.translate(translationX, 0);
}
float cornersRadius = dp(8) * cornerProgress;
if (isSelected) {
rect.set(0, 0, getMeasuredWidth(), AndroidUtilities.lerp(getMeasuredHeight(), getCollapsedHeight(), rightFragmentOpenedProgress));
rect.offset(0, -translateY + collapseOffset);
canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_tabletSeletedPaint);
}
canvas.save();
canvas.translate(0, -rightFragmentOffset * rightFragmentOpenedProgress);
if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) {
Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f));
Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress)));
canvas.drawRect(-xOffset, 0, getMeasuredWidth(), getMeasuredHeight() - translateY, Theme.dialogs_pinnedPaint);
} else if (getIsPinned() || drawPinBackground) {
Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider));
Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress)));
canvas.drawRect(-xOffset, 0, getMeasuredWidth(), getMeasuredHeight() - translateY, Theme.dialogs_pinnedPaint);
}
canvas.restore();
updateHelper.updateAnimationValues();
if (collapseOffset != 0) {
canvas.save();
canvas.translate(0, collapseOffset);
}
if (rightFragmentOpenedProgress != 1) {
int restoreToCount = -1;
if (rightFragmentOpenedProgress != 0) {
float startAnimationProgress = Utilities.clamp(rightFragmentOpenedProgress / 0.4f, 1f, 0);
if (SharedConfig.getDevicePerformanceClass() >= SharedConfig.PERFORMANCE_CLASS_HIGH) {
restoreToCount = canvas.saveLayerAlpha(dp(RightSlidingDialogContainer.getRightPaddingSize() + 1) - dp(8) * (1f - startAnimationProgress), 0, getMeasuredWidth(), getMeasuredHeight(), (int) (255 * (1f - rightFragmentOpenedProgress)), Canvas.ALL_SAVE_FLAG);
} else {
restoreToCount = canvas.save();
canvas.clipRect(dp(RightSlidingDialogContainer.getRightPaddingSize() + 1) - dp(8) * (1f - startAnimationProgress), 0, getMeasuredWidth(), getMeasuredHeight());
}
canvas.translate(-(getMeasuredWidth() - dp(74)) * 0.7f * rightFragmentOpenedProgress, 0);
}
if (translationX != 0 || cornerProgress != 0.0f) {
canvas.save();
Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
rect.set(getMeasuredWidth() - dp(64), 0, getMeasuredWidth(), getMeasuredHeight());
rect.offset(0, -translateY);
canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint);
if (isSelected) {
canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_tabletSeletedPaint);
}
if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) {
Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f));
Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress)));
canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint);
} else if (getIsPinned() || drawPinBackground) {
Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider));
Theme.dialogs_pinnedPaint.setAlpha((int) (Theme.dialogs_pinnedPaint.getAlpha() * (1f - rightFragmentOpenedProgress)));
canvas.drawRoundRect(rect, cornersRadius, cornersRadius, Theme.dialogs_pinnedPaint);
}
canvas.restore();
}
if (translationX != 0) {
if (cornerProgress < 1.0f) {
cornerProgress += 16f / 150.0f;
if (cornerProgress > 1.0f) {
cornerProgress = 1.0f;
}
needInvalidate = true;
}
} else if (cornerProgress > 0.0f) {
cornerProgress -= 16f / 150.0f;
if (cornerProgress < 0.0f) {
cornerProgress = 0.0f;
}
needInvalidate = true;
}
if (drawNameLock) {
setDrawableBounds(Theme.dialogs_lockDrawable, nameLockLeft, nameLockTop);
Theme.dialogs_lockDrawable.draw(canvas);
}
int nameTop = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 13);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
nameTop -= dp(isForumCell() ? 8 : 9);
}
if (nameLayout != null) {
if (nameLayoutEllipsizeByGradient && !nameLayoutFits) {
if (nameLayoutEllipsizeLeft && fadePaint == null) {
fadePaint = new Paint();
fadePaint.setShader(new LinearGradient(0, 0, dp(24), 0, new int[]{0xffffffff, 0}, new float[]{0f, 1f}, Shader.TileMode.CLAMP));
fadePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
} else if (fadePaintBack == null) {
fadePaintBack = new Paint();
fadePaintBack.setShader(new LinearGradient(0, 0, dp(24), 0, new int[]{0, 0xffffffff}, new float[]{0f, 1f}, Shader.TileMode.CLAMP));
fadePaintBack.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
canvas.saveLayerAlpha(0, 0, getMeasuredWidth(), getMeasuredHeight(), 255, Canvas.ALL_SAVE_FLAG);
canvas.clipRect(nameLeft, 0, nameLeft + nameWidth, getMeasuredHeight());
}
if (currentDialogFolderId != 0) {
Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider));
} else if (encryptedChat != null || customDialog != null && customDialog.type == 2) {
Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_secretName, resourcesProvider));
} else {
Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_name, resourcesProvider));
}
canvas.save();
canvas.translate(nameLeft + nameLayoutTranslateX, nameTop);
SpoilerEffect.layoutDrawMaybe(nameLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, nameLayout, animatedEmojiStackName, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(0, nameLayout.getPaint().getColor()));
canvas.restore();
if (nameLayoutEllipsizeByGradient && !nameLayoutFits) {
canvas.save();
if (nameLayoutEllipsizeLeft) {
canvas.translate(nameLeft, 0);
canvas.drawRect(0, 0, dp(24), getMeasuredHeight(), fadePaint);
} else {
canvas.translate(nameLeft + nameWidth - dp(24), 0);
canvas.drawRect(0, 0, dp(24), getMeasuredHeight(), fadePaintBack);
}
canvas.restore();
canvas.restore();
}
}
if (timeLayout != null && currentDialogFolderId == 0) {
canvas.save();
canvas.translate(timeLeft, timeTop);
SpoilerEffect.layoutDrawMaybe(timeLayout, canvas);
canvas.restore();
}
if (drawLock2()) {
Theme.dialogs_lock2Drawable.setBounds(
lock2Left,
timeTop + (timeLayout.getHeight() - Theme.dialogs_lock2Drawable.getIntrinsicHeight()) / 2,
lock2Left + Theme.dialogs_lock2Drawable.getIntrinsicWidth(),
timeTop + (timeLayout.getHeight() - Theme.dialogs_lock2Drawable.getIntrinsicHeight()) / 2 + Theme.dialogs_lock2Drawable.getIntrinsicHeight()
);
Theme.dialogs_lock2Drawable.draw(canvas);
}
if (messageNameLayout != null && !isForumCell()) {
if (currentDialogFolderId != 0) {
Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived_threeLines, resourcesProvider));
} else if (draftMessage != null) {
Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_draft, resourcesProvider));
} else {
Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessage_threeLines, resourcesProvider));
}
canvas.save();
canvas.translate(messageNameLeft, messageNameTop);
try {
SpoilerEffect.layoutDrawMaybe(messageNameLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageNameLayout, animatedEmojiStack2, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(1, messageNameLayout.getPaint().getColor()));
} catch (Exception e) {
FileLog.e(e);
}
canvas.restore();
}
if (messageLayout != null) {
if (currentDialogFolderId != 0) {
if (chat != null) {
Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived, resourcesProvider));
} else {
Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_messageArchived, resourcesProvider));
}
} else {
Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider));
}
float top;
float typingAnimationOffset = dp(14);
if (updateHelper.typingOutToTop) {
top = messageTop - typingAnimationOffset * updateHelper.typingProgres;
} else {
top = messageTop + typingAnimationOffset * updateHelper.typingProgres;
}
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
top -= dp(isForumCell() ? 10 : 11);
}
if (updateHelper.typingProgres != 1f) {
canvas.save();
canvas.translate(messageLeft, top);
int oldAlpha = messageLayout.getPaint().getAlpha();
messageLayout.getPaint().setAlpha((int) (oldAlpha * (1f - updateHelper.typingProgres)));
if (!spoilers.isEmpty()) {
try {
canvas.save();
SpoilerEffect.clipOutCanvas(canvas, spoilers);
SpoilerEffect.layoutDrawMaybe(messageLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageLayout, animatedEmojiStack, -.075f, spoilers, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(2, messageLayout.getPaint().getColor()));
canvas.restore();
for (int i = 0; i < spoilers.size(); i++) {
SpoilerEffect eff = spoilers.get(i);
eff.setColor(messageLayout.getPaint().getColor());
eff.draw(canvas);
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
SpoilerEffect.layoutDrawMaybe(messageLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, messageLayout, animatedEmojiStack, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(2, messageLayout.getPaint().getColor()));
}
messageLayout.getPaint().setAlpha(oldAlpha);
canvas.restore();
}
canvas.save();
if (updateHelper.typingOutToTop) {
top = messageTop + typingAnimationOffset * (1f - updateHelper.typingProgres);
} else {
top = messageTop - typingAnimationOffset * (1f - updateHelper.typingProgres);
}
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
top -= dp(isForumCell() ? 10 : 11);
}
canvas.translate(typingLeft, top);
if (typingLayout != null && updateHelper.typingProgres > 0) {
int oldAlpha = typingLayout.getPaint().getAlpha();
typingLayout.getPaint().setAlpha((int) (oldAlpha * updateHelper.typingProgres));
typingLayout.draw(canvas);
typingLayout.getPaint().setAlpha(oldAlpha);
}
canvas.restore();
if (typingLayout != null && (printingStringType >= 0 || (updateHelper.typingProgres > 0 && updateHelper.lastKnownTypingType >= 0))) {
int type = printingStringType >= 0 ? printingStringType : updateHelper.lastKnownTypingType;
StatusDrawable statusDrawable = Theme.getChatStatusDrawable(type);
if (statusDrawable != null) {
canvas.save();
int color = Theme.getColor(Theme.key_chats_actionMessage);
statusDrawable.setColor(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * updateHelper.typingProgres)));
if (updateHelper.typingOutToTop) {
top = messageTop + typingAnimationOffset * (1f - updateHelper.typingProgres);
} else {
top = messageTop - typingAnimationOffset * (1f - updateHelper.typingProgres);
}
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
top -= dp(isForumCell() ? 10 : 11);
}
if (type == 1 || type == 4) {
canvas.translate(statusDrawableLeft, top + (type == 1 ? dp(1) : 0));
} else {
canvas.translate(statusDrawableLeft, top + (dp(18) - statusDrawable.getIntrinsicHeight()) / 2f);
}
statusDrawable.draw(canvas);
invalidate();
canvas.restore();
}
}
}
if (buttonLayout != null) {
canvas.save();
if (buttonBackgroundPaint == null) {
buttonBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
if (canvasButton == null) {
canvasButton = new CanvasButton(this);
canvasButton.setDelegate(() -> {
if (delegate != null) {
delegate.onButtonClicked(this);
}
});
canvasButton.setLongPress(() -> {
if (delegate != null) {
delegate.onButtonLongPress(this);
}
});
}
if (lastTopicMessageUnread && topMessageTopicEndIndex != topMessageTopicStartIndex && (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER1 || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER2)) {
canvasButton.setColor(ColorUtils.setAlphaComponent(currentMessagePaint.getColor(), Theme.isCurrentThemeDark() ? 36 : 26));
if (!buttonCreated) {
canvasButton.rewind();
if (topMessageTopicEndIndex != topMessageTopicStartIndex && topMessageTopicEndIndex > 0) {
float top = messageTop;
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
top -= dp(isForumCell() ? 10 : 11);
}
AndroidUtilities.rectTmp.set(messageLeft + dp(2) + messageLayout.getPrimaryHorizontal(0), top, messageLeft + messageLayout.getPrimaryHorizontal(Math.min(messageLayout.getText().length(), topMessageTopicEndIndex)) - dp(3), buttonTop - dp(4));
AndroidUtilities.rectTmp.inset(-dp(8), -dp(4));
if (AndroidUtilities.rectTmp.right > AndroidUtilities.rectTmp.left) {
canvasButton.addRect(AndroidUtilities.rectTmp);
}
}
float buttonLayoutLeft = buttonLayout.getLineLeft(0);
AndroidUtilities.rectTmp.set(buttonLeft + buttonLayoutLeft + dp(2), buttonTop + dp(2), buttonLeft + buttonLayoutLeft + buttonLayout.getLineWidth(0) + dp(12), buttonTop + buttonLayout.getHeight());
AndroidUtilities.rectTmp.inset(-dp(8), -dp(3));
canvasButton.addRect(AndroidUtilities.rectTmp);
}
canvasButton.draw(canvas);
Theme.dialogs_forum_arrowDrawable.setAlpha(125);
setDrawableBounds(Theme.dialogs_forum_arrowDrawable, AndroidUtilities.rectTmp.right - dp(18), AndroidUtilities.rectTmp.top + (AndroidUtilities.rectTmp.height() - Theme.dialogs_forum_arrowDrawable.getIntrinsicHeight()) / 2f);
Theme.dialogs_forum_arrowDrawable.draw(canvas);
}
canvas.translate(buttonLeft, buttonTop);
if (!spoilers2.isEmpty()) {
try {
canvas.save();
SpoilerEffect.clipOutCanvas(canvas, spoilers2);
SpoilerEffect.layoutDrawMaybe(buttonLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, buttonLayout, animatedEmojiStack3, -.075f, spoilers2, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(3, buttonLayout.getPaint().getColor()));
canvas.restore();
for (int i = 0; i < spoilers2.size(); i++) {
SpoilerEffect eff = spoilers2.get(i);
eff.setColor(buttonLayout.getPaint().getColor());
eff.draw(canvas);
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
SpoilerEffect.layoutDrawMaybe(buttonLayout, canvas);
AnimatedEmojiSpan.drawAnimatedEmojis(canvas, buttonLayout, animatedEmojiStack3, -.075f, null, 0, 0, 0, 1f, getAdaptiveEmojiColorFilter(3, buttonLayout.getPaint().getColor()));
}
canvas.restore();
}
if (currentDialogFolderId == 0) {
int currentStatus = (drawClock ? 1 : 0) + (drawCheck1 ? 2 : 0) + (drawCheck2 ? 4 : 0);
if (lastStatusDrawableParams >= 0 && lastStatusDrawableParams != currentStatus && !statusDrawableAnimationInProgress) {
createStatusDrawableAnimator(lastStatusDrawableParams, currentStatus);
}
if (statusDrawableAnimationInProgress) {
currentStatus = animateToStatusDrawableParams;
}
boolean drawClock = (currentStatus & 1) != 0;
boolean drawCheck1 = (currentStatus & 2) != 0;
boolean drawCheck2 = (currentStatus & 4) != 0;
if (statusDrawableAnimationInProgress) {
boolean outDrawClock = (animateFromStatusDrawableParams & 1) != 0;
boolean outDrawCheck1 = (animateFromStatusDrawableParams & 2) != 0;
boolean outDrawCheck2 = (animateFromStatusDrawableParams & 4) != 0;
if (!drawClock && !outDrawClock && outDrawCheck2 && !outDrawCheck1 && drawCheck1 && drawCheck2) {
drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, true, statusDrawableProgress);
} else {
drawCheckStatus(canvas, outDrawClock, outDrawCheck1, outDrawCheck2, false, 1f - statusDrawableProgress);
drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, false, statusDrawableProgress);
}
} else {
drawCheckStatus(canvas, drawClock, drawCheck1, drawCheck2, false,1f);
}
lastStatusDrawableParams = (this.drawClock ? 1 : 0) + (this.drawCheck1 ? 2 : 0) + (this.drawCheck2 ? 4 : 0);
}
boolean drawMuted = drawUnmute || dialogMuted;
if (dialogsType != 2 && (drawMuted || dialogMutedProgress > 0) && !drawVerified && drawScam == 0 && !drawPremium) {
if (drawMuted && dialogMutedProgress != 1f) {
dialogMutedProgress += 16 / 150f;
if (dialogMutedProgress > 1f) {
dialogMutedProgress = 1f;
} else {
invalidate();
}
} else if (!drawMuted && dialogMutedProgress != 0f) {
dialogMutedProgress -= 16 / 150f;
if (dialogMutedProgress < 0f) {
dialogMutedProgress = 0f;
} else {
invalidate();
}
}
float muteX = nameMuteLeft - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 0 : 1);
float muteY = dp(SharedConfig.useThreeLinesLayout ? 13.5f : 17.5f);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
muteY -= dp(isForumCell() ? 8 : 9);
}
setDrawableBounds(Theme.dialogs_muteDrawable, muteX, muteY);
setDrawableBounds(Theme.dialogs_unmuteDrawable, muteX, muteY);
if (dialogMutedProgress != 1f) {
canvas.save();
canvas.scale(dialogMutedProgress, dialogMutedProgress, Theme.dialogs_muteDrawable.getBounds().centerX(), Theme.dialogs_muteDrawable.getBounds().centerY());
if (drawUnmute) {
Theme.dialogs_unmuteDrawable.setAlpha((int) (255 * dialogMutedProgress));
Theme.dialogs_unmuteDrawable.draw(canvas);
Theme.dialogs_unmuteDrawable.setAlpha(255);
} else {
Theme.dialogs_muteDrawable.setAlpha((int) (255 * dialogMutedProgress));
Theme.dialogs_muteDrawable.draw(canvas);
Theme.dialogs_muteDrawable.setAlpha(255);
}
canvas.restore();
} else {
if (drawUnmute) {
Theme.dialogs_unmuteDrawable.draw(canvas);
} else {
Theme.dialogs_muteDrawable.draw(canvas);
}
}
} else if (drawVerified) {
float y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 13.5f : 16.5f);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
y -= dp(9);
}
setDrawableBounds(Theme.dialogs_verifiedDrawable, nameMuteLeft - dp(1), y);
setDrawableBounds(Theme.dialogs_verifiedCheckDrawable, nameMuteLeft - dp(1), y);
Theme.dialogs_verifiedDrawable.draw(canvas);
Theme.dialogs_verifiedCheckDrawable.draw(canvas);
} else if (drawPremium) {
int y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12.5f : 15.5f);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
y -= dp(9);
}
if (emojiStatus != null) {
emojiStatus.setBounds(
nameMuteLeft - dp(2),
y - dp(4),
nameMuteLeft + dp(20),
y - dp(4) + dp(22)
);
emojiStatus.setColor(Theme.getColor(Theme.key_chats_verifiedBackground, resourcesProvider));
emojiStatus.draw(canvas);
} else {
Drawable premiumDrawable = PremiumGradient.getInstance().premiumStarDrawableMini;
setDrawableBounds(premiumDrawable, nameMuteLeft - dp(1), dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12.5f : 15.5f));
premiumDrawable.draw(canvas);
}
} else if (drawScam != 0) {
int y = dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 12 : 15);
if ((!(useForceThreeLines || SharedConfig.useThreeLinesLayout) || isForumCell()) && hasTags()) {
y -= dp(9);
}
setDrawableBounds((drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable), nameMuteLeft, y);
(drawScam == 1 ? Theme.dialogs_scamDrawable : Theme.dialogs_fakeDrawable).draw(canvas);
}
if (drawReorder || reorderIconProgress != 0) {
Theme.dialogs_reorderDrawable.setAlpha((int) (reorderIconProgress * 255));
setDrawableBounds(Theme.dialogs_reorderDrawable, pinLeft, pinTop);
Theme.dialogs_reorderDrawable.draw(canvas);
}
if (drawError) {
Theme.dialogs_errorDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
rect.set(errorLeft, errorTop, errorLeft + dp(23), errorTop + dp(23));
canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, Theme.dialogs_errorPaint);
setDrawableBounds(Theme.dialogs_errorDrawable, errorLeft + dp(5.5f), errorTop + dp(5));
Theme.dialogs_errorDrawable.draw(canvas);
} else if ((drawCount || drawMention) && drawCount2 || countChangeProgress != 1f || drawReactionMention || reactionsMentionsChangeProgress != 1f) {
boolean drawCounterMuted;
if (isTopic) {
drawCounterMuted = topicMuted;
} else {
drawCounterMuted = chat != null && chat.forum && forumTopic == null ? !hasUnmutedTopics : dialogMuted;
}
drawCounter(canvas, drawCounterMuted, countTop, countLeft, countLeftOld, 1f, false);
if (drawMention) {
Theme.dialogs_countPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
int x = mentionLeft - dp(5.5f);
rect.set(x, countTop, x + mentionWidth + dp(11), countTop + dp(23));
Paint paint = drawCounterMuted && folderId != 0 ? Theme.dialogs_countGrayPaint : Theme.dialogs_countPaint;
canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, paint);
if (mentionLayout != null) {
Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
canvas.save();
canvas.translate(mentionLeft, countTop + dp(4));
mentionLayout.draw(canvas);
canvas.restore();
} else {
Theme.dialogs_mentionDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
setDrawableBounds(Theme.dialogs_mentionDrawable, mentionLeft - dp(2), countTop + dp(3.2f), dp(16), dp(16));
Theme.dialogs_mentionDrawable.draw(canvas);
}
}
if (drawReactionMention || reactionsMentionsChangeProgress != 1f) {
Theme.dialogs_reactionsCountPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
int x = reactionMentionLeft - dp(5.5f);
rect.set(x, countTop, x + dp(23), countTop + dp(23));
Paint paint = Theme.dialogs_reactionsCountPaint;
canvas.save();
if (reactionsMentionsChangeProgress != 1f) {
float s = drawReactionMention ? reactionsMentionsChangeProgress : (1f - reactionsMentionsChangeProgress);
canvas.scale(s, s, rect.centerX(), rect.centerY());
}
canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, paint);
Theme.dialogs_reactionsMentionDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
setDrawableBounds(Theme.dialogs_reactionsMentionDrawable, reactionMentionLeft - dp(2), countTop + dp(3.8f), dp(16), dp(16));
Theme.dialogs_reactionsMentionDrawable.draw(canvas);
canvas.restore();
}
} else if (getIsPinned()) {
Theme.dialogs_pinnedDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
setDrawableBounds(Theme.dialogs_pinnedDrawable, pinLeft, pinTop);
Theme.dialogs_pinnedDrawable.draw(canvas);
}
if (thumbsCount > 0 && updateHelper.typingProgres != 1f) {
float alpha = 1f;
if (updateHelper.typingProgres > 0) {
alpha = (1f - updateHelper.typingProgres);
canvas.saveLayerAlpha(0, 0, getWidth(), getHeight(), (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
float top;
if (updateHelper.typingOutToTop) {
top = -dp(14) * updateHelper.typingProgres;
} else {
top = dp(14) * updateHelper.typingProgres;
}
canvas.translate(0, top);
}
for (int i = 0; i < thumbsCount; ++i) {
if (!thumbImageSeen[i]) {
continue;
}
if (thumbBackgroundPaint == null) {
thumbBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
thumbBackgroundPaint.setShadowLayer(dp(1.34f), 0, dp(0.34f), 0x18000000);
thumbBackgroundPaint.setColor(0x00000000);
}
AndroidUtilities.rectTmp.set(
thumbImage[i].getImageX(),
thumbImage[i].getImageY(),
thumbImage[i].getImageX2(),
thumbImage[i].getImageY2()
);
canvas.drawRoundRect(
AndroidUtilities.rectTmp,
thumbImage[i].getRoundRadius()[0],
thumbImage[i].getRoundRadius()[1],
thumbBackgroundPaint
);
thumbImage[i].draw(canvas);
if (drawSpoiler[i]) {
if (thumbPath == null) {
thumbPath = new Path();
} else {
thumbPath.rewind();
}
thumbPath.addRoundRect(AndroidUtilities.rectTmp, thumbImage[i].getRoundRadius()[0], thumbImage[i].getRoundRadius()[1], Path.Direction.CW);
canvas.save();
canvas.clipPath(thumbPath);
int sColor = Color.WHITE;
thumbSpoiler.setColor(ColorUtils.setAlphaComponent(sColor, (int) (Color.alpha(sColor) * 0.325f)));
thumbSpoiler.setBounds((int) thumbImage[i].getImageX(), (int) thumbImage[i].getImageY(), (int) thumbImage[i].getImageX2(), (int) thumbImage[i].getImageY2());
thumbSpoiler.draw(canvas);
invalidate();
canvas.restore();
}
if (drawPlay[i]) {
int x = (int) (thumbImage[i].getCenterX() - Theme.dialogs_playDrawable.getIntrinsicWidth() / 2);
int y = (int) (thumbImage[i].getCenterY() - Theme.dialogs_playDrawable.getIntrinsicHeight() / 2);
setDrawableBounds(Theme.dialogs_playDrawable, x, y);
Theme.dialogs_playDrawable.draw(canvas);
}
}
if (updateHelper.typingProgres > 0) {
canvas.restore();
}
}
if (tags != null && !tags.isEmpty()) {
canvas.save();
canvas.translate(tagsLeft, getMeasuredHeight() - dp(21.66f) - (useSeparator ? 1 : 0));
tags.draw(canvas, tagsRight - tagsLeft);
canvas.restore();
}
if (restoreToCount != -1) {
canvas.restoreToCount(restoreToCount);
}
}
if (animatingArchiveAvatar) {
canvas.save();
float scale = 1.0f + interpolator.getInterpolation(animatingArchiveAvatarProgress / 170.0f);
canvas.scale(scale, scale, avatarImage.getCenterX(), avatarImage.getCenterY());
}
if (drawAvatar && (!(isTopic && forumTopic != null && forumTopic.id == 1) || archivedChatsDrawable == null || !archivedChatsDrawable.isDraw())) {
storyParams.drawHiddenStoriesAsSegments = currentDialogFolderId != 0;
StoriesUtilities.drawAvatarWithStory(currentDialogId, canvas, avatarImage, storyParams);
}
if (animatingArchiveAvatar) {
canvas.restore();
}
if (avatarImage.getVisible()) {
if (drawAvatarOverlays(canvas)) {
needInvalidate = true;
}
}
if (rightFragmentOpenedProgress > 0 && currentDialogFolderId == 0) {
boolean drawCounterMuted;
if (isTopic) {
drawCounterMuted = topicMuted;
} else {
drawCounterMuted = chat != null && chat.forum && forumTopic == null ? !hasUnmutedTopics : dialogMuted;
}
int countLeftLocal = (int) (storyParams.originalAvatarRect.left + storyParams.originalAvatarRect.width() - countWidth - dp(5f));
int countLeftOld = (int) (storyParams.originalAvatarRect.left + storyParams.originalAvatarRect.width() - countWidthOld - dp(5f));
int countTop = (int) (avatarImage.getImageY() + storyParams.originalAvatarRect.height() - dp(22));
drawCounter(canvas, drawCounterMuted, countTop, countLeftLocal, countLeftOld, rightFragmentOpenedProgress, true);
}
if (collapseOffset != 0) {
canvas.restore();
}
if (translationX != 0) {
canvas.restore();
}
if (drawArchive && (currentDialogFolderId != 0 || isTopic && forumTopic != null && forumTopic.id == 1) && translationX == 0 && archivedChatsDrawable != null) {
canvas.save();
canvas.translate(0, -translateY - rightFragmentOffset * rightFragmentOpenedProgress);
canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight());
archivedChatsDrawable.draw(canvas);
canvas.restore();
}
if (useSeparator) {
int left;
if (fullSeparator || currentDialogFolderId != 0 && archiveHidden && !fullSeparator2 || fullSeparator2 && !archiveHidden) {
left = 0;
} else {
left = dp(messagePaddingStart);
}
if (rightFragmentOpenedProgress != 1) {
int alpha = Theme.dividerPaint.getAlpha();
if (rightFragmentOpenedProgress != 0) {
Theme.dividerPaint.setAlpha((int) (alpha * (1f - rightFragmentOpenedProgress)));
}
float y = getMeasuredHeight() - 1 - rightFragmentOffset * rightFragmentOpenedProgress;
if (LocaleController.isRTL) {
canvas.drawLine(0, y, getMeasuredWidth() - left, y, Theme.dividerPaint);
} else {
canvas.drawLine(left, y, getMeasuredWidth(), y, Theme.dividerPaint);
}
if (rightFragmentOpenedProgress != 0) {
Theme.dividerPaint.setAlpha(alpha);
}
}
}
if (clipProgress != 0.0f) {
if (Build.VERSION.SDK_INT != 24) {
canvas.restore();
} else {
Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
canvas.drawRect(0, 0, getMeasuredWidth(), topClip * clipProgress, Theme.dialogs_pinnedPaint);
canvas.drawRect(0, getMeasuredHeight() - (int) (bottomClip * clipProgress), getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint);
}
}
if (drawReorder || reorderIconProgress != 0.0f) {
if (drawReorder) {
if (reorderIconProgress < 1.0f) {
reorderIconProgress += 16f / 170.0f;
if (reorderIconProgress > 1.0f) {
reorderIconProgress = 1.0f;
}
needInvalidate = true;
}
} else {
if (reorderIconProgress > 0.0f) {
reorderIconProgress -= 16f / 170.0f;
if (reorderIconProgress < 0.0f) {
reorderIconProgress = 0.0f;
}
needInvalidate = true;
}
}
}
if (archiveHidden) {
if (archiveBackgroundProgress > 0.0f) {
archiveBackgroundProgress -= 16f / 230.0f;
if (archiveBackgroundProgress < 0.0f) {
archiveBackgroundProgress = 0.0f;
}
if (avatarDrawable.getAvatarType() == AvatarDrawable.AVATAR_TYPE_ARCHIVED) {
avatarDrawable.setArchivedAvatarHiddenProgress(CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(archiveBackgroundProgress));
}
needInvalidate = true;
}
} else {
if (archiveBackgroundProgress < 1.0f) {
archiveBackgroundProgress += 16f / 230.0f;
if (archiveBackgroundProgress > 1.0f) {
archiveBackgroundProgress = 1.0f;
}
if (avatarDrawable.getAvatarType() == AvatarDrawable.AVATAR_TYPE_ARCHIVED) {
avatarDrawable.setArchivedAvatarHiddenProgress(CubicBezierInterpolator.EASE_OUT_QUINT.getInterpolation(archiveBackgroundProgress));
}
needInvalidate = true;
}
}
if (animatingArchiveAvatar) {
animatingArchiveAvatarProgress += 16f;
if (animatingArchiveAvatarProgress >= 170.0f) {
animatingArchiveAvatarProgress = 170.0f;
animatingArchiveAvatar = false;
}
needInvalidate = true;
}
if (drawRevealBackground) {
if (currentRevealBounceProgress < 1.0f) {
currentRevealBounceProgress += 16f / 170.0f;
if (currentRevealBounceProgress > 1.0f) {
currentRevealBounceProgress = 1.0f;
needInvalidate = true;
}
}
if (currentRevealProgress < 1.0f) {
currentRevealProgress += 16f / 300.0f;
if (currentRevealProgress > 1.0f) {
currentRevealProgress = 1.0f;
}
needInvalidate = true;
}
} else {
if (currentRevealBounceProgress == 1.0f) {
currentRevealBounceProgress = 0.0f;
needInvalidate = true;
}
if (currentRevealProgress > 0.0f) {
currentRevealProgress -= 16f / 300.0f;
if (currentRevealProgress < 0.0f) {
currentRevealProgress = 0.0f;
}
needInvalidate = true;
}
}
if (needInvalidate) {
invalidate();
}
}
private PremiumGradient.PremiumGradientTools premiumGradient;
private Drawable lockDrawable;
public boolean drawAvatarOverlays(Canvas canvas) {
boolean needInvalidate = false;
float lockT = premiumBlockedT.set(premiumBlocked);
if (lockT > 0) {
float top = avatarImage.getCenterY() + dp(18);
float left = avatarImage.getCenterX() + dp(18);
canvas.save();
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
canvas.drawCircle(left, top, dp(10 + 1.33f) * lockT, Theme.dialogs_onlineCirclePaint);
if (premiumGradient == null) {
premiumGradient = new PremiumGradient.PremiumGradientTools(Theme.key_premiumGradient1, Theme.key_premiumGradient2, -1, -1, -1, resourcesProvider);
}
premiumGradient.gradientMatrix((int) (left - dp(10)), (int) (top - dp(10)), (int) (left + dp(10)), (int) (top + dp(10)), 0, 0);
canvas.drawCircle(left, top, dp(10) * lockT, premiumGradient.paint);
if (lockDrawable == null) {
lockDrawable = getContext().getResources().getDrawable(R.drawable.msg_mini_lock2).mutate();
lockDrawable.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN));
}
lockDrawable.setBounds(
(int) (left - lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT),
(int) (top - lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT),
(int) (left + lockDrawable.getIntrinsicWidth() / 2f * .875f * lockT),
(int) (top + lockDrawable.getIntrinsicHeight() / 2f * .875f * lockT)
);
lockDrawable.setAlpha((int) (0xFF * lockT));
lockDrawable.draw(canvas);
canvas.restore();
return false;
}
if (isDialogCell && currentDialogFolderId == 0) {
showTtl = ttlPeriod > 0 && !isOnline() && !hasCall;
if (rightFragmentOpenedProgress != 1f && (showTtl || ttlProgress > 0)) {
if (timerDrawable == null || (timerDrawable.getTime() != ttlPeriod && ttlPeriod > 0)) {
timerDrawable = TimerDrawable.getTtlIconForDialogs(ttlPeriod);
}
if (timerPaint == null) {
timerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
timerPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
timerPaint2.setColor(0x32000000);
}
int top = (int) (avatarImage.getImageY2() - dp(9));
int left;
if (LocaleController.isRTL) {
left = (int) (storyParams.originalAvatarRect.left + dp(9));
} else {
left = (int) (storyParams.originalAvatarRect.right - dp(9));
}
timerDrawable.setBounds(
0, 0, dp(22), dp(22)
);
timerDrawable.setTime(ttlPeriod);
if (avatarImage.updateThumbShaderMatrix()) {
if (avatarImage.thumbShader != null) {
timerPaint.setShader(avatarImage.thumbShader);
} else if (avatarImage.staticThumbShader != null) {
timerPaint.setShader(avatarImage.staticThumbShader);
}
} else {
timerPaint.setShader(null);
if (avatarImage.getBitmap() != null && !avatarImage.getBitmap().isRecycled()) {
timerPaint.setColor(AndroidUtilities.getDominantColor(avatarImage.getBitmap()));
} else if (avatarImage.getDrawable() instanceof VectorAvatarThumbDrawable){
VectorAvatarThumbDrawable vectorAvatarThumbDrawable = (VectorAvatarThumbDrawable) avatarImage.getDrawable();
timerPaint.setColor(vectorAvatarThumbDrawable.gradientTools.getAverageColor());
} else {
timerPaint.setColor(avatarDrawable.getColor2());
}
}
canvas.save();
float s = ttlProgress * (1f - rightFragmentOpenedProgress);
if (checkBox != null) {
s *= 1f - checkBox.getProgress();
}
canvas.scale(s, s, left, top);
canvas.drawCircle(left, top, AndroidUtilities.dpf2(11f), timerPaint);
canvas.drawCircle(left, top, AndroidUtilities.dpf2(11f), timerPaint2);
canvas.save();
canvas.translate(left - AndroidUtilities.dpf2(11f), top - AndroidUtilities.dpf2(11f));
timerDrawable.draw(canvas);
canvas.restore();
canvas.restore();
}
if (user != null && !MessagesController.isSupportUser(user) && !user.bot) {
boolean isOnline = isOnline();
wasDrawnOnline = isOnline;
if (isOnline || onlineProgress != 0) {
int top = (int) (storyParams.originalAvatarRect.bottom - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 8));
int left;
if (LocaleController.isRTL) {
left = (int) (storyParams.originalAvatarRect.left + dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6));
} else {
left = (int) (storyParams.originalAvatarRect.right - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6));
}
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
canvas.drawCircle(left, top, dp(7) * onlineProgress, Theme.dialogs_onlineCirclePaint);
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider));
canvas.drawCircle(left, top, dp(5) * onlineProgress, Theme.dialogs_onlineCirclePaint);
if (isOnline) {
if (onlineProgress < 1.0f) {
onlineProgress += 16f / 150.0f;
if (onlineProgress > 1.0f) {
onlineProgress = 1.0f;
}
needInvalidate = true;
}
} else {
if (onlineProgress > 0.0f) {
onlineProgress -= 16f / 150.0f;
if (onlineProgress < 0.0f) {
onlineProgress = 0.0f;
}
needInvalidate = true;
}
}
}
} else if (chat != null) {
hasCall = chat.call_active && chat.call_not_empty;
if ((hasCall || chatCallProgress != 0) && rightFragmentOpenedProgress < 1f) {
float checkProgress = checkBox != null && checkBox.isChecked() ? 1.0f - checkBox.getProgress() : 1.0f;
int top = (int) (storyParams.originalAvatarRect.bottom - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 6 : 8));
int left;
if (LocaleController.isRTL) {
left = (int) (storyParams.originalAvatarRect.left + dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6));
} else {
left = (int) (storyParams.originalAvatarRect.right - dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6));
}
if (rightFragmentOpenedProgress != 0) {
canvas.save();
float scale = 1f - rightFragmentOpenedProgress;
canvas.scale(scale, scale, left, top);
}
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
canvas.drawCircle(left, top, dp(11) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint);
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider));
canvas.drawCircle(left, top, dp(9) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint);
Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider));
float size1;
float size2;
if (!LiteMode.isEnabled(LiteMode.FLAGS_CHAT)) {
innerProgress = 0.65f;
}
if (progressStage == 0) {
size1 = dp(1) + dp(4) * innerProgress;
size2 = dp(3) - dp(2) * innerProgress;
} else if (progressStage == 1) {
size1 = dp(5) - dp(4) * innerProgress;
size2 = dp(1) + dp(4) * innerProgress;
} else if (progressStage == 2) {
size1 = dp(1) + dp(2) * innerProgress;
size2 = dp(5) - dp(4) * innerProgress;
} else if (progressStage == 3) {
size1 = dp(3) - dp(2) * innerProgress;
size2 = dp(1) + dp(2) * innerProgress;
} else if (progressStage == 4) {
size1 = dp(1) + dp(4) * innerProgress;
size2 = dp(3) - dp(2) * innerProgress;
} else if (progressStage == 5) {
size1 = dp(5) - dp(4) * innerProgress;
size2 = dp(1) + dp(4) * innerProgress;
} else if (progressStage == 6) {
size1 = dp(1) + dp(4) * innerProgress;
size2 = dp(5) - dp(4) * innerProgress;
} else {
size1 = dp(5) - dp(4) * innerProgress;
size2 = dp(1) + dp(2) * innerProgress;
}
if (chatCallProgress < 1.0f || checkProgress < 1.0f) {
canvas.save();
canvas.scale(chatCallProgress * checkProgress, chatCallProgress * checkProgress, left, top);
}
rect.set(left - dp(1), top - size1, left + dp(1), top + size1);
canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint);
rect.set(left - dp(5), top - size2, left - dp(3), top + size2);
canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint);
rect.set(left + dp(3), top - size2, left + dp(5), top + size2);
canvas.drawRoundRect(rect, dp(1), dp(1), Theme.dialogs_onlineCirclePaint);
if (chatCallProgress < 1.0f || checkProgress < 1.0f) {
canvas.restore();
}
if (LiteMode.isEnabled(LiteMode.FLAGS_CHAT)) {
innerProgress += 16f / 400.0f;
if (innerProgress >= 1.0f) {
innerProgress = 0.0f;
progressStage++;
if (progressStage >= 8) {
progressStage = 0;
}
}
needInvalidate = true;
}
if (hasCall) {
if (chatCallProgress < 1.0f) {
chatCallProgress += 16f / 150.0f;
if (chatCallProgress > 1.0f) {
chatCallProgress = 1.0f;
}
}
} else {
if (chatCallProgress > 0.0f) {
chatCallProgress -= 16f / 150.0f;
if (chatCallProgress < 0.0f) {
chatCallProgress = 0.0f;
}
}
}
if (rightFragmentOpenedProgress != 0) {
canvas.restore();
}
}
}
if (showTtl) {
if (ttlProgress < 1.0f) {
ttlProgress += 16f / 150.0f;
needInvalidate = true;
}
} else {
if (ttlProgress > 0.0f) {
ttlProgress -= 16f / 150.0f;
needInvalidate = true;
}
}
ttlProgress = Utilities.clamp(ttlProgress, 1f, 0);
}
return needInvalidate;
}
private void drawCounter(Canvas canvas, boolean drawCounterMuted, int countTop, int countLeftLocal, int countLeftOld, float globalScale, boolean outline) {
final boolean drawBubble = isForumCell() || isFolderCell();
if (drawCount && drawCount2 || countChangeProgress != 1f) {
final float progressFinal = (unreadCount == 0 && !markUnread) ? 1f - countChangeProgress : countChangeProgress;
Paint paint;
int fillPaintAlpha = 255;
boolean restoreCountTextPaint = false;
if (outline) {
if (counterPaintOutline == null) {
counterPaintOutline = new Paint();
counterPaintOutline.setStyle(Paint.Style.STROKE);
counterPaintOutline.setStrokeWidth(dp(2));
counterPaintOutline.setStrokeJoin(Paint.Join.ROUND);
counterPaintOutline.setStrokeCap(Paint.Cap.ROUND);
}
int color = Theme.getColor(Theme.key_chats_pinnedOverlay);
counterPaintOutline.setColor(ColorUtils.blendARGB(
Theme.getColor(Theme.key_windowBackgroundWhite),
ColorUtils.setAlphaComponent(color, 255),
Color.alpha(color) / 255f
));
}
if (isTopic && forumTopic.read_inbox_max_id == 0) {
if (topicCounterPaint == null) {
topicCounterPaint = new Paint();
}
paint = topicCounterPaint;
int color = Theme.getColor(drawCounterMuted ? Theme.key_topics_unreadCounterMuted : Theme.key_topics_unreadCounter, resourcesProvider);
paint.setColor(color);
Theme.dialogs_countTextPaint.setColor(color);
fillPaintAlpha = drawCounterMuted ? 30 : 40;
restoreCountTextPaint = true;
} else {
paint = drawCounterMuted || currentDialogFolderId != 0 ? Theme.dialogs_countGrayPaint : Theme.dialogs_countPaint;
}
if (countOldLayout == null || unreadCount == 0) {
StaticLayout drawLayout = unreadCount == 0 ? countOldLayout : countLayout;
paint.setAlpha((int) ((1.0f - reorderIconProgress) * fillPaintAlpha));
Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
int x = countLeftLocal - dp(5.5f);
rect.set(x, countTop, x + countWidth + dp(11), countTop + dp(23));
int restoreToCount = canvas.save();
if (globalScale != 1f) {
canvas.scale(globalScale, globalScale, rect.centerX(), rect.centerY());
}
if (progressFinal != 1f) {
if (getIsPinned()) {
Theme.dialogs_pinnedDrawable.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
setDrawableBounds(Theme.dialogs_pinnedDrawable, pinLeft, pinTop);
canvas.save();
canvas.scale(1f - progressFinal, 1f - progressFinal, Theme.dialogs_pinnedDrawable.getBounds().centerX(), Theme.dialogs_pinnedDrawable.getBounds().centerY());
Theme.dialogs_pinnedDrawable.draw(canvas);
canvas.restore();
}
canvas.scale(progressFinal, progressFinal, rect.centerX(), rect.centerY());
}
if (drawBubble) {
if (counterPath == null || counterPathRect == null || !counterPathRect.equals(rect)) {
if (counterPathRect == null) {
counterPathRect = new RectF(rect);
} else {
counterPathRect.set(rect);
}
if (counterPath == null) {
counterPath = new Path();
}
BubbleCounterPath.addBubbleRect(counterPath, counterPathRect, dp(11.5f));
}
canvas.drawPath(counterPath, paint);
if (outline) {
canvas.drawPath(counterPath, counterPaintOutline);
}
} else {
canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), paint);
if (outline) {
canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), counterPaintOutline);
}
}
if (drawLayout != null) {
canvas.save();
canvas.translate(countLeftLocal, countTop + dp(4));
drawLayout.draw(canvas);
canvas.restore();
}
canvas.restoreToCount(restoreToCount);
} else {
paint.setAlpha((int) ((1.0f - reorderIconProgress) * fillPaintAlpha));
Theme.dialogs_countTextPaint.setAlpha((int) ((1.0f - reorderIconProgress) * 255));
float progressHalf = progressFinal * 2;
if (progressHalf > 1f) {
progressHalf = 1f;
}
float countLeft = countLeftLocal * progressHalf + countLeftOld * (1f - progressHalf);
float x = countLeft - dp(5.5f);
rect.set(x, countTop, x + (countWidth * progressHalf) + (countWidthOld * (1f - progressHalf)) + dp(11), countTop + dp(23));
float scale = 1f;
if (progressFinal <= 0.5f) {
scale += 0.1f * CubicBezierInterpolator.EASE_OUT.getInterpolation(progressFinal * 2);
} else {
scale += 0.1f * CubicBezierInterpolator.EASE_IN.getInterpolation((1f - (progressFinal - 0.5f) * 2));
}
canvas.save();
canvas.scale(scale * globalScale, scale * globalScale, rect.centerX(), rect.centerY());
if (drawBubble) {
if (counterPath == null || counterPathRect == null || !counterPathRect.equals(rect)) {
if (counterPathRect == null) {
counterPathRect = new RectF(rect);
} else {
counterPathRect.set(rect);
}
if (counterPath == null) {
counterPath = new Path();
}
BubbleCounterPath.addBubbleRect(counterPath, counterPathRect, dp(11.5f));
}
canvas.drawPath(counterPath, paint);
if (outline) {
canvas.drawPath(counterPath, counterPaintOutline);
}
} else {
canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), paint);
if (outline) {
canvas.drawRoundRect(rect, dp(11.5f), dp(11.5f), counterPaintOutline);
}
}
if (countAnimationStableLayout != null) {
canvas.save();
canvas.translate(countLeft, countTop + dp(4));
countAnimationStableLayout.draw(canvas);
canvas.restore();
}
int textAlpha = Theme.dialogs_countTextPaint.getAlpha();
Theme.dialogs_countTextPaint.setAlpha((int) (textAlpha * progressHalf));
if (countAnimationInLayout != null) {
canvas.save();
canvas.translate(countLeft, (countAnimationIncrement ? dp(13) : -dp(13)) * (1f - progressHalf) + countTop + dp(4));
countAnimationInLayout.draw(canvas);
canvas.restore();
} else if (countLayout != null) {
canvas.save();
canvas.translate(countLeft, (countAnimationIncrement ? dp(13) : -dp(13)) * (1f - progressHalf) + countTop + dp(4));
countLayout.draw(canvas);
canvas.restore();
}
if (countOldLayout != null) {
Theme.dialogs_countTextPaint.setAlpha((int) (textAlpha * (1f - progressHalf)));
canvas.save();
canvas.translate(countLeft, (countAnimationIncrement ? -dp(13) : dp(13)) * progressHalf + countTop + dp(4));
countOldLayout.draw(canvas);
canvas.restore();
}
Theme.dialogs_countTextPaint.setAlpha(textAlpha);
canvas.restore();
}
if (restoreCountTextPaint) {
Theme.dialogs_countTextPaint.setColor(Theme.getColor(Theme.key_chats_unreadCounterText));
}
}
}
private void createStatusDrawableAnimator(int lastStatusDrawableParams, int currentStatus) {
statusDrawableProgress = 0f;
statusDrawableAnimator = ValueAnimator.ofFloat(0,1f);
statusDrawableAnimator.setDuration(220);
statusDrawableAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT);
animateFromStatusDrawableParams = lastStatusDrawableParams;
animateToStatusDrawableParams = currentStatus;
statusDrawableAnimator.addUpdateListener(valueAnimator -> {
statusDrawableProgress = (float) valueAnimator.getAnimatedValue();
invalidate();
});
statusDrawableAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
int currentStatus = (DialogCell.this.drawClock ? 1 : 0) + (DialogCell.this.drawCheck1 ? 2 : 0) + (DialogCell.this.drawCheck2 ? 4 : 0);
if (animateToStatusDrawableParams != currentStatus) {
createStatusDrawableAnimator(animateToStatusDrawableParams, currentStatus);
} else {
statusDrawableAnimationInProgress = false;
DialogCell.this.lastStatusDrawableParams = animateToStatusDrawableParams;
}
invalidate();
}
});
statusDrawableAnimationInProgress = true;
statusDrawableAnimator.start();
}
public void startOutAnimation() {
if (archivedChatsDrawable != null) {
if (isTopic) {
archivedChatsDrawable.outCy = dp(10 + 14);
archivedChatsDrawable.outCx = dp(10 + 14);
archivedChatsDrawable.outRadius = 0;
archivedChatsDrawable.outImageSize = 0;
} else {
archivedChatsDrawable.outCy = storyParams.originalAvatarRect.centerY();
archivedChatsDrawable.outCx = storyParams.originalAvatarRect.centerX();
archivedChatsDrawable.outRadius = storyParams.originalAvatarRect.width() / 2.0f;
if (MessagesController.getInstance(currentAccount).getStoriesController().hasHiddenStories()) {
archivedChatsDrawable.outRadius -= AndroidUtilities.dpf2(3.5f);
}
archivedChatsDrawable.outImageSize = avatarImage.getBitmapWidth();
}
archivedChatsDrawable.startOutAnimation();
}
}
public void onReorderStateChanged(boolean reordering, boolean animated) {
if (!getIsPinned() && reordering || drawReorder == reordering) {
if (!getIsPinned()) {
drawReorder = false;
}
return;
}
drawReorder = reordering;
if (animated) {
reorderIconProgress = drawReorder ? 0.0f : 1.0f;
} else {
reorderIconProgress = drawReorder ? 1.0f : 0.0f;
}
invalidate();
}
public void setSliding(boolean value) {
isSliding = value;
}
@Override
public void invalidateDrawable(Drawable who) {
if (who == translationDrawable || who == Theme.dialogs_archiveAvatarDrawable) {
invalidate(who.getBounds());
} else {
super.invalidateDrawable(who);
}
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
@Override
public boolean performAccessibilityAction(int action, Bundle arguments) {
if (action == R.id.acc_action_chat_preview && parentFragment != null) {
parentFragment.showChatPreview(this);
return true;
}
return super.performAccessibilityAction(action, arguments);
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (isFolderCell() && archivedChatsDrawable != null && SharedConfig.archiveHidden && archivedChatsDrawable.pullProgress == 0.0f) {
info.setVisibleToUser(false);
} else {
info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
if (!isFolderCell() && parentFragment != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
info.addAction(new AccessibilityNodeInfo.AccessibilityAction(R.id.acc_action_chat_preview, LocaleController.getString("AccActionChatPreview", R.string.AccActionChatPreview)));
}
}
if (checkBox != null && checkBox.isChecked()) {
info.setClassName("android.widget.CheckBox");
info.setCheckable(true);
info.setChecked(true);
}
}
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
super.onPopulateAccessibilityEvent(event);
StringBuilder sb = new StringBuilder();
if (currentDialogFolderId == 1) {
sb.append(LocaleController.getString("ArchivedChats", R.string.ArchivedChats));
sb.append(". ");
} else {
if (encryptedChat != null) {
sb.append(LocaleController.getString("AccDescrSecretChat", R.string.AccDescrSecretChat));
sb.append(". ");
}
if (isTopic && forumTopic != null) {
sb.append(LocaleController.getString("AccDescrTopic", R.string.AccDescrTopic));
sb.append(". ");
sb.append(forumTopic.title);
sb.append(". ");
} else if (user != null) {
if (UserObject.isReplyUser(user)) {
sb.append(LocaleController.getString("RepliesTitle", R.string.RepliesTitle));
} else if (UserObject.isAnonymous(user)) {
sb.append(LocaleController.getString(R.string.AnonymousForward));
} else {
if (user.bot) {
sb.append(LocaleController.getString("Bot", R.string.Bot));
sb.append(". ");
}
if (user.self) {
sb.append(LocaleController.getString("SavedMessages", R.string.SavedMessages));
} else {
sb.append(ContactsController.formatName(user.first_name, user.last_name));
}
}
sb.append(". ");
} else if (chat != null) {
if (chat.broadcast) {
sb.append(LocaleController.getString("AccDescrChannel", R.string.AccDescrChannel));
} else {
sb.append(LocaleController.getString("AccDescrGroup", R.string.AccDescrGroup));
}
sb.append(". ");
sb.append(chat.title);
sb.append(". ");
}
}
if (drawVerified) {
sb.append(LocaleController.getString("AccDescrVerified", R.string.AccDescrVerified));
sb.append(". ");
}
if (dialogMuted) {
sb.append(LocaleController.getString("AccDescrNotificationsMuted", R.string.AccDescrNotificationsMuted));
sb.append(". ");
}
if (isOnline()) {
sb.append(LocaleController.getString("AccDescrUserOnline", R.string.AccDescrUserOnline));
sb.append(". ");
}
if (unreadCount > 0) {
sb.append(LocaleController.formatPluralString("NewMessages", unreadCount));
sb.append(". ");
}
if (mentionCount > 0) {
sb.append(LocaleController.formatPluralString("AccDescrMentionCount", mentionCount));
sb.append(". ");
}
if (reactionMentionCount > 0) {
sb.append(LocaleController.getString("AccDescrMentionReaction", R.string.AccDescrMentionReaction));
sb.append(". ");
}
if (message == null || currentDialogFolderId != 0) {
event.setContentDescription(sb);
setContentDescription(sb);
return;
}
int lastDate = lastMessageDate;
if (lastMessageDate == 0) {
lastDate = message.messageOwner.date;
}
String date = LocaleController.formatDateAudio(lastDate, true);
if (message.isOut()) {
sb.append(LocaleController.formatString("AccDescrSentDate", R.string.AccDescrSentDate, date));
} else {
sb.append(LocaleController.formatString("AccDescrReceivedDate", R.string.AccDescrReceivedDate, date));
}
sb.append(". ");
if (chat != null && !message.isOut() && message.isFromUser() && message.messageOwner.action == null) {
TLRPC.User fromUser = MessagesController.getInstance(currentAccount).getUser(message.messageOwner.from_id.user_id);
if (fromUser != null) {
sb.append(ContactsController.formatName(fromUser.first_name, fromUser.last_name));
sb.append(". ");
}
}
if (encryptedChat == null) {
StringBuilder messageString = new StringBuilder();
messageString.append(message.messageText);
if (!message.isMediaEmpty()) {
MessageObject captionMessage = getCaptionMessage();
if (captionMessage != null && !TextUtils.isEmpty(captionMessage.caption)) {
if (messageString.length() > 0) {
messageString.append(". ");
}
messageString.append(captionMessage.caption);
}
}
int len = messageLayout == null ? -1 : messageLayout.getText().length();
if (len > 0) {
int index = messageString.length(), b;
if ((b = messageString.indexOf("\n", len)) < index && b >= 0)
index = b;
if ((b = messageString.indexOf("\t", len)) < index && b >= 0)
index = b;
if ((b = messageString.indexOf(" ", len)) < index && b >= 0)
index = b;
sb.append(messageString.substring(0, index));
} else {
sb.append(messageString);
}
}
event.setContentDescription(sb);
setContentDescription(sb);
}
private MessageObject getCaptionMessage() {
if (groupMessages == null) {
if (message != null && message.caption != null) {
return message;
}
return null;
}
MessageObject captionMessage = null;
int hasCaption = 0;
for (int i = 0; i < groupMessages.size(); ++i) {
MessageObject msg = groupMessages.get(i);
if (msg != null && msg.caption != null) {
captionMessage = msg;
if (!TextUtils.isEmpty(msg.caption)) {
hasCaption++;
}
}
}
if (hasCaption > 1) {
return null;
}
return captionMessage;
}
public void updateMessageThumbs() {
if (message == null) {
return;
}
String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason);
if (groupMessages != null && groupMessages.size() > 1 && TextUtils.isEmpty(restrictionReason) && currentDialogFolderId == 0 && encryptedChat == null) {
thumbsCount = 0;
hasVideoThumb = false;
Collections.sort(groupMessages, Comparator.comparingInt(MessageObject::getId));
for (int i = 0; i < Math.min(3, groupMessages.size()); ++i) {
MessageObject message = groupMessages.get(i);
if (message != null && !message.needDrawBluredPreview() && (message.isPhoto() || message.isNewGif() || message.isVideo() || message.isRoundVideo() || message.isStoryMedia())) {
String type = message.isWebpage() ? message.messageOwner.media.webpage.type : null;
if (!("app".equals(type) || "profile".equals(type) || "article".equals(type) || type != null && type.startsWith("telegram_"))) {
setThumb(i, message);
}
}
}
} else if (message != null && currentDialogFolderId == 0) {
thumbsCount = 0;
hasVideoThumb = false;
if (!message.needDrawBluredPreview() && (message.isPhoto() || message.isNewGif() || message.isVideo() || message.isRoundVideo() || message.isStoryMedia())) {
String type = message.isWebpage() ? message.messageOwner.media.webpage.type : null;
if (!("app".equals(type) || "profile".equals(type) || "article".equals(type) || type != null && type.startsWith("telegram_"))) {
setThumb(0, message);
}
}
}
}
private void setThumb(int index, MessageObject message) {
ArrayList<TLRPC.PhotoSize> photoThumbs = message.photoThumbs;
TLObject photoThumbsObject = message.photoThumbsObject;
if (message.isStoryMedia()) {
TL_stories.StoryItem storyItem = message.messageOwner.media.storyItem;
if (storyItem != null && storyItem.media != null) {
if (storyItem.media.document != null) {
photoThumbs = storyItem.media.document.thumbs;
photoThumbsObject = storyItem.media.document;
} else if (storyItem.media.photo != null) {
photoThumbs = storyItem.media.photo.sizes;
photoThumbsObject = storyItem.media.photo;
}
} else {
return;
}
}
TLRPC.PhotoSize smallThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, 40);
TLRPC.PhotoSize bigThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, AndroidUtilities.getPhotoSize());
if (smallThumb == bigThumb) {
bigThumb = null;
}
TLRPC.PhotoSize selectedThumb = bigThumb;
if (selectedThumb == null || DownloadController.getInstance(currentAccount).canDownloadMedia(message.messageOwner) == 0) {
selectedThumb = smallThumb;
}
if (smallThumb != null) {
hasVideoThumb = hasVideoThumb || (message.isVideo() || message.isRoundVideo());
if (thumbsCount < 3) {
thumbsCount++;
drawPlay[index] = (message.isVideo() || message.isRoundVideo()) && !message.hasMediaSpoilers();
drawSpoiler[index] = message.hasMediaSpoilers();
int size = message.type == MessageObject.TYPE_PHOTO && selectedThumb != null ? selectedThumb.size : 0;
String filter = message.hasMediaSpoilers() ? "5_5_b" : "20_20";
thumbImage[index].setImage(ImageLocation.getForObject(selectedThumb, photoThumbsObject), filter, ImageLocation.getForObject(smallThumb, photoThumbsObject), filter, size, null, message, 0);
thumbImage[index].setRoundRadius(message.isRoundVideo() ? dp(18) : dp(2));
needEmoji = false;
}
}
}
public String getMessageNameString() {
if (message == null) {
return null;
}
TLRPC.User user;
TLRPC.User fromUser = null;
TLRPC.Chat fromChat = null;
long fromId = message.getFromChatId();
final long selfId = UserConfig.getInstance(currentAccount).getClientUserId();
if (!isSavedDialog && currentDialogId == selfId) {
long savedDialogId = message.getSavedDialogId();
if (savedDialogId == selfId) {
return null;
} else if (savedDialogId != UserObject.ANONYMOUS) {
if (message.messageOwner != null && message.messageOwner.fwd_from != null) {
long fwdId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.saved_from_id);
if (fwdId == 0) {
fwdId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.from_id);
}
if (fwdId > 0 && fwdId != savedDialogId) {
return null;
}
}
fromId = savedDialogId;
}
}
if (isSavedDialog && message.messageOwner != null && message.messageOwner.fwd_from != null) {
fromId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.saved_from_id);
if (fromId == 0) {
fromId = DialogObject.getPeerDialogId(message.messageOwner.fwd_from.from_id);
}
}
if (DialogObject.isUserDialog(fromId)) {
fromUser = MessagesController.getInstance(currentAccount).getUser(fromId);
} else {
fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId);
}
if (currentDialogId == selfId) {
if (fromUser != null) {
return UserObject.getFirstName(fromUser).replace("\n", "");
} else if (fromChat != null) {
return fromChat.title.replace("\n", "");
}
return null;
} else if (message.isOutOwner()) {
return LocaleController.getString("FromYou", R.string.FromYou);
} else if (!isSavedDialog && message != null && message.messageOwner != null && message.messageOwner.from_id instanceof TLRPC.TL_peerUser && (user = MessagesController.getInstance(currentAccount).getUser(message.messageOwner.from_id.user_id)) != null) {
return UserObject.getFirstName(user).replace("\n", "");
} else if (message != null && message.messageOwner != null && message.messageOwner.fwd_from != null && message.messageOwner.fwd_from.from_name != null) {
return message.messageOwner.fwd_from.from_name;
} else if (fromUser != null) {
if (useForceThreeLines || SharedConfig.useThreeLinesLayout) {
if (UserObject.isDeleted(fromUser)) {
return LocaleController.getString("HiddenName", R.string.HiddenName);
} else {
return ContactsController.formatName(fromUser.first_name, fromUser.last_name).replace("\n", "");
}
} else {
return UserObject.getFirstName(fromUser).replace("\n", "");
}
} else if (fromChat != null && fromChat.title != null) {
return fromChat.title.replace("\n", "");
} else {
return "DELETED";
}
}
public SpannableStringBuilder getMessageStringFormatted(int messageFormatType, String restrictionReason, CharSequence messageNameString, boolean applyThumbs) {
SpannableStringBuilder stringBuilder;
MessageObject captionMessage = getCaptionMessage();
CharSequence msgText = message != null ? message.messageText : null;
applyName = true;
if (!TextUtils.isEmpty(restrictionReason)) {
stringBuilder = formatInternal(messageFormatType, restrictionReason, messageNameString);
} else if (message.messageOwner instanceof TLRPC.TL_messageService) {
CharSequence mess;
if (message.messageTextShort != null && (!(message.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate) || !isTopic)) {
mess = message.messageTextShort;
} else {
mess = message.messageText;
}
if (MessageObject.isTopicActionMessage(message)) {
stringBuilder = formatInternal(messageFormatType, mess, messageNameString);
if (message.topicIconDrawable[0] instanceof ForumBubbleDrawable) {
TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-message.getDialogId(), MessageObject.getTopicId(currentAccount, message.messageOwner, true));
if (topic != null) {
((ForumBubbleDrawable) message.topicIconDrawable[0]).setColor(topic.icon_color);
}
}
} else {
applyName = false;
stringBuilder = SpannableStringBuilder.valueOf(mess);
}
if (applyThumbs) {
applyThumbs(stringBuilder);
}
} else if (captionMessage != null && captionMessage.caption != null) {
MessageObject message = captionMessage;
CharSequence mess = message.caption.toString();
String emoji;
if (!needEmoji) {
emoji = "";
} else if (message.isVideo()) {
emoji = "\uD83D\uDCF9 ";
} else if (message.isVoice()) {
emoji = "\uD83C\uDFA4 ";
} else if (message.isMusic()) {
emoji = "\uD83C\uDFA7 ";
} else if (message.isPhoto()) {
emoji = "\uD83D\uDDBC ";
} else {
emoji = "\uD83D\uDCCE ";
}
if (message.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) {
CharSequence text = message.messageTrimmedToHighlight;
int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 24);
if (hasNameInMessage) {
if (!TextUtils.isEmpty(messageNameString)) {
w -= currentMessagePaint.measureText(messageNameString.toString());
}
w -= currentMessagePaint.measureText(": ");
}
if (w > 0) {
text = AndroidUtilities.ellipsizeCenterEnd(text, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
}
stringBuilder = new SpannableStringBuilder(emoji).append(text);
} else {
if (mess.length() > 150) {
mess = mess.subSequence(0, 150);
}
SpannableStringBuilder msgBuilder = new SpannableStringBuilder(mess);
if (message != null) {
message.spoilLoginCode();
}
MediaDataController.addTextStyleRuns(message.messageOwner.entities, mess, msgBuilder, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE);
if (message != null && message.messageOwner != null) {
MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, msgBuilder, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt());
}
CharSequence charSequence = new SpannableStringBuilder(emoji).append(AndroidUtilities.replaceNewLines(msgBuilder));
if (applyThumbs) {
charSequence = applyThumbs(charSequence);
}
stringBuilder = formatInternal(messageFormatType, charSequence, messageNameString);
}
} else if (message.messageOwner.media != null && !message.isMediaEmpty()) {
currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex];
CharSequence innerMessage;
int colorKey = Theme.key_chats_attachMessage;
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.messageOwner.media;
if (Build.VERSION.SDK_INT >= 18) {
if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) {
SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text.replace('\n', ' '));
MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText);
MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt());
innerMessage = new SpannableStringBuilder("\uD83D\uDCCA \u2068").append(questionText).append("\u2069");
} else {
innerMessage = String.format("\uD83D\uDCCA \u2068%s\u2069", mediaPoll.poll.question.text);
}
} else {
if (mediaPoll.poll.question != null && mediaPoll.poll.question.entities != null) {
SpannableStringBuilder questionText = new SpannableStringBuilder(mediaPoll.poll.question.text.replace('\n', ' '));
MediaDataController.addTextStyleRuns(mediaPoll.poll.question.entities, mediaPoll.poll.question.text, questionText);
MediaDataController.addAnimatedEmojiSpans(mediaPoll.poll.question.entities, questionText, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt());
innerMessage = new SpannableStringBuilder("\uD83D\uDCCA ").append(questionText);
} else {
innerMessage = String.format("\uD83D\uDCCA %s", mediaPoll.poll.question.text);
}
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
if (Build.VERSION.SDK_INT >= 18) {
innerMessage = String.format("\uD83C\uDFAE \u2068%s\u2069", message.messageOwner.media.game.title);
} else {
innerMessage = String.format("\uD83C\uDFAE %s", message.messageOwner.media.game.title);
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice) {
innerMessage = message.messageOwner.media.title;
} else if (message.type == MessageObject.TYPE_MUSIC) {
if (Build.VERSION.SDK_INT >= 18) {
innerMessage = String.format("\uD83C\uDFA7 \u2068%s - %s\u2069", message.getMusicAuthor(), message.getMusicTitle());
} else {
innerMessage = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle());
}
} else if (thumbsCount > 1) {
if (hasVideoThumb) {
innerMessage = LocaleController.formatPluralString("Media", groupMessages == null ? 0 : groupMessages.size());
} else {
innerMessage = LocaleController.formatPluralString("Photos", groupMessages == null ? 0 : groupMessages.size());
}
colorKey = Theme.key_chats_actionMessage;
} else {
innerMessage = msgText.toString();
colorKey = Theme.key_chats_actionMessage;
}
if (innerMessage instanceof String) {
innerMessage = ((String) innerMessage).replace('\n', ' ');
}
CharSequence message = innerMessage;
if (applyThumbs) {
message = applyThumbs(innerMessage);
}
stringBuilder = formatInternal(messageFormatType, message, messageNameString);
if (!isForumCell()) {
try {
stringBuilder.setSpan(new ForegroundColorSpanThemable(colorKey, resourcesProvider), hasNameInMessage ? messageNameString.length() + 2 : 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
FileLog.e(e);
}
}
} else if (message.messageOwner.message != null) {
CharSequence mess = message.messageOwner.message;
if (message.hasHighlightedWords()) {
if (message.messageTrimmedToHighlight != null) {
mess = message.messageTrimmedToHighlight;
}
int w = getMeasuredWidth() - dp(messagePaddingStart + 23 + 10);
if (hasNameInMessage) {
if (!TextUtils.isEmpty(messageNameString)) {
w -= currentMessagePaint.measureText(messageNameString.toString());
}
w -= currentMessagePaint.measureText(": ");
}
if (w > 0) {
mess = AndroidUtilities.ellipsizeCenterEnd(mess, message.highlightedWords.get(0), w, currentMessagePaint, 130).toString();
}
} else {
if (mess.length() > 150) {
mess = mess.subSequence(0, 150);
}
mess = AndroidUtilities.replaceNewLines(mess);
}
mess = new SpannableStringBuilder(mess);
if (message != null) {
message.spoilLoginCode();
}
MediaDataController.addTextStyleRuns(message, (Spannable) mess, TextStyleSpan.FLAG_STYLE_SPOILER | TextStyleSpan.FLAG_STYLE_STRIKE);
if (message != null && message.messageOwner != null) {
MediaDataController.addAnimatedEmojiSpans(message.messageOwner.entities, mess, currentMessagePaint == null ? null : currentMessagePaint.getFontMetricsInt());
}
if (applyThumbs) {
mess = applyThumbs(mess);
}
stringBuilder = formatInternal(messageFormatType, mess, messageNameString);
} else {
stringBuilder = new SpannableStringBuilder();
}
return stringBuilder;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (rightFragmentOpenedProgress == 0 && !isTopic && storyParams.checkOnTouchEvent(ev, this)) {
return true;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (!isTopic && ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
storyParams.checkOnTouchEvent(ev, this);
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (rightFragmentOpenedProgress == 0 && !isTopic && storyParams.checkOnTouchEvent(event, this)) {
return true;
}
if (delegate == null || delegate.canClickButtonInside()) {
if (lastTopicMessageUnread && canvasButton != null && buttonLayout != null && (dialogsType == DialogsActivity.DIALOGS_TYPE_DEFAULT || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER1 || dialogsType == DialogsActivity.DIALOGS_TYPE_FOLDER2) && canvasButton.checkTouchEvent(event)) {
return true;
}
}
return super.onTouchEvent(event);
}
public void setClipProgress(float value) {
clipProgress = value;
invalidate();
}
public float getClipProgress() {
return clipProgress;
}
public void setTopClip(int value) {
topClip = value;
}
public void setBottomClip(int value) {
bottomClip = value;
}
public void setArchivedPullAnimation(PullForegroundDrawable drawable) {
archivedChatsDrawable = drawable;
}
public int getCurrentDialogFolderId() {
return currentDialogFolderId;
}
public boolean isDialogFolder() {
return currentDialogFolderId > 0;
}
public MessageObject getMessage() {
return message;
}
public void setDialogCellDelegate(DialogCellDelegate delegate) {
this.delegate = delegate;
}
public interface DialogCellDelegate {
void onButtonClicked(DialogCell dialogCell);
void onButtonLongPress(DialogCell dialogCell);
boolean canClickButtonInside();
void openStory(DialogCell dialogCell, Runnable onDone);
void showChatPreview(DialogCell dialogCell);
void openHiddenStories();
}
private class DialogUpdateHelper {
public long lastDrawnDialogId;
public long lastDrawnMessageId;
public boolean lastDrawnTranslated;
public boolean lastDrawnDialogIsFolder;
public long lastDrawnReadState;
public int lastDrawnDraftHash;
public Integer lastDrawnPrintingType;
public int lastDrawnSizeHash;
public int lastTopicsCount;
public boolean lastDrawnPinned;
public boolean lastDrawnHasCall;
public float typingProgres;
public boolean typingOutToTop;
public int lastKnownTypingType;
boolean waitngNewMessageFroTypingAnimation = false;
long startWaitingTime;
public boolean update() {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(currentDialogId);
if (dialog == null) {
if (dialogsType == DialogsActivity.DIALOGS_TYPE_FORWARD && lastDrawnDialogId != currentDialogId) {
lastDrawnDialogId = currentDialogId;
return true;
}
return false;
}
int messageHash = message == null ? 0 : message.getId() + message.hashCode();
Integer printingType = null;
long readHash = dialog.read_inbox_max_id + ((long) dialog.read_outbox_max_id << 8) + ((long) (dialog.unread_count + (dialog.unread_mark ? -1 : 0)) << 16) +
(dialog.unread_reactions_count > 0 ? (1 << 18) : 0) +
(dialog.unread_mentions_count > 0 ? (1 << 19) : 0);
if (!isForumCell() && (isDialogCell || isTopic)) {
if (!TextUtils.isEmpty(MessagesController.getInstance(currentAccount).getPrintingString(currentDialogId, getTopicId(), true))) {
printingType = MessagesController.getInstance(currentAccount).getPrintingStringType(currentDialogId, getTopicId());
} else {
printingType = null;
}
}
int sizeHash = getMeasuredWidth() + (getMeasuredHeight() << 16);
int topicCount = 0;
if (isForumCell()) {
ArrayList<TLRPC.TL_forumTopic> topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(-currentDialogId);
topicCount = topics == null ? -1 : topics.size();
if (topicCount == -1 && MessagesController.getInstance(currentAccount).getTopicsController().endIsReached(-currentDialogId)) {
topicCount = 0;
}
}
boolean draftVoice = false;
TLRPC.DraftMessage draftMessage = null;
if (isTopic) {
draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, getTopicId()) != null;
draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, getTopicId()) : null;
if (draftMessage != null && TextUtils.isEmpty(draftMessage.message)) {
draftMessage = null;
}
} else if (isDialogCell) {
draftVoice = MediaDataController.getInstance(currentAccount).getDraftVoice(currentDialogId, 0) != null;
draftMessage = !draftVoice ? MediaDataController.getInstance(currentAccount).getDraft(currentDialogId, 0) : null;
}
int draftHash = draftMessage == null ? 0 : draftMessage.message.hashCode() + (draftMessage.reply_to != null ? (draftMessage.reply_to.reply_to_msg_id << 16) : 0);
boolean hasCall = chat != null && chat.call_active && chat.call_not_empty;
boolean translated = MessagesController.getInstance(currentAccount).getTranslateController().isTranslatingDialog(currentDialogId);
if (lastDrawnSizeHash == sizeHash &&
lastDrawnMessageId == messageHash &&
lastDrawnTranslated == translated &&
lastDrawnDialogId == currentDialogId &&
lastDrawnDialogIsFolder == dialog.isFolder &&
lastDrawnReadState == readHash &&
Objects.equals(lastDrawnPrintingType, printingType) &&
lastTopicsCount == topicCount &&
draftHash == lastDrawnDraftHash &&
lastDrawnPinned == drawPin &&
lastDrawnHasCall == hasCall &&
DialogCell.this.draftVoice == draftVoice) {
return false;
}
if (lastDrawnDialogId != currentDialogId) {
typingProgres = printingType == null ? 0f : 1f;
waitngNewMessageFroTypingAnimation = false;
} else {
if (!Objects.equals(lastDrawnPrintingType, printingType) || waitngNewMessageFroTypingAnimation) {
if (!waitngNewMessageFroTypingAnimation && printingType == null) {
waitngNewMessageFroTypingAnimation = true;
startWaitingTime = System.currentTimeMillis();
} else if (waitngNewMessageFroTypingAnimation && lastDrawnMessageId != messageHash) {
waitngNewMessageFroTypingAnimation = false;
}
if (lastDrawnMessageId != messageHash) {
typingOutToTop = false;
} else {
typingOutToTop = true;
}
}
}
if (printingType != null) {
lastKnownTypingType = printingType;
}
lastDrawnDialogId = currentDialogId;
lastDrawnMessageId = messageHash;
lastDrawnDialogIsFolder = dialog.isFolder;
lastDrawnReadState = readHash;
lastDrawnPrintingType = printingType;
lastDrawnSizeHash = sizeHash;
lastDrawnDraftHash = draftHash;
lastTopicsCount = topicCount;
lastDrawnPinned = drawPin;
lastDrawnHasCall = hasCall;
lastDrawnTranslated = translated;
return true;
}
public void updateAnimationValues() {
if (!waitngNewMessageFroTypingAnimation) {
if (lastDrawnPrintingType != null && typingLayout != null && typingProgres != 1f) {
typingProgres += 16f / 200f;
invalidate();
} else if (lastDrawnPrintingType == null && typingProgres != 0) {
typingProgres -= 16f / 200f;
invalidate();
}
typingProgres = Utilities.clamp(typingProgres, 1f, 0f);
} else {
if (System.currentTimeMillis() - startWaitingTime > 100) {
waitngNewMessageFroTypingAnimation = false;
}
invalidate();
}
}
}
@Override
public void invalidate() {
if (StoryViewer.animationInProgress) {
return;
}
super.invalidate();
}
@Override
public void invalidate(int l, int t, int r, int b) {
if (StoryViewer.animationInProgress) {
return;
}
super.invalidate(l, t, r, b);
}
public static class SharedResources {
LongSparseArray<ForumFormattedNames> formattedTopicNames = new LongSparseArray<>();
}
private static class ForumFormattedNames {
int lastMessageId;
int topMessageTopicStartIndex;
int topMessageTopicEndIndex;
boolean lastTopicMessageUnread;
boolean isLoadingState;
CharSequence formattedNames;
private void formatTopicsNames(int currentAccount, MessageObject message, TLRPC.Chat chat) {
int messageId = message == null || chat == null ? 0 : message.getId();
if (lastMessageId == messageId && !isLoadingState) {
return;
}
topMessageTopicStartIndex = 0;
topMessageTopicEndIndex = 0;
lastTopicMessageUnread = false;
isLoadingState = false;
lastMessageId = messageId;
Paint currentMessagePaint = Theme.dialogs_messagePaint[0];
if (chat != null) {
List<TLRPC.TL_forumTopic> topics = MessagesController.getInstance(currentAccount).getTopicsController().getTopics(chat.id);
boolean hasDivider = false;
if (topics != null && !topics.isEmpty()) {
topics = new ArrayList<>(topics);
Collections.sort(topics, Comparator.comparingInt(o -> -o.top_message));
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
long topMessageTopicId = 0;
int boldLen = 0;
if (message != null) {
topMessageTopicId = MessageObject.getTopicId(currentAccount, message.messageOwner, true);
TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(chat.id, topMessageTopicId);
if (topic != null) {
CharSequence topicString = ForumUtilities.getTopicSpannedName(topic, currentMessagePaint, false);
spannableStringBuilder.append(topicString);
if (topic.unread_count > 0) {
boldLen = topicString.length();
}
topMessageTopicStartIndex = 0;
topMessageTopicEndIndex = topicString.length();
if (message.isOutOwner()) {
lastTopicMessageUnread = false;
} else {
lastTopicMessageUnread = topic.unread_count > 0;
}
} else {
lastTopicMessageUnread = false;
}
if (lastTopicMessageUnread) {
spannableStringBuilder.append(" ");
spannableStringBuilder.setSpan(new DialogCell.FixedWidthSpan(dp(3)), spannableStringBuilder.length() - 1, spannableStringBuilder.length(), 0);
hasDivider = true;
}
}
boolean firstApplay = true;
for (int i = 0; i < Math.min(4, topics.size()); i++) {
if (topics.get(i).id == topMessageTopicId) {
continue;
}
if (spannableStringBuilder.length() != 0) {
if (firstApplay && hasDivider) {
spannableStringBuilder.append(" ");
} else {
spannableStringBuilder.append(", ");
}
}
firstApplay = false;
CharSequence topicString = ForumUtilities.getTopicSpannedName(topics.get(i), currentMessagePaint, false);
spannableStringBuilder.append(topicString);
}
if (boldLen > 0) {
spannableStringBuilder.setSpan(
new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.key_chats_name, null),
0, Math.min(spannableStringBuilder.length(), boldLen + 2), 0
);
}
formattedNames = spannableStringBuilder;
return;
}
if (!MessagesController.getInstance(currentAccount).getTopicsController().endIsReached(chat.id)) {
MessagesController.getInstance(currentAccount).getTopicsController().preloadTopics(chat.id);
formattedNames = LocaleController.getString("Loading", R.string.Loading);
isLoadingState = true;
} else {
formattedNames = "no created topics";
}
}
}
}
private ColorFilter[] adaptiveEmojiColorFilter;
private int[] adaptiveEmojiColor;
private ColorFilter getAdaptiveEmojiColorFilter(int n, int color) {
if (adaptiveEmojiColorFilter == null) {
adaptiveEmojiColor = new int[4];
adaptiveEmojiColorFilter = new ColorFilter[4];
}
if (color != adaptiveEmojiColor[n] || adaptiveEmojiColorFilter[n] == null) {
adaptiveEmojiColorFilter[n] = new PorterDuffColorFilter(adaptiveEmojiColor[n] = color, PorterDuff.Mode.SRC_IN);
}
return adaptiveEmojiColorFilter[n];
}
private Runnable unsubscribePremiumBlocked;
public void showPremiumBlocked(boolean show) {
if (show != (unsubscribePremiumBlocked != null)) {
if (!show && unsubscribePremiumBlocked != null) {
unsubscribePremiumBlocked.run();
unsubscribePremiumBlocked = null;
} else if (show) {
unsubscribePremiumBlocked = NotificationCenter.getInstance(currentAccount).listen(this, NotificationCenter.userIsPremiumBlockedUpadted, args -> {
updatePremiumBlocked(true);
});
}
}
}
private void updatePremiumBlocked(boolean animated) {
final boolean wasPremiumBlocked = premiumBlocked;
premiumBlocked = (unsubscribePremiumBlocked != null) && user != null && MessagesController.getInstance(currentAccount).isUserPremiumBlocked(user.id);
if (wasPremiumBlocked != premiumBlocked) {
if (!animated) {
premiumBlockedT.set(premiumBlocked, true);
}
invalidate();
}
}
}
| DrKLO/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java |
45,319 | /**
* Copyright (c) 2006-2022, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
@SuppressWarnings("serial")
abstract public class GoogleAuth extends AbsAuth
{
public static String CLIENT_SECRET_FILE_PATH = "google_client_secret";
public static String CLIENT_ID_FILE_PATH = "google_client_id";
private static Config CONFIG = null;
protected Config getConfig()
{
if (CONFIG == null)
{
String clientSerets = SecretFacade.getSecret(CLIENT_SECRET_FILE_PATH, getServletContext()),
clientIds = SecretFacade.getSecret(CLIENT_ID_FILE_PATH, getServletContext());
CONFIG = new Config(clientIds, clientSerets);
CONFIG.REDIRECT_PATH = "/google";
CONFIG.AUTH_SERVICE_URL = "https://www.googleapis.com/oauth2/v4/token";
}
return CONFIG;
}
public GoogleAuth()
{
super();
cookiePath = "/google";
}
protected String getTokenFromCookieVal(String tokenCookieVal, Object request)
{
String userId = getParameter("userId", request);
if (tokenCookieVal != null && userId != null)
{
String[] tokens = tokenCookieVal.split(SEPARATOR);
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].startsWith(userId + ":"))
{
return tokens[i].substring(userId.length() + 1);
}
}
}
return tokenCookieVal;
}
protected String getRefreshTokenCookie(String refreshToken, String tokenCookieVal, String accessToken)
{
HttpURLConnection con = null;
String userId = null;
try
{
URL obj = new URL("https://www.googleapis.com/oauth2/v2/userinfo?alt=json");
con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Authorization", "Bearer " + accessToken);
con.setRequestProperty("User-Agent", "draw.io");
int status = con.getResponseCode();
if (status >= 200 && status <= 299)
{
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer strRes = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
strRes.append(inputLine);
}
in.close();
userId = new Gson().fromJson(strRes.toString(), JsonElement.class).getAsJsonObject().get("id").getAsString();
}
}
catch(Exception e)
{
e.printStackTrace();
}
if (userId != null)
{
ArrayList<String> tokens = new ArrayList<>();
tokens.add(userId + ":" + refreshToken);
if (tokenCookieVal != null)
{
String[] curTokens = tokenCookieVal.split(SEPARATOR);
for (int i = 0; i < curTokens.length; i++)
{
if (!curTokens[i].startsWith(userId + ":"))
{
tokens.add(curTokens[i]);
}
}
}
return String.join(SEPARATOR, tokens);
}
return tokenCookieVal; //If we couldn't get the userId, we just return existing tokens such that we don't corrupt them
}
protected void logout(String tokenCookieName, String tokenCookieVal, Object request, Object response)
{
String userId = getParameter("userId", request);
if (tokenCookieVal != null && userId != null)
{
ArrayList<String> tokens = new ArrayList<>();
String[] curTokens = tokenCookieVal.split(SEPARATOR);
for (int i = 0; i < curTokens.length; i++)
{
if (!curTokens[i].startsWith(userId + ":"))
{
tokens.add(curTokens[i]);
}
}
if (tokens.size() > 0)
{
addCookie(tokenCookieName, String.join(SEPARATOR, tokens), TOKEN_COOKIE_AGE, cookiePath, response);
}
else
{
deleteCookie(tokenCookieName, cookiePath, response);
}
}
}
protected String processAuthResponse(String authRes, boolean jsonResponse)
{
StringBuffer res = new StringBuffer();
//In Office Add-in, we don't have access to opened window to attach a function to it,
// also with the redirect (since we had to open google auth in the same window) we lost Office Messaging.
// This is due to using Google own file picker instead of creating our own picker
// (as we did with OneDrive since its picker only support popup windows which is not supported in Office)
// This is why we load driveLoader.js which define onGDriveCallback and redirects automatically to the page including the picker
// For other scenarios, we use another function name (onGoogleDriveCallback)
if (!jsonResponse)
{
res.append("<!DOCTYPE html><html><head>");
res.append("<script src=\"/connect/office365/js/driveLoader.js\" type=\"text/javascript\"></script>");
res.append("<script type=\"text/javascript\">");
res.append("(function() { var authInfo = "); //The following is a json containing access_token
}
res.append(authRes);
if (!jsonResponse)
{
res.append(";");
res.append("if (window.opener != null && window.opener.onGoogleDriveCallback != null)");
res.append("{");
res.append(" window.opener.onGoogleDriveCallback(authInfo, window);");
res.append("} else {");
res.append(" onGDriveCallback(authInfo);");
res.append("}");
res.append("})();</script>");
res.append("</head><body></body></html>");
}
return res.toString();
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/GoogleAuth.java |
45,320 | /*
* Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import com.sun.tools.attach.spi.AttachProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.io.IOException;
/**
* A Java virtual machine.
*
* <p> A {@code VirtualMachine} represents a Java virtual machine to which this
* Java virtual machine has attached. The Java virtual machine to which it is
* attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>.
* An application (typically a tool such as a managemet console or profiler) uses a
* VirtualMachine to load an agent into the target VM. For example, a profiler tool
* written in the Java Language might attach to a running application and load its
* profiler agent to profile the running application. </p>
*
* <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method
* with an identifier that identifies the target virtual machine. The identifier is
* implementation-dependent but is typically the process identifier (or pid) in
* environments where each Java virtual machine runs in its own operating system process.
* Alternatively, a {@code VirtualMachine} instance is obtained by invoking the
* {@link #attach(VirtualMachineDescriptor) attach} method with a {@link
* com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained
* from the list of virtual machine descriptors returned by the {@link #list list} method.
* Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent},
* {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath}
* methods are used to load agents into target virtual machine. The {@link
* #loadAgent loadAgent} method is used to load agents that are written in the Java
* Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See
* {@link java.lang.instrument} for a detailed description on how these agents
* are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and
* {@link #loadAgentPath loadAgentPath} methods are used to load agents that
* are deployed either in a dynamic library or statically linked into the VM and
* make use of the <a href="{@docRoot}/../specs/jvmti.html">JVM Tools Interface</a>.
* </p>
*
* <p> In addition to loading agents a VirtualMachine provides read access to the
* {@link java.lang.System#getProperties() system properties} in the target VM.
* This can be useful in some environments where properties such as
* {@code java.home}, {@code os.name}, or {@code os.arch} are
* used to construct the path to agent that will be loaded into the target VM.
*
* <p> The following example demonstrates how VirtualMachine may be used:</p>
*
* <pre>
*
* // attach to target VM
* VirtualMachine vm = VirtualMachine.attach("2177");
*
* // start management agent
* Properties props = new Properties();
* props.put("com.sun.management.jmxremote.port", "5000");
* vm.startManagementAgent(props);
*
* // detach
* vm.detach();
*
* </pre>
*
* <p> In this example we attach to a Java virtual machine that is identified by
* the process identifier {@code 2177}. Then the JMX management agent is
* started in the target process using the supplied arguments. Finally, the
* client detaches from the target VM. </p>
*
* <p> A VirtualMachine is safe for use by multiple concurrent threads. </p>
*
* @since 1.6
*/
public abstract class VirtualMachine {
private AttachProvider provider;
private String id;
private volatile int hash; // 0 => not computed
/**
* Initializes a new instance of this class.
*
* @param provider
* The attach provider creating this class.
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @throws NullPointerException
* If {@code provider} or {@code id} is {@code null}.
*/
protected VirtualMachine(AttachProvider provider, String id) {
if (provider == null) {
throw new NullPointerException("provider cannot be null");
}
if (id == null) {
throw new NullPointerException("id cannot be null");
}
this.provider = provider;
this.id = id;
}
/**
* Return a list of Java virtual machines.
*
* <p> This method returns a list of Java {@link
* com.sun.tools.attach.VirtualMachineDescriptor} elements.
* The list is an aggregation of the virtual machine
* descriptor lists obtained by invoking the {@link
* com.sun.tools.attach.spi.AttachProvider#listVirtualMachines
* listVirtualMachines} method of all installed
* {@link com.sun.tools.attach.spi.AttachProvider attach providers}.
* If there are no Java virtual machines known to any provider
* then an empty list is returned.
*
* @return The list of virtual machine descriptors.
*/
public static List<VirtualMachineDescriptor> list() {
ArrayList<VirtualMachineDescriptor> l =
new ArrayList<VirtualMachineDescriptor>();
List<AttachProvider> providers = AttachProvider.providers();
for (AttachProvider provider: providers) {
l.addAll(provider.listVirtualMachines());
}
return l;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method obtains the list of attach providers by invoking the
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} method. It then iterates overs the list
* and invokes each provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String)
* attachVirtualMachine} method in turn. If a provider successfully
* attaches then the iteration terminates, and the VirtualMachine created
* by the provider that successfully attached is returned by this method.
* If the {@code attachVirtualMachine} method of all providers throws
* {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}
* then this method also throws {@code AttachNotSupportedException}.
* This means that {@code AttachNotSupportedException} is thrown when
* the identifier provided to this method is invalid, or the identifier
* corresponds to a Java virtual machine that does not exist, or none
* of the providers can attach to it. This exception is also thrown if
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} returns an empty list. </p>
*
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* {@code ("attachVirtualMachine")}, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the {@code attachVirtualmachine} method of all installed
* providers throws {@code AttachNotSupportedException}, or
* there aren't any providers installed.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code id} is {@code null}.
*/
public static VirtualMachine attach(String id)
throws AttachNotSupportedException, IOException
{
if (id == null) {
throw new NullPointerException("id cannot be null");
}
List<AttachProvider> providers = AttachProvider.providers();
if (providers.size() == 0) {
throw new AttachNotSupportedException("no providers installed");
}
AttachNotSupportedException lastExc = null;
for (AttachProvider provider: providers) {
try {
return provider.attachVirtualMachine(id);
} catch (AttachNotSupportedException x) {
lastExc = x;
}
}
throw lastExc;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method first invokes the {@link
* com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
* of the given virtual machine descriptor to obtain the attach provider. It
* then invokes the attach provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor)
* attachVirtualMachine} to attach to the target VM.
*
* @param vmd
* The virtual machine descriptor.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* {@code ("attachVirtualMachine")}, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the attach provider's {@code attachVirtualmachine}
* throws {@code AttachNotSupportedException}.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code vmd} is {@code null}.
*/
public static VirtualMachine attach(VirtualMachineDescriptor vmd)
throws AttachNotSupportedException, IOException
{
return vmd.provider().attachVirtualMachine(vmd);
}
/**
* Detach from the virtual machine.
*
* <p> After detaching from the virtual machine, any further attempt to invoke
* operations on that virtual machine will cause an {@link java.io.IOException
* IOException} to be thrown. If an operation (such as {@link #loadAgent
* loadAgent} for example) is in progress when this method is invoked then
* the behaviour is implementation dependent. In other words, it is
* implementation specific if the operation completes or throws
* {@code IOException}.
*
* <p> If already detached from the virtual machine then invoking this
* method has no effect. </p>
*
* @throws IOException
* If an I/O error occurs
*/
public abstract void detach() throws IOException;
/**
* Returns the provider that created this virtual machine.
*
* @return The provider that created this virtual machine.
*/
public final AttachProvider provider() {
return provider;
}
/**
* Returns the identifier for this Java virtual machine.
*
* @return The identifier for this Java virtual machine.
*/
public final String id() {
return id;
}
/**
* Loads an agent library.
*
* <p> A <a href="{@docRoot}/../specs/jvmti.html">JVM TI</a>
* client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, it may be statically linked into the VM.
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the {@code Agent_OnAttach} function
* or, for a statically linked agent named 'L', the {@code Agent_OnAttach_L} function
* as specified in the
* <a href="{@docRoot}/../specs/jvmti.html">JVM Tools Interface</a> specification.
* Note that the {@code Agent_OnAttach[_L]}
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the name of the agent library. It is interpreted
* in the target virtual machine in an implementation-dependent manner. Typically an
* implementation will expand the library name into an operating system specific file
* name. For example, on UNIX systems, the name {@code L} might be expanded to
* {@code libL.so}, and located using the search path specified by the
* {@code LD_LIBRARY_PATH} environment variable. If the agent named 'L' is
* statically linked into the VM then the VM must export a function named
* {@code Agent_OnAttach_L}.</p>
*
* <p> If the {@code Agent_OnAttach[_L]} function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the {@code Agent_OnAttach[_L]} can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentLibrary
* The name of the agent library.
*
* @param options
* The options to provide to the {@code Agent_OnAttach[_L]}
* function (can be {@code null}).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the {@code Agent_OnAttach[_L]} function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agentLibrary} is {@code null}.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentLibrary(String agentLibrary, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent library.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><code>
* {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary, null);
* </code></blockquote>
*
* @param agentLibrary
* The name of the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the {@code Agent_OnAttach[_L]} function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agentLibrary} is {@code null}.
*/
public void loadAgentLibrary(String agentLibrary)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentLibrary(agentLibrary, null);
}
/**
* Load a native agent library by full pathname.
*
* <p> A <a href="{@docRoot}/../specs/jvmti.html">JVM TI</a>
* client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, the native
* library specified by the agentPath parameter may be statically
* linked with the VM. The parsing of the agentPath parameter into
* a statically linked library name is done in a platform
* specific manner in the VM. For example, in UNIX, an agentPath parameter
* of {@code /a/b/libL.so} would name a library 'L'.
*
* See the JVM TI Specification for more details.
*
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the {@code Agent_OnAttach}
* function or, for a statically linked agent named 'L', the
* {@code Agent_OnAttach_L} function as specified in the
* <a href="{@docRoot}/../specs/jvmti.html">JVM Tools Interface</a> specification.
* Note that the {@code Agent_OnAttach[_L]}
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the absolute path from which to load the
* agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name
* is not expanded in the target virtual machine. </p>
*
* <p> If the {@code Agent_OnAttach[_L]} function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the {@code Agent_OnAttach[_L]} can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentPath
* The full path of the agent library.
*
* @param options
* The options to provide to the {@code Agent_OnAttach[_L]}
* function (can be {@code null}).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the {@code Agent_OnAttach[_L]} function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agentPath} is {@code null}.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentPath(String agentPath, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Load a native agent library by full pathname.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><code>
* {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary, null);
* </code></blockquote>
*
* @param agentPath
* The full path to the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the {@code Agent_OnAttach[_L]} function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agentPath} is {@code null}.
*/
public void loadAgentPath(String agentPath)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentPath(agentPath, null);
}
/**
* Loads an agent.
*
* <p> The agent provided to this method is a path name to a JAR file on the file
* system of the target virtual machine. This path is passed to the target virtual
* machine where it is interpreted. The target virtual machine attempts to start
* the agent as specified by the {@link java.lang.instrument} specification.
* That is, the specified JAR file is added to the system class path (of the target
* virtual machine), and the {@code agentmain} method of the agent class, specified
* by the {@code Agent-Class} attribute in the JAR manifest, is invoked. This
* method completes when the {@code agentmain} method completes.
*
* @param agent
* Path to the JAR file containing the agent.
*
* @param options
* The options to provide to the agent's {@code agentmain}
* method (can be {@code null}).
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the {@code agentmain} throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agent} is {@code null}.
*/
public abstract void loadAgent(String agent, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><code>
* {@link #loadAgent(String, String) loadAgent}(agent, null);
* </code></blockquote>
*
* @param agent
* Path to the JAR file containing the agent.
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the {@code agentmain} throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If {@code agent} is {@code null}.
*/
public void loadAgent(String agent)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgent(agent, null);
}
/**
* Returns the current system properties in the target virtual machine.
*
* <p> This method returns the system properties in the target virtual
* machine. Properties whose key or value is not a {@code String} are
* omitted. The method is approximately equivalent to the invocation of the
* method {@link java.lang.System#getProperties System.getProperties}
* in the target virtual machine except that properties with a key or
* value that is not a {@code String} are not included.
*
* <p> This method is typically used to decide which agent to load into
* the target virtual machine with {@link #loadAgent loadAgent}, or
* {@link #loadAgentLibrary loadAgentLibrary}. For example, the
* {@code java.home} or {@code user.dir} properties might be
* use to create the path to the agent library or JAR file.
*
* @return The system properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @see java.lang.System#getProperties
* @see #loadAgentLibrary
* @see #loadAgent
*/
public abstract Properties getSystemProperties() throws IOException;
/**
* Returns the current <i>agent properties</i> in the target virtual
* machine.
*
* <p> The target virtual machine can maintain a list of properties on
* behalf of agents. The manner in which this is done, the names of the
* properties, and the types of values that are allowed, is implementation
* specific. Agent properties are typically used to store communication
* end-points and other agent configuration details. For example, a debugger
* agent might create an agent property for its transport address.
*
* <p> This method returns the agent properties whose key and value is a
* {@code String}. Properties whose key or value is not a {@code String}
* are omitted. If there are no agent properties maintained in the target
* virtual machine then an empty property list is returned.
*
* @return The agent properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*/
public abstract Properties getAgentProperties() throws IOException;
/**
* Starts the JMX management agent in the target virtual machine.
*
* <p> The configuration properties are the same as those specified on
* the command line when starting the JMX management agent. In the same
* way as on the command line, you need to specify at least the
* {@code com.sun.management.jmxremote.port} property.
*
* <p> See the online documentation for
* {@extLink monitoring_and_management_using_jmx_technology
* Monitoring and Management Using JMX Technology} for further details.
*
* @param agentProperties
* A Properties object containing the configuration properties
* for the agent.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @throws IllegalArgumentException
* If keys or values in agentProperties are invalid.
*
* @throws NullPointerException
* If agentProperties is null.
*
* @since 1.8
*/
public abstract void startManagementAgent(Properties agentProperties) throws IOException;
/**
* Starts the local JMX management agent in the target virtual machine.
*
* <p> See the online documentation for
* {@extLink monitoring_and_management_using_jmx_technology
* Monitoring and Management Using JMX Technology} for further details.
*
* @return The String representation of the local connector's service address.
* The value can be parsed by the
* {@link javax.management.remote.JMXServiceURL#JMXServiceURL(String)}
* constructor.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @since 1.8
*/
public abstract String startLocalManagementAgent() throws IOException;
/**
* Returns a hash-code value for this VirtualMachine. The hash
* code is based upon the VirtualMachine's components, and satisfies
* the general contract of the {@link java.lang.Object#hashCode()
* Object.hashCode} method.
*
* @return A hash-code value for this virtual machine
*/
public int hashCode() {
if (hash != 0) {
return hash;
}
hash = provider.hashCode() * 127 + id.hashCode();
return hash;
}
/**
* Tests this VirtualMachine for equality with another object.
*
* <p> If the given object is not a VirtualMachine then this
* method returns {@code false}. For two VirtualMachines to
* be considered equal requires that they both reference the same
* provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p>
*
* <p> This method satisfies the general contract of the {@link
* java.lang.Object#equals(Object) Object.equals} method. </p>
*
* @param ob The object to which this object is to be compared
*
* @return {@code true} if, and only if, the given object is
* a VirtualMachine that is equal to this
* VirtualMachine.
*/
public boolean equals(Object ob) {
if (ob == this)
return true;
if (!(ob instanceof VirtualMachine))
return false;
VirtualMachine other = (VirtualMachine)ob;
if (other.provider() != this.provider()) {
return false;
}
if (!other.id().equals(this.id())) {
return false;
}
return true;
}
/**
* Returns the string representation of the {@code VirtualMachine}.
*/
public String toString() {
return provider.toString() + ": " + id;
}
}
| openjdk/jdk | src/jdk.attach/share/classes/com/sun/tools/attach/VirtualMachine.java |
45,321 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/12/14 Support for extension dependencies
// ZAP: 2012/02/18 Rationalised session handling
// ZAP: 2012/03/15 Reflected the change in the name of the method optionsChanged of
// the class OptionsChangedListener. Changed the method destroyAllExtension() to
// save the configurations of the main http panels and save the configuration file.
// ZAP: 2012/04/23 Reverted the changes of the method destroyAllExtension(),
// now the configurations of the main http panels and the configuration file
// are saved in the method Control.shutdown(boolean).
// ZAP: 2012/04/24 Changed the method destroyAllExtension to catch exceptions.
// ZAP: 2012/04/25 Added the type argument and removed unnecessary cast.
// ZAP: 2012/07/23 Removed parameter from View.getSessionDialog call.
// ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event
// ZAP: 2012/08/01 Issue 332: added support for Modes
// ZAP: 2012/11/30 Issue 425: Added tab index to support quick start tab
// ZAP: 2012/12/27 Added hookPersistentConnectionListener() method.
// ZAP: 2013/01/16 Issue 453: Dynamic loading and unloading of add-ons
// ZAP: 2013/01/25 Added removeExtension(...) method and further helper methods
// to remove listeners, menu items, etc.
// ZAP: 2013/01/25 Refactored hookMenu(). Resolved some Checkstyle issues.
// ZAP: 2013/01/29 Catch Errors thrown by out of date extensions as well as Exceptions
// ZAP: 2013/07/23 Issue 738: Options to hide tabs
// ZAP: 2013/11/16 Issue 807: Error while loading ZAP when Quick Start Tab is closed
// ZAP: 2013/11/16 Issue 845: AbstractPanel added twice to TabbedPanel2 in
// ExtensionLoader#addTabPanel
// ZAP: 2013/12/03 Issue 934: Handle files on the command line via extension
// ZAP: 2013/12/13 Added support for Full Layout DISPLAY_OPTION_TOP_FULL in the hookView function.
// ZAP: 2014/03/23 Issue 1022: Proxy - Allow to override a proxied message
// ZAP: 2014/03/23 Issue 1090: Do not add pop up menus if target extension is not enabled
// ZAP: 2014/05/20 Issue 1202: Issue with loading addons that did not initialize correctly
// ZAP: 2014/08/14 Catch Exceptions thrown by extensions when stopping them
// ZAP: 2014/08/14 Issue 1309: NullPointerExceptions during a failed uninstallation of an add-on
// ZAP: 2014/10/07 Issue 1357: Hide unused tabs
// ZAP: 2014/10/09 Issue 1359: Added info logging for splash screen
// ZAP: 2014/10/25 Issue 1062: Added scannerhook to be loaded by an active scanner.
// ZAP: 2014/11/11 Issue 1406: Move online menu items to an add-on
// ZAP: 2014/11/21 Reviewed foreach loops and commented startup process for splash screen progress
// bar
// ZAP: 2015/01/04 Issue 1379: Not all extension's listeners are hooked during add-on installation
// ZAP: 2015/01/19 Remove online menus when removeMenu(View, ExtensionHook) is called.
// ZAP: 2015/01/19 Issue 1510: New Extension.postInit() method to be called once all extensions
// loaded
// ZAP: 2015/02/09 Issue 1525: Introduce a database interface layer to allow for alternative
// implementations
// ZAP: 2015/02/10 Issue 1208: Search classes/resources in add-ons declared as dependencies
// ZAP: 2015/04/09 Generify Extension.getExtension(Class) to avoid unnecessary casts
// ZAP: 2015/09/07 Start GUI on EDT
// ZAP: 2016/04/06 Fix layouts' issues
// ZAP: 2016/04/08 Hook ContextDataFactory/ContextPanelFactory
// ZAP: 2016/05/30 Notification of installation status of the add-ons
// ZAP: 2016/05/30 Issue 2494: ZAP Proxy is not showing the HTTP CONNECT Request in history tab
// ZAP: 2016/08/18 Hook ApiImplementor
// ZAP: 2016/11/23 Call postInit() when starting an extension, startLifeCycle(Extension).
// ZAP: 2017/02/19 Hook/remove extensions' components to/from the main tool bar.
// ZAP: 2017/06/07 Allow to notify of changes in the session's properties (e.g. name, description).
// ZAP: 2017/07/25 Hook HttpSenderListener.
// ZAP: 2017/10/11 Include add-on in extensions' initialisation errors.
// ZAP: 2017/10/31 Add JavaDoc to ExtensionLoader.getExtension(String).
// ZAP: 2018/04/25 Allow to add ProxyServer to automatically add/remove proxy related listeners to
// it.
// ZAP: 2018/07/18 Tweak logging.
// ZAP: 2018/10/05 Get menu/view hooks without initialising them.
// ZAP: 2018/10/09 Use managed ExtensionHook when removing extensions.
// ZAP: 2019/03/15 Issue 3578: Added Helper options for Import menu
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/07/25 Relocate null check to be earlier in hookScannerHook(scan) [LGTM issue].
// ZAP: 2019/08/19 Validate menu and main frame in EDT.
// ZAP: 2019/09/30 Use instance variable for view checks.
// ZAP: 2020/05/14 Hook HttpSenderListener when starting single extension.
// ZAP: 2020/08/27 Added support for plugable variants
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/04/13 Issue 6536: Stop and destroy extensions being removed.
// ZAP: 2021/08/17 Issue 6755: Extension's errors during shutdown prevent ZAP to exit.
// ZAP: 2021/10/01 Do not initialise view if there's none when starting a single extension.
// ZAP: 2022/02/09 Deprecate code related to core proxy, remove code no longer needed.
// ZAP: 2022/04/17 Log extension name prior to description when loading.
// ZAP: 2022/04/17 Address various SAST (SonarLint) issues.
// ZAP: 2022/06/13 Hook HrefTypeInfo.
// ZAP: 2022/08/17 Install updates before running other cmdline args.
// ZAP: 2022/11/23 Refresh tabs menu when tabs are removed.
// ZAP: 2023/01/10 Tidy up logger.
// ZAP: 2023/04/28 Deprecate Proxy and ProxyServer related methods.
// ZAP: 2023/08/25 Set view to ExtensionAdaptor.
// ZAP: 2023/11/14 Hook AbstractParamPanel with parents.
package org.parosproxy.paros.extension;
import java.awt.Component;
import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.CommandLine;
import org.parosproxy.paros.common.AbstractParam;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.core.proxy.ConnectRequestProxyListener;
import org.parosproxy.paros.core.proxy.OverrideMessageProxyListener;
import org.parosproxy.paros.core.proxy.ProxyListener;
import org.parosproxy.paros.core.scanner.Scanner;
import org.parosproxy.paros.core.scanner.ScannerHook;
import org.parosproxy.paros.core.scanner.Variant;
import org.parosproxy.paros.db.Database;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.db.DatabaseUnsupportedException;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.OptionsParam;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.network.HttpSender;
import org.parosproxy.paros.view.AbstractParamDialog;
import org.parosproxy.paros.view.AbstractParamPanel;
import org.parosproxy.paros.view.MainMenuBar;
import org.parosproxy.paros.view.SiteMapPanel;
import org.parosproxy.paros.view.View;
import org.parosproxy.paros.view.WorkbenchPanel;
import org.zaproxy.zap.PersistentConnectionListener;
import org.zaproxy.zap.control.AddOn;
import org.zaproxy.zap.extension.AddOnInstallationStatusListener;
import org.zaproxy.zap.extension.AddonFilesChangedListener;
import org.zaproxy.zap.extension.api.API;
import org.zaproxy.zap.extension.api.ApiImplementor;
import org.zaproxy.zap.extension.httppanel.DisplayedMessageChangedListener;
import org.zaproxy.zap.model.ContextDataFactory;
import org.zaproxy.zap.network.HttpSenderListener;
import org.zaproxy.zap.view.ContextPanelFactory;
import org.zaproxy.zap.view.HrefTypeInfo;
import org.zaproxy.zap.view.MainToolbarPanel;
import org.zaproxy.zap.view.SiteMapListener;
public class ExtensionLoader {
private final List<Extension> extensionList = new ArrayList<>();
private final Map<Class<? extends Extension>, Extension> extensionsMap = new HashMap<>();
private final Map<Extension, ExtensionHook> extensionHooks = new HashMap<>();
private Model model = null;
private View view = null;
private CommandLine cmdLine;
private static final Logger LOGGER = LogManager.getLogger(ExtensionLoader.class);
@SuppressWarnings("deprecation")
private List<org.parosproxy.paros.core.proxy.ProxyServer> proxyServers;
public ExtensionLoader(Model model, View view) {
this.model = model;
this.view = view;
this.proxyServers = new ArrayList<>();
}
public void addExtension(Extension extension) {
extensionList.add(extension);
extensionsMap.put(extension.getClass(), extension);
}
public void destroyAllExtension() {
for (int i = 0; i < getExtensionCount(); i++) {
try {
getExtension(i).destroy();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
public Extension getExtension(int i) {
return extensionList.get(i);
}
/**
* Gets the {@code Extension} with the given name.
*
* @param name the name of the {@code Extension}.
* @return the {@code Extension} or {@code null} if not found/enabled.
* @see #getExtension(Class)
*/
public Extension getExtension(String name) {
if (name != null) {
for (int i = 0; i < extensionList.size(); i++) {
Extension p = getExtension(i);
if (p.getName().equalsIgnoreCase(name)) {
return p;
}
}
}
return null;
}
public Extension getExtensionByClassName(String name) {
if (name != null) {
for (int i = 0; i < extensionList.size(); i++) {
Extension p = getExtension(i);
if (p.getClass().getName().equals(name)) {
return p;
}
}
}
return null;
}
/**
* Gets the {@code Extension} with the given class.
*
* @param clazz the class of the {@code Extension}
* @return the {@code Extension} or {@code null} if not found/enabled.
*/
public <T extends Extension> T getExtension(Class<T> clazz) {
if (clazz != null) {
Extension extension = extensionsMap.get(clazz);
if (extension != null) {
return clazz.cast(extension);
}
}
return null;
}
/**
* Tells whether or not an {@code Extension} with the given {@code extensionName} is enabled.
*
* @param extensionName the name of the extension
* @return {@code true} if the extension is enabled, {@code false} otherwise.
* @throws IllegalArgumentException if the {@code extensionName} is {@code null}.
* @see #getExtension(String)
* @see Extension
*/
public boolean isExtensionEnabled(String extensionName) {
if (extensionName == null) {
throw new IllegalArgumentException("Parameter extensionName must not be null.");
}
Extension extension = getExtension(extensionName);
if (extension == null) {
return false;
}
return extension.isEnabled();
}
public int getExtensionCount() {
return extensionList.size();
}
/**
* Adds the given proxy server, to be automatically updated with proxy related listeners.
*
* @param proxyServer the proxy server to add, must not be null.
* @since 2.8.0
* @see #removeProxyServer(org.parosproxy.paros.core.proxy.ProxyServer)
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void addProxyServer(org.parosproxy.paros.core.proxy.ProxyServer proxyServer) {
proxyServers.add(proxyServer);
extensionHooks.values().forEach(extHook -> hookProxyServer(extHook, proxyServer));
}
@SuppressWarnings("deprecation")
private static void hookProxyServer(
ExtensionHook extHook, org.parosproxy.paros.core.proxy.ProxyServer proxyServer) {
process(extHook.getProxyListenerList(), proxyServer::addProxyListener);
process(
extHook.getOverrideMessageProxyListenerList(),
proxyServer::addOverrideMessageProxyListener);
process(
extHook.getPersistentConnectionListener(),
proxyServer::addPersistentConnectionListener);
process(
extHook.getConnectRequestProxyListeners(),
proxyServer::addConnectRequestProxyListener);
}
private static <T> void process(List<T> elements, Consumer<T> action) {
try {
elements.stream().filter(Objects::nonNull).forEach(action);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
@SuppressWarnings("deprecation")
private void hookProxies(ExtensionHook extHook) {
for (org.parosproxy.paros.core.proxy.ProxyServer proxyServer : proxyServers) {
hookProxyServer(extHook, proxyServer);
}
}
/**
* Removes the given proxy server.
*
* @param proxyServer the proxy server to remove, must not be null.
* @since 2.8.0
* @see #addProxyServer(org.parosproxy.paros.core.proxy.ProxyServer)
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void removeProxyServer(org.parosproxy.paros.core.proxy.ProxyServer proxyServer) {
proxyServers.remove(proxyServer);
extensionHooks.values().forEach(extHook -> unhookProxyServer(extHook, proxyServer));
}
@SuppressWarnings("deprecation")
private void unhookProxyServer(
ExtensionHook extHook, org.parosproxy.paros.core.proxy.ProxyServer proxyServer) {
process(extHook.getProxyListenerList(), proxyServer::removeProxyListener);
process(
extHook.getOverrideMessageProxyListenerList(),
proxyServer::removeOverrideMessageProxyListener);
process(
extHook.getPersistentConnectionListener(),
proxyServer::removePersistentConnectionListener);
process(
extHook.getConnectRequestProxyListeners(),
proxyServer::removeConnectRequestProxyListener);
}
@SuppressWarnings("deprecation")
private void unhookProxies(ExtensionHook extHook) {
for (org.parosproxy.paros.core.proxy.ProxyServer proxyServer : proxyServers) {
unhookProxyServer(extHook, proxyServer);
}
}
/**
* @param proxy the proxy to hook.
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void hookProxyListener(org.parosproxy.paros.control.Proxy proxy) {
for (ExtensionHook hook : extensionHooks.values()) {
hookProxyListeners(proxy, hook.getProxyListenerList());
}
}
@SuppressWarnings("deprecation")
private static void hookProxyListeners(
org.parosproxy.paros.control.Proxy proxy, List<ProxyListener> listeners) {
for (ProxyListener listener : listeners) {
try {
if (listener != null) {
proxy.addProxyListener(listener);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
/**
* @param proxy the proxy to hook.
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void hookOverrideMessageProxyListener(org.parosproxy.paros.control.Proxy proxy) {
for (ExtensionHook hook : extensionHooks.values()) {
hookOverrideMessageProxyListeners(proxy, hook.getOverrideMessageProxyListenerList());
}
}
@SuppressWarnings("deprecation")
private static void hookOverrideMessageProxyListeners(
org.parosproxy.paros.control.Proxy proxy,
List<OverrideMessageProxyListener> listeners) {
for (OverrideMessageProxyListener listener : listeners) {
try {
if (listener != null) {
proxy.addOverrideMessageProxyListener(listener);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
/**
* Hooks (adds) the {@code ConnectRequestProxyListener}s of the loaded extensions to the given
* {@code proxy}.
*
* <p><strong>Note:</strong> even if public this method is expected to be called only by core
* classes (for example, {@code Control}).
*
* @param proxy the local proxy
* @since 2.5.0
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void hookConnectRequestProxyListeners(org.parosproxy.paros.control.Proxy proxy) {
for (ExtensionHook hook : extensionHooks.values()) {
hookConnectRequestProxyListeners(proxy, hook.getConnectRequestProxyListeners());
}
}
@SuppressWarnings("deprecation")
private static void hookConnectRequestProxyListeners(
org.parosproxy.paros.control.Proxy proxy, List<ConnectRequestProxyListener> listeners) {
for (ConnectRequestProxyListener listener : listeners) {
proxy.addConnectRequestProxyListener(listener);
}
}
/**
* @param proxy the proxy to hook.
* @deprecated (2.13.0) Use the network add-on to create proxies.
*/
@Deprecated(since = "2.13.0", forRemoval = true)
public void hookPersistentConnectionListener(org.parosproxy.paros.control.Proxy proxy) {
for (ExtensionHook hook : extensionHooks.values()) {
hookPersistentConnectionListeners(proxy, hook.getPersistentConnectionListener());
}
}
@SuppressWarnings("deprecation")
private static void hookPersistentConnectionListeners(
org.parosproxy.paros.control.Proxy proxy,
List<PersistentConnectionListener> listeners) {
for (PersistentConnectionListener listener : listeners) {
try {
if (listener != null) {
proxy.addPersistentConnectionListener(listener);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
// ZAP: Added support for site map listeners
public void hookSiteMapListener(SiteMapPanel siteMapPanel) {
for (ExtensionHook hook : extensionHooks.values()) {
hookSiteMapListeners(siteMapPanel, hook.getSiteMapListenerList());
}
}
private static void hookSiteMapListeners(
SiteMapPanel siteMapPanel, List<SiteMapListener> listeners) {
for (SiteMapListener listener : listeners) {
try {
if (listener != null) {
siteMapPanel.addSiteMapListener(listener);
}
} catch (Exception e) {
// ZAP: Log the exception
LOGGER.error(e.getMessage(), e);
}
}
}
private void removeSiteMapListener(ExtensionHook hook) {
if (!hasView()) {
return;
}
SiteMapPanel siteMapPanel = view.getSiteTreePanel();
List<SiteMapListener> listenerList = hook.getSiteMapListenerList();
for (SiteMapListener listener : listenerList) {
try {
if (listener != null) {
siteMapPanel.removeSiteMapListener(listener);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
private boolean hasView() {
return view != null;
}
// ZAP: method called by the scanner to load all scanner hooks.
public void hookScannerHook(Scanner scan) {
Iterator<ExtensionHook> iter = extensionHooks.values().iterator();
while (iter.hasNext()) {
ExtensionHook hook = iter.next();
if (hook == null) {
continue;
}
List<ScannerHook> scannerHookList = hook.getScannerHookList();
for (ScannerHook scannerHook : scannerHookList) {
try {
scan.addScannerHook(scannerHook);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void optionsChangedAllPlugin(OptionsParam options) {
for (ExtensionHook hook : extensionHooks.values()) {
List<OptionsChangedListener> listenerList = hook.getOptionsChangedListenerList();
for (OptionsChangedListener listener : listenerList) {
try {
if (listener != null) {
listener.optionsChanged(options);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void runCommandLine() {
Extension ext;
for (int i = 0; i < getExtensionCount(); i++) {
ext = getExtension(i);
if (ext instanceof CommandLineListener) {
CommandLineListener listener = (CommandLineListener) ext;
listener.preExecute(extensionHooks.get(ext).getCommandLineArgument());
}
}
for (int i = 0; i < getExtensionCount(); i++) {
ext = getExtension(i);
if (ext instanceof CommandLineListener) {
CommandLineListener listener = (CommandLineListener) ext;
listener.execute(extensionHooks.get(ext).getCommandLineArgument());
}
}
}
public void sessionChangedAllPlugin(Session session) {
LOGGER.debug("sessionChangedAllPlugin");
for (ExtensionHook hook : extensionHooks.values()) {
List<SessionChangedListener> listenerList = hook.getSessionListenerList();
for (SessionChangedListener listener : listenerList) {
try {
if (listener != null) {
listener.sessionChanged(session);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void databaseOpen(Database db) {
Extension ext;
for (int i = 0; i < getExtensionCount(); i++) {
ext = getExtension(i);
try {
ext.databaseOpen(db);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
public void sessionAboutToChangeAllPlugin(Session session) {
LOGGER.debug("sessionAboutToChangeAllPlugin");
for (ExtensionHook hook : extensionHooks.values()) {
List<SessionChangedListener> listenerList = hook.getSessionListenerList();
for (SessionChangedListener listener : listenerList) {
try {
if (listener != null) {
listener.sessionAboutToChange(session);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void sessionScopeChangedAllPlugin(Session session) {
LOGGER.debug("sessionScopeChangedAllPlugin");
for (ExtensionHook hook : extensionHooks.values()) {
List<SessionChangedListener> listenerList = hook.getSessionListenerList();
for (SessionChangedListener listener : listenerList) {
try {
if (listener != null) {
listener.sessionScopeChanged(session);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void sessionModeChangedAllPlugin(Mode mode) {
LOGGER.debug("sessionModeChangedAllPlugin");
for (ExtensionHook hook : extensionHooks.values()) {
List<SessionChangedListener> listenerList = hook.getSessionListenerList();
for (SessionChangedListener listener : listenerList) {
try {
if (listener != null) {
listener.sessionModeChanged(mode);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
/**
* Notifies that the properties (e.g. name, description) of the current session were changed.
*
* <p>Should be called only by "core" classes.
*
* @param session the session changed.
* @since 2.7.0
*/
public void sessionPropertiesChangedAllPlugin(Session session) {
LOGGER.debug("sessionPropertiesChangedAllPlugin");
for (ExtensionHook hook : extensionHooks.values()) {
for (SessionChangedListener listener : hook.getSessionListenerList()) {
try {
if (listener != null) {
listener.sessionPropertiesChanged(session);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void addonFilesAdded() {
for (ExtensionHook hook : extensionHooks.values()) {
List<AddonFilesChangedListener> listenerList = hook.getAddonFilesChangedListener();
for (AddonFilesChangedListener listener : listenerList) {
try {
listener.filesAdded();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
public void addonFilesRemoved() {
for (ExtensionHook hook : extensionHooks.values()) {
List<AddonFilesChangedListener> listenerList = hook.getAddonFilesChangedListener();
for (AddonFilesChangedListener listener : listenerList) {
try {
listener.filesRemoved();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
/**
* Notifies of an add-on's installation status update.
*
* @param statusUpdate the status update, must not be {@code null}.
* @since 2.15.0
*/
public void addOnStatusUpdate(AddOnInstallationStatusListener.StatusUpdate statusUpdate) {
for (ExtensionHook hook : extensionHooks.values()) {
for (AddOnInstallationStatusListener listener :
hook.getAddOnInstallationStatusListeners()) {
try {
listener.update(statusUpdate);
} catch (Exception e) {
LOGGER.error(
"An error occurred while notifying: {}",
listener.getClass().getCanonicalName(),
e);
}
}
}
}
/**
* Notifies {@code Extension}s' {@code AddOnInstallationStatusListener}s that the given add-on
* was installed.
*
* @param addOn the add-on that was installed, must not be {@code null}
* @since 2.5.0
* @deprecated (2.15.0) Replaced by {@link
* #addOnStatusUpdate(org.zaproxy.zap.extension.AddOnInstallationStatusListener.StatusUpdate)}.
*/
@SuppressWarnings("removal")
@Deprecated(since = "2.15.0", forRemoval = true)
public void addOnInstalled(AddOn addOn) {
for (ExtensionHook hook : extensionHooks.values()) {
for (AddOnInstallationStatusListener listener :
hook.getAddOnInstallationStatusListeners()) {
try {
listener.addOnInstalled(addOn);
} catch (Exception e) {
LOGGER.error(
"An error occurred while notifying: {}",
listener.getClass().getCanonicalName(),
e);
}
}
}
}
/**
* Notifies {@code Extension}s' {@code AddOnInstallationStatusListener}s that the given add-on
* was soft uninstalled.
*
* @param addOn the add-on that was soft uninstalled, must not be {@code null}
* @param successfully if the soft uninstallation was successful, that is, no errors occurred
* while uninstalling it
* @since 2.5.0
* @deprecated (2.15.0) Replaced by {@link
* #addOnStatusUpdate(org.zaproxy.zap.extension.AddOnInstallationStatusListener.StatusUpdate)}.
*/
@SuppressWarnings("removal")
@Deprecated(since = "2.15.0", forRemoval = true)
public void addOnSoftUninstalled(AddOn addOn, boolean successfully) {
for (ExtensionHook hook : extensionHooks.values()) {
for (AddOnInstallationStatusListener listener :
hook.getAddOnInstallationStatusListeners()) {
try {
listener.addOnSoftUninstalled(addOn, successfully);
} catch (Exception e) {
LOGGER.error(
"An error occurred while notifying: {}",
listener.getClass().getCanonicalName(),
e);
}
}
}
}
/**
* Notifies {@code Extension}s' {@code AddOnInstallationStatusListener}s that the given add-on
* was uninstalled.
*
* @param addOn the add-on that was uninstalled, must not be {@code null}
* @param successfully if the uninstallation was successful, that is, no errors occurred while
* uninstalling it
* @since 2.5.0
* @deprecated (2.15.0) Replaced by {@link
* #addOnStatusUpdate(org.zaproxy.zap.extension.AddOnInstallationStatusListener.StatusUpdate)}.
*/
@SuppressWarnings("removal")
@Deprecated(since = "2.15.0", forRemoval = true)
public void addOnUninstalled(AddOn addOn, boolean successfully) {
for (ExtensionHook hook : extensionHooks.values()) {
for (AddOnInstallationStatusListener listener :
hook.getAddOnInstallationStatusListeners()) {
try {
listener.addOnUninstalled(addOn, successfully);
} catch (Exception e) {
LOGGER.error(
"An error occurred while notifying: {}",
listener.getClass().getCanonicalName(),
e);
}
}
}
}
public void startAllExtension(double progressFactor) {
double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
Extension extension = getExtension(i);
try {
extension.start();
if (hasView()) {
view.addSplashScreenLoadingCompletion(factorPerc);
}
} catch (Exception e) {
logExtensionInitError(extension, e);
}
}
}
/**
* Initialize and start all Extensions This function loops for all getExtensionCount() exts
* launching each specific initialization element (model, xml, view, hook, etc.)
*/
public void startLifeCycle() {
// Percentages are passed into the calls as doubles
if (hasView()) {
view.setSplashScreenLoadingCompletion(0.0);
}
// Step 3: initialize all (slow)
initAllExtension(5.0);
// Step 4: initialize models (quick)
initModelAllExtension(model, 0.0);
// Step 5: initialize xmls (quick)
initXMLAllExtension(model.getSession(), model.getOptionsParam(), 0.0);
// Step 6: initialize viewes (slow)
initViewAllExtension(view, 10.0);
// Step 7: initialize hooks (slowest)
hookAllExtension(75.0);
// Step 8: start all extensions(quick)
startAllExtension(10.0);
// Clear so that manually updated add-ons dont get called with cmdline args again
this.cmdLine = null;
}
/**
* Initialize a specific Extension
*
* @param ext the Extension that need to be initialized
* @throws DatabaseUnsupportedException
* @throws DatabaseException
*/
public void startLifeCycle(Extension ext)
throws DatabaseException, DatabaseUnsupportedException {
setExtensionAdaptorView(ext);
ext.init();
ext.databaseOpen(model.getDb());
ext.initModel(model);
ext.initXML(model.getSession(), model.getOptionsParam());
if (hasView()) {
ext.initView(view);
}
ExtensionHook extHook = new ExtensionHook(model, view);
extensionHooks.put(ext, extHook);
try {
ext.hook(extHook);
if (cmdLine != null) {
// This extension has been added or updated via the commandline args, so
// re-apply any args
CommandLineArgument[] arg = extHook.getCommandLineArgument();
if (arg.length > 0 && ext instanceof CommandLineListener) {
List<CommandLineArgument[]> allCommandLineList = new ArrayList<>();
Map<String, CommandLineListener> extMap = new HashMap<>();
allCommandLineList.add(arg);
CommandLineListener cli = (CommandLineListener) ext;
List<String> extensions = cli.getHandledExtensions();
if (extensions != null) {
for (String extension : extensions) {
extMap.put(extension, cli);
}
}
cmdLine.resetArgs();
cmdLine.parse(allCommandLineList, extMap, false);
}
}
hookContextDataFactories(ext, extHook);
hookApiImplementors(ext, extHook);
hookHttpSenderListeners(ext, extHook);
hookVariant(ext, extHook);
hookHrefTypeInfo(ext, extHook);
if (hasView()) {
// no need to hook view if no GUI
hookView(ext, view, extHook);
hookMenu(view, extHook);
}
hookOptions(extHook);
hookProxies(extHook);
ext.optionsLoaded();
ext.postInit();
} catch (Exception e) {
logExtensionInitError(ext, e);
}
ext.start();
if (hasView()) {
hookSiteMapListeners(view.getSiteTreePanel(), extHook.getSiteMapListenerList());
}
}
private void setExtensionAdaptorView(Extension extension) {
if (hasView() && extension instanceof ExtensionAdaptor) {
((ExtensionAdaptor) extension).setView(view);
}
}
public void stopAllExtension() {
for (int i = 0; i < getExtensionCount(); i++) {
try {
getExtension(i).stop();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
// ZAP: Added the type argument.
private void addParamPanel(
List<ExtensionHookView.AbstractParamPanelEntry> panelList, AbstractParamDialog dialog) {
for (ExtensionHookView.AbstractParamPanelEntry entry : panelList) {
try {
dialog.addParamPanel(entry.getParents(), entry.getPanel(), true);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
private void removeParamPanel(
List<ExtensionHookView.AbstractParamPanelEntry> panelList, AbstractParamDialog dialog) {
for (ExtensionHookView.AbstractParamPanelEntry entry : panelList) {
try {
dialog.removeParamPanel(entry.getPanel());
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
dialog.revalidate();
}
private void hookAllExtension(double progressFactor) {
final double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
final Extension ext = getExtension(i);
try {
LOGGER.info("Initializing {} - {}", ext.getUIName(), ext.getDescription());
final ExtensionHook extHook = new ExtensionHook(model, view);
extensionHooks.put(ext, extHook);
ext.hook(extHook);
hookContextDataFactories(ext, extHook);
hookApiImplementors(ext, extHook);
hookHttpSenderListeners(ext, extHook);
hookVariant(ext, extHook);
hookHrefTypeInfo(ext, extHook);
if (hasView()) {
EventQueue.invokeAndWait(
() -> {
// no need to hook view if no GUI
hookView(ext, view, extHook);
hookMenu(view, extHook);
view.addSplashScreenLoadingCompletion(factorPerc);
});
}
hookOptions(extHook);
hookProxies(extHook);
ext.optionsLoaded();
} catch (Throwable e) {
// Catch Errors thrown by out of date extensions as well as Exceptions
logExtensionInitError(ext, e);
}
}
// Call postInit for all extensions after they have all been initialized
for (int i = 0; i < getExtensionCount(); i++) {
Extension extension = getExtension(i);
try {
extension.postInit();
} catch (Throwable e) {
// Catch Errors thrown by out of date extensions as well as Exceptions
logExtensionInitError(extension, e);
}
}
if (hasView()) {
try {
EventQueue.invokeAndWait(
() -> {
view.getMainFrame().getMainMenuBar().validate();
view.getMainFrame().validate();
});
} catch (InvocationTargetException | InterruptedException e) {
LOGGER.warn("An error occurred while updating the UI:", e);
}
}
}
private static void logExtensionInitError(Extension extension, Throwable e) {
StringBuilder strBuilder = new StringBuilder(150);
strBuilder.append("Failed to initialise extension ");
strBuilder.append(extension.getClass().getCanonicalName());
AddOn addOn = extension.getAddOn();
if (addOn != null) {
strBuilder.append(" (from add-on ").append(addOn).append(')');
}
strBuilder.append(", cause: ");
strBuilder.append(ExceptionUtils.getRootCauseMessage(e));
LOGGER.error(strBuilder, e);
}
private void hookContextDataFactories(Extension extension, ExtensionHook extHook) {
for (ContextDataFactory contextDataFactory : extHook.getContextDataFactories()) {
try {
model.addContextDataFactory(contextDataFactory);
} catch (Exception e) {
LOGGER.error(
"Error while adding a ContextDataFactory from {}",
extension.getClass().getCanonicalName(),
e);
}
}
}
private void hookApiImplementors(Extension extension, ExtensionHook extHook) {
for (ApiImplementor apiImplementor : extHook.getApiImplementors()) {
try {
API.getInstance().registerApiImplementor(apiImplementor);
} catch (Exception e) {
LOGGER.error(
"Error while adding an ApiImplementor from {}",
extension.getClass().getCanonicalName(),
e);
}
}
}
private void hookHttpSenderListeners(Extension extension, ExtensionHook extHook) {
for (HttpSenderListener httpSenderListener : extHook.getHttpSenderListeners()) {
try {
HttpSender.addListener(httpSenderListener);
} catch (Exception e) {
LOGGER.error(
"Error while adding an HttpSenderListener from {}",
extension.getClass().getCanonicalName(),
e);
}
}
}
private void hookVariant(Extension extension, ExtensionHook extHook) {
for (Class<? extends Variant> variant : extHook.getVariants()) {
try {
// Try to create a new instance just to check its possible
variant.getDeclaredConstructor().newInstance();
Model.getSingleton().getVariantFactory().addVariant(variant);
} catch (Exception e) {
LOGGER.error(
"Error while adding a Variant from {}",
extension.getClass().getCanonicalName(),
e);
}
}
}
private void hookHrefTypeInfo(Extension extension, ExtensionHook extHook) {
for (HrefTypeInfo hrefTypeInfo : extHook.getHrefsTypeInfo()) {
try {
HrefTypeInfo.addType(hrefTypeInfo);
} catch (Exception e) {
LOGGER.error(
"Error while adding a HrefTypeInfo from {}",
extension.getClass().getCanonicalName(),
e);
}
}
}
/**
* Hook command line listener with the command line processor
*
* @param cmdLine
* @throws java.lang.Exception
*/
public void hookCommandLineListener(CommandLine cmdLine) throws Exception {
// Save the CommandLine in case add-ons are added or replaced
this.cmdLine = cmdLine;
List<CommandLineArgument[]> allCommandLineList = new ArrayList<>();
Map<String, CommandLineListener> extMap = new HashMap<>();
for (Map.Entry<Extension, ExtensionHook> entry : extensionHooks.entrySet()) {
ExtensionHook hook = entry.getValue();
CommandLineArgument[] arg = hook.getCommandLineArgument();
if (arg.length > 0) {
allCommandLineList.add(arg);
}
Extension extension = entry.getKey();
if (extension instanceof CommandLineListener) {
CommandLineListener cli = (CommandLineListener) extension;
List<String> exts = cli.getHandledExtensions();
if (exts != null) {
for (String ext : exts) {
extMap.put(ext, cli);
}
}
}
}
cmdLine.parse(allCommandLineList, extMap);
}
private void hookMenu(View view, ExtensionHook hook) {
if (!hasView()) {
return;
}
ExtensionHookMenu hookMenu = hook.getHookMenuNoInit();
if (hookMenu == null) {
return;
}
MainMenuBar menuBar = view.getMainFrame().getMainMenuBar();
// 2 menus at the back (Tools/Help)
addMenuHelper(menuBar, hookMenu.getNewMenus(), 2);
addMenuHelper(menuBar.getMenuFile(), hookMenu.getFile(), 2);
addMenuHelper(menuBar.getMenuTools(), hookMenu.getTools(), 2);
addMenuHelper(menuBar.getMenuEdit(), hookMenu.getEdit());
addMenuHelper(menuBar.getMenuView(), hookMenu.getView());
addMenuHelper(menuBar.getMenuAnalyse(), hookMenu.getAnalyse());
addMenuHelper(menuBar.getMenuHelp(), hookMenu.getHelpMenus());
addMenuHelper(menuBar.getMenuReport(), hookMenu.getReportMenus());
addMenuHelper(menuBar.getMenuOnline(), hookMenu.getOnlineMenus());
addMenuHelper(menuBar.getMenuImport(), hookMenu.getImport());
addMenuHelper(view.getPopupList(), hookMenu.getPopupMenus());
}
private void addMenuHelper(JMenu menu, List<JMenuItem> items) {
addMenuHelper(menu, items, 0);
}
private void addMenuHelper(JMenuBar menuBar, List<JMenuItem> items, int existingCount) {
for (JMenuItem item : items) {
if (item != null) {
menuBar.add(item, menuBar.getMenuCount() - existingCount);
}
}
menuBar.revalidate();
}
private void addMenuHelper(JMenu menu, List<JMenuItem> items, int existingCount) {
for (JMenuItem item : items) {
if (item != null) {
if (item == ExtensionHookMenu.MENU_SEPARATOR) {
menu.addSeparator();
continue;
}
menu.add(item, menu.getItemCount() - existingCount);
}
}
menu.revalidate();
}
private void addMenuHelper(List<JMenuItem> menuList, List<JMenuItem> items) {
for (JMenuItem item : items) {
if (item != null) {
menuList.add(item);
}
}
}
private void removeMenu(View view, ExtensionHook hook) {
if (!hasView()) {
return;
}
ExtensionHookMenu hookMenu = hook.getHookMenuNoInit();
if (hookMenu == null) {
return;
}
MainMenuBar menuBar = view.getMainFrame().getMainMenuBar();
// clear up various menus
removeMenuHelper(menuBar, hookMenu.getNewMenus());
removeMenuHelper(menuBar.getMenuFile(), hookMenu.getFile());
removeMenuHelper(menuBar.getMenuTools(), hookMenu.getTools());
removeMenuHelper(menuBar.getMenuEdit(), hookMenu.getEdit());
removeMenuHelper(menuBar.getMenuView(), hookMenu.getView());
removeMenuHelper(menuBar.getMenuAnalyse(), hookMenu.getAnalyse());
removeMenuHelper(menuBar.getMenuHelp(), hookMenu.getHelpMenus());
removeMenuHelper(menuBar.getMenuReport(), hookMenu.getReportMenus());
removeMenuHelper(menuBar.getMenuOnline(), hookMenu.getOnlineMenus());
removeMenuHelper(menuBar.getMenuImport(), hookMenu.getImport());
removeMenuHelper(view.getPopupList(), hookMenu.getPopupMenus());
}
private void removeMenuHelper(JMenuBar menuBar, List<JMenuItem> items) {
for (JMenuItem item : items) {
if (item != null) {
menuBar.remove(item);
}
}
menuBar.revalidate();
}
private void removeMenuHelper(JMenu menu, List<JMenuItem> items) {
for (JMenuItem item : items) {
if (item != null) {
menu.remove(item);
}
}
menu.revalidate();
}
private void removeMenuHelper(List<JMenuItem> menuList, List<JMenuItem> items) {
for (JMenuItem item : items) {
if (item != null) {
menuList.remove(item);
}
}
}
private void hookOptions(ExtensionHook hook) {
List<AbstractParam> list = hook.getOptionsParamSetList();
for (AbstractParam paramSet : list) {
try {
model.getOptionsParam().addParamSet(paramSet);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
private void unloadOptions(ExtensionHook hook) {
List<AbstractParam> list = hook.getOptionsParamSetList();
for (AbstractParam paramSet : list) {
try {
model.getOptionsParam().removeParamSet(paramSet);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
private void hookView(Extension extension, View view, ExtensionHook hook) {
if (!hasView()) {
return;
}
ExtensionHookView pv = hook.getHookViewNoInit();
if (pv == null) {
return;
}
for (ContextPanelFactory contextPanelFactory : pv.getContextPanelFactories()) {
try {
view.addContextPanelFactory(contextPanelFactory);
} catch (Exception e) {
LOGGER.error(
"Error while adding a ContextPanelFactory from {}",
extension.getClass().getCanonicalName(),
e);
}
}
MainToolbarPanel mainToolBarPanel = view.getMainFrame().getMainToolbarPanel();
for (Component component : pv.getMainToolBarComponents()) {
try {
mainToolBarPanel.addToolBarComponent(component);
} catch (Exception e) {
LOGGER.error(
"Error while adding a component to the main tool bar panel, from {}",
extension.getClass().getCanonicalName(),
e);
}
}
view.getWorkbench().addPanels(pv.getSelectPanel(), WorkbenchPanel.PanelType.SELECT);
view.getWorkbench().addPanels(pv.getWorkPanel(), WorkbenchPanel.PanelType.WORK);
view.getWorkbench().addPanels(pv.getStatusPanel(), WorkbenchPanel.PanelType.STATUS);
addParamPanel(pv.getSessionPanel(), view.getSessionDialog());
addParamPanel(pv.getOptionsPanel(), view.getOptionsDialog(""));
for (DisplayedMessageChangedListener changedListener :
pv.getRequestPanelDisplayedMessageChangedListeners()) {
view.getRequestPanel().addDisplayedMessageChangedListener(changedListener);
}
for (DisplayedMessageChangedListener changedListener :
pv.getResponsePanelDisplayedMessageChangedListeners()) {
view.getResponsePanel().addDisplayedMessageChangedListener(changedListener);
}
}
private void removeView(Extension extension, View view, ExtensionHook hook) {
if (!hasView()) {
return;
}
ExtensionHookView pv = hook.getHookViewNoInit();
if (pv == null) {
return;
}
for (ContextPanelFactory contextPanelFactory : pv.getContextPanelFactories()) {
try {
view.removeContextPanelFactory(contextPanelFactory);
} catch (Exception e) {
LOGGER.error(
"Error while removing a ContextPanelFactory from {}",
extension.getClass().getCanonicalName(),
e);
}
}
MainToolbarPanel mainToolBarPanel = view.getMainFrame().getMainToolbarPanel();
for (Component component : pv.getMainToolBarComponents()) {
try {
mainToolBarPanel.removeToolBarComponent(component);
} catch (Exception e) {
LOGGER.error(
"Error while removing a component from the main tool bar panel, from {}",
extension.getClass().getCanonicalName(),
e);
}
}
view.getWorkbench().removePanels(pv.getSelectPanel(), WorkbenchPanel.PanelType.SELECT);
view.getWorkbench().removePanels(pv.getWorkPanel(), WorkbenchPanel.PanelType.WORK);
view.getWorkbench().removePanels(pv.getStatusPanel(), WorkbenchPanel.PanelType.STATUS);
if (!(pv.getSelectPanel().isEmpty()
&& pv.getWorkPanel().isEmpty()
&& pv.getStatusPanel().isEmpty())) {
view.refreshTabViewMenus();
}
removeParamPanel(pv.getSessionPanel(), view.getSessionDialog());
removeParamPanel(pv.getOptionsPanel(), view.getOptionsDialog(""));
for (DisplayedMessageChangedListener changedListener :
pv.getRequestPanelDisplayedMessageChangedListeners()) {
view.getRequestPanel().removeDisplayedMessageChangedListener(changedListener);
}
for (DisplayedMessageChangedListener changedListener :
pv.getResponsePanelDisplayedMessageChangedListeners()) {
view.getResponsePanel().removeDisplayedMessageChangedListener(changedListener);
}
}
public void removeStatusPanel(AbstractPanel panel) {
if (!hasView()) {
return;
}
view.getWorkbench().removePanel(panel, WorkbenchPanel.PanelType.STATUS);
}
public void removeOptionsPanel(AbstractParamPanel panel) {
if (!hasView()) {
return;
}
view.getOptionsDialog("").removeParamPanel(panel);
}
public void removeOptionsParamSet(AbstractParam params) {
model.getOptionsParam().removeParamSet(params);
}
public void removeWorkPanel(AbstractPanel panel) {
if (!hasView()) {
return;
}
view.getWorkbench().removePanel(panel, WorkbenchPanel.PanelType.WORK);
}
public void removePopupMenuItem(ExtensionPopupMenuItem popupMenuItem) {
if (!hasView()) {
return;
}
view.getPopupList().remove(popupMenuItem);
}
public void removeFileMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuFile().remove(menuItem);
}
public void removeEditMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuEdit().remove(menuItem);
}
public void removeViewMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuView().remove(menuItem);
}
public void removeToolsMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuTools().remove(menuItem);
}
public void removeHelpMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuHelp().remove(menuItem);
}
public void removeReportMenuItem(JMenuItem menuItem) {
if (!hasView()) {
return;
}
view.getMainFrame().getMainMenuBar().getMenuReport().remove(menuItem);
}
/** Init all extensions */
private void initAllExtension(double progressFactor) {
double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
Extension extension = getExtension(i);
try {
setExtensionAdaptorView(extension);
extension.init();
extension.databaseOpen(Model.getSingleton().getDb());
if (hasView()) {
view.addSplashScreenLoadingCompletion(factorPerc);
}
} catch (Throwable e) {
logExtensionInitError(extension, e);
}
}
}
/**
* Init all extensions with the same Model
*
* @param model the model to apply to all extensions
*/
private void initModelAllExtension(Model model, double progressFactor) {
double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
Extension extension = getExtension(i);
try {
extension.initModel(model);
if (hasView()) {
view.addSplashScreenLoadingCompletion(factorPerc);
}
} catch (Exception e) {
logExtensionInitError(extension, e);
}
}
}
/**
* Init all extensions with the same View
*
* @param view the View that need to be applied
*/
private void initViewAllExtension(final View view, double progressFactor) {
if (!hasView()) {
return;
}
final double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
final Extension extension = getExtension(i);
try {
EventQueue.invokeAndWait(
() -> {
extension.initView(view);
view.addSplashScreenLoadingCompletion(factorPerc);
});
} catch (Exception e) {
logExtensionInitError(extension, e);
}
}
}
private void initXMLAllExtension(Session session, OptionsParam options, double progressFactor) {
double factorPerc = progressFactor / getExtensionCount();
for (int i = 0; i < getExtensionCount(); i++) {
Extension extension = getExtension(i);
try {
extension.initXML(session, options);
if (hasView()) {
view.addSplashScreenLoadingCompletion(factorPerc);
}
} catch (Exception e) {
logExtensionInitError(extension, e);
}
}
}
/**
* Removes the given extension and any components added through its extension hook.
*
* <p>The extension is also {@link Extension#stop() stopped} and {@link Extension#destroy()
* destroyed}.
*
* <p><strong>Note:</strong> This method should be called only by bootstrap classes.
*
* @param extension the extension to remove.
* @since 2.8.0
*/
public void removeExtension(Extension extension) {
extensionList.remove(extension);
extensionsMap.remove(extension.getClass());
extension.stop();
unhook(extension);
extension.destroy();
}
private void unhook(Extension extension) {
ExtensionHook hook = extensionHooks.remove(extension);
if (hook == null) {
LOGGER.error(
"ExtensionHook not found for: {}", extension.getClass().getCanonicalName());
return;
}
unloadOptions(hook);
unhookProxies(hook);
removeSiteMapListener(hook);
for (ContextDataFactory contextDataFactory : hook.getContextDataFactories()) {
try {
model.removeContextDataFactory(contextDataFactory);
} catch (Exception e) {
LOGGER.error(
"Error while removing a ContextDataFactory from {}",
extension.getClass().getCanonicalName(),
e);
}
}
for (ApiImplementor apiImplementor : hook.getApiImplementors()) {
try {
API.getInstance().removeApiImplementor(apiImplementor);
} catch (Exception e) {
LOGGER.error(
"Error while removing an ApiImplementor from {}",
extension.getClass().getCanonicalName(),
e);
}
}
for (HttpSenderListener httpSenderListener : hook.getHttpSenderListeners()) {
try {
HttpSender.removeListener(httpSenderListener);
} catch (Exception e) {
LOGGER.error(
"Error while removing an HttpSenderListener from {}",
extension.getClass().getCanonicalName(),
e);
}
}
for (Class<? extends Variant> variant : hook.getVariants()) {
try {
model.getVariantFactory().removeVariant(variant);
} catch (Exception e) {
LOGGER.error(
"Error while removing a Variant from {}",
extension.getClass().getCanonicalName(),
e);
}
}
for (HrefTypeInfo hrefTypeInfo : hook.getHrefsTypeInfo()) {
try {
HrefTypeInfo.removeType(hrefTypeInfo);
} catch (Exception e) {
LOGGER.error(
"Error while removing a HrefTypeInfo from {}",
extension.getClass().getCanonicalName(),
e);
}
}
removeViewInEDT(extension, hook);
}
private void removeViewInEDT(final Extension extension, final ExtensionHook hook) {
if (!hasView()) {
return;
}
if (EventQueue.isDispatchThread()) {
removeView(extension, view, hook);
removeMenu(view, hook);
} else {
EventQueue.invokeLater(() -> removeViewInEDT(extension, hook));
}
}
/**
* Gets the names of all unsaved resources of all the extensions.
*
* @return a {@code List} containing all the unsaved resources of all add-ons, never {@code
* null}
* @see Extension#getActiveActions()
*/
public List<String> getUnsavedResources() {
return collectMessages(Extension::getUnsavedResources);
}
private List<String> collectMessages(Function<Extension, List<String>> function) {
return extensionList.stream()
.map(
e -> {
try {
List<String> messages = function.apply(e);
if (messages != null) {
return messages;
}
} catch (Throwable ex) {
LOGGER.error(
"Error while getting messages from {}",
e.getClass().getCanonicalName(),
ex);
}
return Collections.<String>emptyList();
})
.flatMap(List::stream)
.collect(Collectors.toList());
}
/**
* Gets the names of all active actions of all the extensions.
*
* @return a {@code List} containing all the active actions of all add-ons, never {@code null}
* @since 2.4.0
* @see Extension#getActiveActions()
*/
public List<String> getActiveActions() {
return collectMessages(Extension::getActiveActions);
}
}
| zaproxy/zaproxy | zap/src/main/java/org/parosproxy/paros/extension/ExtensionLoader.java |
45,322 | package hex.schemas;
import hex.Distribution;
import hex.deeplearning.DeepLearning;
import hex.deeplearning.DeepLearningModel.DeepLearningParameters;
import water.api.API;
import water.api.schemas3.ModelParametersSchemaV3;
import water.api.schemas3.KeyV3;
public class DeepLearningV3 extends ModelBuilderSchema<DeepLearning,DeepLearningV3,DeepLearningV3.DeepLearningParametersV3> {
public static final class DeepLearningParametersV3 extends ModelParametersSchemaV3<DeepLearningParameters, DeepLearningParametersV3> {
// Determines the order of parameters in the GUI
public static String[] fields = {
"model_id",
"training_frame",
"validation_frame",
"nfolds",
"keep_cross_validation_models",
"keep_cross_validation_predictions",
"keep_cross_validation_fold_assignment",
"fold_assignment",
"fold_column",
"response_column",
"ignored_columns",
"ignore_const_cols",
"score_each_iteration",
"weights_column",
"offset_column",
"balance_classes",
"class_sampling_factors",
"max_after_balance_size",
"max_confusion_matrix_size",
"checkpoint",
"pretrained_autoencoder",
"overwrite_with_best_model",
"use_all_factor_levels",
"standardize",
"activation",
"hidden",
"epochs",
"train_samples_per_iteration",
"target_ratio_comm_to_comp",
"seed",
"adaptive_rate",
"rho",
"epsilon",
"rate",
"rate_annealing",
"rate_decay",
"momentum_start",
"momentum_ramp",
"momentum_stable",
"nesterov_accelerated_gradient",
"input_dropout_ratio",
"hidden_dropout_ratios",
"l1",
"l2",
"max_w2",
"initial_weight_distribution",
"initial_weight_scale",
"initial_weights",
"initial_biases",
"loss",
"distribution",
"quantile_alpha",
"tweedie_power",
"huber_alpha",
"score_interval",
"score_training_samples",
"score_validation_samples",
"score_duty_cycle",
"classification_stop",
"regression_stop",
"stopping_rounds",
"stopping_metric",
"stopping_tolerance",
"max_runtime_secs",
"score_validation_sampling",
"diagnostics",
"fast_mode",
"force_load_balance",
"variable_importances",
"replicate_training_data",
"single_node_mode",
"shuffle_training_data",
"missing_values_handling",
"quiet_mode",
"autoencoder",
"sparse",
"col_major",
"average_activation",
"sparsity_beta",
"max_categorical_features",
"reproducible",
"export_weights_and_biases",
"mini_batch_size",
"categorical_encoding",
"elastic_averaging",
"elastic_averaging_moving_rate",
"elastic_averaging_regularization",
"export_checkpoints_dir",
"auc_type",
"custom_metric_func",
"gainslift_bins",
};
/* Imbalanced Classes */
/**
* For imbalanced data, balance training data class counts via
* over/under-sampling. This can result in improved predictive accuracy.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Balance training data class counts via over/under-sampling (for imbalanced data).")
public boolean balance_classes;
/**
* Desired over/under-sampling ratios per class (lexicographic order).
* Only when balance_classes is enabled.
* If not specified, they will be automatically computed to obtain class balance during training.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Desired over/under-sampling ratios per class (in lexicographic order). If not specified, sampling " +
"factors will be automatically computed to obtain class balance during training. Requires balance_classes.")
public float[] class_sampling_factors;
/**
* When classes are balanced, limit the resulting dataset size to the
* specified multiple of the original dataset size.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = false,
help = "Maximum relative size of the training data after balancing class counts (can be less than 1.0). " +
"Requires balance_classes.")
public float max_after_balance_size;
/** For classification models, the maximum size (in terms of classes) of
* the confusion matrix for it to be printed. This option is meant to
* avoid printing extremely large confusion matrices.
* */
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = false,
help = "[Deprecated] Maximum size (# classes) for confusion matrices to be printed in the Logs.")
public int max_confusion_matrix_size;
/* Neural Net Topology */
/**
* The activation function (non-linearity) to be used by the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Rectifier Linear Unit: Chooses the maximum of (0, x) where x is the input value.
* Maxout: Choose the maximum coordinate of the input vector.
* ExpRectifier: Exponential Rectifier Linear Unit function (http://arxiv.org/pdf/1511.07289v2.pdf)
* With Dropout: Zero out a random user-given fraction of the
* incoming weights to each hidden layer during training, for each
* training row. This effectively trains exponentially many models at
* once, and can improve generalization.
*/
@API(level = API.Level.critical, direction = API.Direction.INOUT, gridable = true,
values = {"Tanh", "TanhWithDropout", "Rectifier", "RectifierWithDropout", "Maxout", "MaxoutWithDropout"},
help = "Activation function.")
public DeepLearningParameters.Activation activation;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.
*/
@API(level = API.Level.critical, direction = API.Direction.INOUT, gridable = true,
help = "Hidden layer sizes (e.g. [100, 100]).")
public int[] hidden;
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial grid searches.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
@API(level = API.Level.critical, direction = API.Direction.INOUT, gridable = true,
help = "How many times the dataset should be iterated (streamed), can be fractional.")
public double epochs;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Number of training samples (globally) per MapReduce iteration. Special values are 0: one epoch, -1: " +
"all available data (e.g., replicated training data), -2: automatic.")
public long train_samples_per_iteration;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Target ratio of communication overhead to computation. Only for multi-node operation and " +
"train_samples_per_iteration = -2 (auto-tuning).")
public double target_ratio_comm_to_comp;
/**
* The random seed controls sampling and initialization. Reproducible
* results are only expected with single-threaded operation (i.e.,
* when running on one node, turning off load balancing and providing
* a small dataset that fits in one chunk). In general, the
* multi-threaded asynchronous updates to the model parameters will
* result in (intentional) race conditions and non-reproducible
* results. Note that deterministic sampling and initialization might
* still lead to some weak sense of determinism in the model.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Seed for random numbers (affects sampling) - Note: only reproducible when running single threaded.")
public long seed;
/*Adaptive Learning Rate*/
/**
* The implemented adaptive learning rate algorithm (ADADELTA) automatically
* combines the benefits of learning rate annealing and momentum
* training to avoid slow convergence. Specification of only two
* parameters (rho and epsilon) simplifies hyper parameter search.
* In some cases, manually controlled (non-adaptive) learning rate and
* momentum specifications can lead to better results, but require the
* specification (and hyper parameter search) of up to 7 parameters.
* If the model is built on a topology with many local minima or
* long plateaus, it is possible for a constant learning rate to produce
* sub-optimal results. Learning rate annealing allows digging deeper into
* local minima, while rate decay allows specification of different
* learning rates per layer. When the gradient is being estimated in
* a long valley in the optimization landscape, a large learning rate
* can cause the gradient to oscillate and move in the wrong
* direction. When the gradient is computed on a relatively flat
* surface with small learning rates, the model can converge far
* slower than necessary.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Adaptive learning rate.")
public boolean adaptive_rate;
/**
* The first of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to momentum and relates to the memory to prior weight updates.
* Typical values are between 0.9 and 0.999.
* This parameter is only active if adaptive learning rate is enabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Adaptive learning rate time decay factor (similarity to prior updates).")
public double rho;
/**
* The second of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to learning rate annealing during initial training
* and momentum at later stages where it allows forward progress.
* Typical values are between 1e-10 and 1e-4.
* This parameter is only active if adaptive learning rate is enabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Adaptive learning rate smoothing factor (to avoid divisions by zero and allow progress).")
public double epsilon;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Learning rate (higher => less stable, lower => slower convergence).")
public double rate;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Learning rate annealing: rate / (1 + rate_annealing * samples).")
public double rate_annealing;
/**
* The learning rate decay parameter controls the change of learning rate across layers.
* For example, assume the rate parameter is set to 0.01, and the rate_decay parameter is set to 0.5.
* Then the learning rate for the weights connecting the input and first hidden layer will be 0.01,
* the learning rate for the weights connecting the first and the second hidden layer will be 0.005,
* and the learning rate for the weights connecting the second and third hidden layer will be 0.0025, etc.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Learning rate decay factor between layers (N-th layer: rate * rate_decay ^ (n - 1).")
public double rate_decay;
/*Momentum*/
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Initial momentum at the beginning of training (try 0.5).")
public double momentum_start;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Number of training samples for which momentum increases.")
public double momentum_ramp;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Final momentum after the ramp is over (try 0.99).")
public double momentum_stable;
/**
* The Nesterov accelerated gradient descent method is a modification to
* traditional gradient descent for convex functions. The method relies on
* gradient information at various points to build a polynomial approximation that
* minimizes the residuals in fewer iterations of the descent.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Use Nesterov accelerated gradient (recommended).")
public boolean nesterov_accelerated_gradient;
/*Regularization*/
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Input layer dropout ratio (can improve generalization, try 0.1 or 0.2).")
public double input_dropout_ratio;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Hidden layer dropout ratios (can improve generalization), specify one value per hidden layer, " +
"defaults to 0.5.")
public double[] hidden_dropout_ratios;
/**
* A regularization method that constrains the absolute value of the weights and
* has the net effect of dropping some weights (setting them to zero) from a model
* to reduce complexity and avoid overfitting.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "L1 regularization (can add stability and improve generalization, causes many weights to become 0).")
public double l1;
/**
* A regularization method that constrains the sum of the squared
* weights. This method introduces bias into parameter estimates, but
* frequently produces substantial gains in modeling as estimate variance is
* reduced.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "L2 regularization (can add stability and improve generalization, causes many weights to be small.")
public double l2;
/**
* A maximum on the sum of the squared incoming weights into
* any one neuron. This tuning parameter is especially useful for unbound
* activation functions such as Maxout or Rectifier.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Constraint for squared sum of incoming weights per unit (e.g. for Rectifier).")
public float max_w2;
/*Initialization*/
/**
* The distribution from which initial weights are to be drawn. The default
* option is an optimized initialization that considers the size of the network.
* The "uniform" option uses a uniform distribution with a mean of 0 and a given
* interval. The "normal" option draws weights from the standard normal
* distribution with a mean of 0 and given standard deviation.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
values = {"UniformAdaptive", "Uniform", "Normal"},
help = "Initial weight distribution.")
public DeepLearningParameters.InitialWeightDistribution initial_weight_distribution;
/**
* The scale of the distribution function for Uniform or Normal distributions.
* For Uniform, the values are drawn uniformly from -initial_weight_scale...initial_weight_scale.
* For Normal, the values are drawn from a Normal distribution with a standard deviation of initial_weight_scale.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Uniform: -value...value, Normal: stddev.")
public double initial_weight_scale;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable=true,
help = "A list of H2OFrame ids to initialize the weight matrices of this model with.")
public KeyV3.FrameKeyV3[] initial_weights;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable=true,
help = "A list of H2OFrame ids to initialize the bias vectors of this model with.")
public KeyV3.FrameKeyV3[] initial_biases;
/**
* The loss (error) function to be minimized by the model.
* CrossEntropy loss is used when the model output consists of independent
* hypotheses, and the outputs can be interpreted as the probability that each
* hypothesis is true. Cross entropy is the recommended loss function when the
* target values are class labels, and especially for imbalanced data.
* It strongly penalizes error in the prediction of the actual class label.
* Quadratic loss is used when the model output are continuous real values, but can
* be used for classification as well (where it emphasizes the error on all
* output classes, not just for the actual class).
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true, required = false,
values = {"Automatic", "CrossEntropy", "Quadratic", "Huber", "Absolute", "Quantile"},
help = "Loss function.")
public DeepLearningParameters.Loss loss;
/*Scoring*/
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Shortest time interval (in seconds) between model scoring.")
public double score_interval;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Number of training set samples for scoring (0 for all).")
public long score_training_samples;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Number of validation set samples for scoring (0 for all).")
public long score_validation_samples;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Maximum duty cycle fraction for scoring (lower: more training, higher: more scoring).")
public double score_duty_cycle;
/**
* The stopping criteria in terms of classification error (1-accuracy) on the
* training data scoring dataset. When the error is at or below this threshold,
* training stops.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Stopping criterion for classification error fraction on training data (-1 to disable).")
public double classification_stop;
/**
* The stopping criteria in terms of regression error (MSE) on the training
* data scoring dataset. When the error is at or below this threshold, training
* stops.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Stopping criterion for regression error (MSE) on training data (-1 to disable).")
public double regression_stop;
/**
* Enable quiet mode for less output to standard output.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Enable quiet mode for less output to standard output.")
public boolean quiet_mode;
/**
* Method used to sample the validation dataset for scoring, see Score Validation Samples above.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
values = {"Uniform", "Stratified"},
help = "Method used to sample validation dataset for scoring.")
public DeepLearningParameters.ClassSamplingMethod score_validation_sampling;
/* Miscellaneous */
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "If enabled, override the final model with the best model found during training.")
public boolean overwrite_with_best_model;
@API(level = API.Level.secondary, direction = API.Direction.INOUT,
help = "Auto-Encoder.")
public boolean autoencoder;
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Use all factor levels of categorical variables. Otherwise, the first factor level is omitted (without" +
" loss of accuracy). Useful for variable importances and auto-enabled for autoencoder.")
public boolean use_all_factor_levels;
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "If enabled, automatically standardize the data. If disabled, the user must provide properly scaled " +
"input data.")
public boolean standardize;
/**
* Gather diagnostics for hidden layers, such as mean and RMS values of learning
* rate, momentum, weights and biases.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT,
help = "Enable diagnostics for hidden layers.")
public boolean diagnostics;
/**
* Whether to compute variable importances for input features.
* The implemented method (by Gedeon) considers the weights connecting the
* input features to the first two hidden layers.
*/
@API(level = API.Level.critical, direction = API.Direction.INOUT, gridable = true,
help = "Compute variable importances for input features (Gedeon method) - can be slow for large networks.")
public boolean variable_importances;
/**
* Enable fast mode (minor approximation in back-propagation), should not affect results significantly.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Enable fast mode (minor approximation in back-propagation).")
public boolean fast_mode;
/**
* Increase training speed on small datasets by splitting it into many chunks
* to allow utilization of all cores.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Force extra load balancing to increase training speed for small datasets (to keep all cores busy).")
public boolean force_load_balance;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
@API(level = API.Level.secondary, direction = API.Direction.INOUT, gridable = true,
help = "Replicate the entire training dataset onto every node for faster training on small datasets.")
public boolean replicate_training_data;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Run on a single node for fine-tuning of model parameters.")
public boolean single_node_mode;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train will (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Enable shuffling of training data (recommended if training data is replicated and " +
"train_samples_per_iteration is close to #nodes x #rows, of if using balance_classes).")
public boolean shuffle_training_data;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
values = {"MeanImputation", "Skip"},
help = "Handling of missing values. Either MeanImputation or Skip.")
public DeepLearningParameters.MissingValuesHandling missing_values_handling;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Sparse data handling (more efficient for data with lots of 0 values).")
public boolean sparse;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "#DEPRECATED Use a column major weight matrix for input layer. Can speed up forward propagation, but " +
"might slow down backpropagation.")
public boolean col_major;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Average activation for sparse auto-encoder. #Experimental")
public double average_activation;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Sparsity regularization. #Experimental")
public double sparsity_beta;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Max. number of categorical features, enforced via hashing. #Experimental")
public int max_categorical_features;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Force reproducibility on small data (will be slow - only uses 1 thread).")
public boolean reproducible;
@API(level = API.Level.expert, direction=API.Direction.INOUT,
help = "Whether to export Neural Network weights and biases to H2O Frames.")
public boolean export_weights_and_biases;
@API(level = API.Level.expert, direction=API.Direction.INOUT,
help = "Mini-batch size (smaller leads to better fit, larger can speed up and generalize better).")
public int mini_batch_size;
@API(level = API.Level.expert, direction=API.Direction.INOUT, gridable = true,
help = "Elastic averaging between compute nodes can improve distributed model convergence. #Experimental")
public boolean elastic_averaging;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Elastic averaging moving rate (only if elastic averaging is enabled).")
public double elastic_averaging_moving_rate;
@API(level = API.Level.expert, direction = API.Direction.INOUT, gridable = true,
help = "Elastic averaging regularization strength (only if elastic averaging is enabled).")
public double elastic_averaging_regularization;
@API(level = API.Level.expert, direction = API.Direction.INOUT,
help = "Pretrained autoencoder model to initialize this model with.")
public KeyV3.ModelKeyV3 pretrained_autoencoder;
}
}
| h2oai/h2o-3 | h2o-algos/src/main/java/hex/schemas/DeepLearningV3.java |
45,323 | package org.jeecg.common.api.dto;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* online 拦截器权限判断
* cloud api 用到的接口传输对象
* @author: jeecg-boot
*/
@Data
public class OnlineAuthDTO implements Serializable {
private static final long serialVersionUID = 1771827545416418203L;
/**
* 用户名
*/
private String username;
/**
* 可能的请求地址
*/
private List<String> possibleUrl;
/**
* online开发的菜单地址
*/
private String onlineFormUrl;
//update-begin---author:chenrui ---date:20240123 for:[QQYUN-7992]【online】工单申请下的online表单,未配置online表单开发菜单,操作报错无权限------------
/**
* online工单的地址
*/
private String onlineWorkOrderUrl;
//update-end---author:chenrui ---date:20240123 for:[QQYUN-7992]【online】工单申请下的online表单,未配置online表单开发菜单,操作报错无权限------------
public OnlineAuthDTO(){
}
public OnlineAuthDTO(String username, List<String> possibleUrl, String onlineFormUrl){
this.username = username;
this.possibleUrl = possibleUrl;
this.onlineFormUrl = onlineFormUrl;
}
}
| lokbun/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/common/api/dto/OnlineAuthDTO.java |
45,324 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2022 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.www;
import org.owasp.encoder.Encode;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.Job;
import org.pentaho.di.trans.Trans;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings( {"squid:S1192", "squid:S1075" } ) // suppress warnings related to dup'd strings & non-config path
public class GetStatusServlet extends BaseHttpServlet implements CartePluginInterface {
private static final Class<?> PKG = GetStatusServlet.class; // for i18n purposes, needed by Translator2!!
private static final long serialVersionUID = 3634806745372015720L;
public static final String CONTEXT_PATH = "/kettle/status";
public GetStatusServlet() {
}
public GetStatusServlet( TransformationMap transformationMap, JobMap jobMap ) {
super( transformationMap, jobMap );
}
/**
<div id="mindtouch">
<h1>/kettle/status</h1>
<a name="GET"></a>
<h2>GET</h2>
<p>Retrieve server status. The status contains information about the server itself (OS, memory, etc)
and information about jobs and transformations present on the server.</p>
<p><b>Example Request:</b><br />
<pre function="syntax.xml">
GET /kettle/status/?xml=Y
</pre>
</p>
<h3>Parameters</h3>
<table class="pentaho-table">
<tbody>
<tr>
<th>name</th>
<th>description</th>
<th>type</th>
</tr>
<tr>
<td>xml</td>
<td>Boolean flag which defines output format <code>Y</code> forces XML output to be generated.
HTML is returned otherwise.</td>
<td>boolean, optional</td>
</tr>
</tbody>
</table>
<h3>Response Body</h3>
<table class="pentaho-table">
<tbody>
<tr>
<td align="right">element:</td>
<td>(custom)</td>
</tr>
<tr>
<td align="right">media types:</td>
<td>text/xml, text/html</td>
</tr>
</tbody>
</table>
<p>Response XML or HTML response containing details about the transformation specified.
If an error occurs during method invocation <code>result</code> field of the response
will contain <code>ERROR</code> status.</p>
<p><b>Example Response:</b></p>
<pre function="syntax.xml">
<?xml version="1.0" encoding="UTF-8"?>
<serverstatus>
<statusdesc>Online</statusdesc>
<memory_free>229093440</memory_free>
<memory_total>285736960</memory_total>
<cpu_cores>4</cpu_cores>
<cpu_process_time>7534848300</cpu_process_time>
<uptime>68818403</uptime>
<thread_count>45</thread_count>
<load_avg>-1.0</load_avg>
<os_name>Windows 7</os_name>
<os_version>6.1</os_version>
<os_arch>amd64</os_arch>
<transstatuslist>
<transstatus>
<transname>Row generator test</transname>
<id>56c93d4e-96c1-4fae-92d9-d864b0779845</id>
<status_desc>Waiting</status_desc>
<error_desc/>
<paused>N</paused>
<stepstatuslist>
</stepstatuslist>
<first_log_line_nr>0</first_log_line_nr>
<last_log_line_nr>0</last_log_line_nr>
<logging_string><![CDATA[]]></logging_string>
</transstatus>
<transstatus>
<transname>dummy-trans</transname>
<id>c56961b2-c848-49b8-abde-76c8015e29b0</id>
<status_desc>Stopped</status_desc>
<error_desc/>
<paused>N</paused>
<stepstatuslist>
</stepstatuslist>
<first_log_line_nr>0</first_log_line_nr>
<last_log_line_nr>0</last_log_line_nr>
<logging_string><![CDATA[]]></logging_string>
</transstatus>
</transstatuslist>
<jobstatuslist>
<jobstatus>
<jobname>dummy_job</jobname>
<id>abd61143-8174-4f27-9037-6b22fbd3e229</id>
<status_desc>Stopped</status_desc>
<error_desc/>
<logging_string><![CDATA[]]></logging_string>
<first_log_line_nr>0</first_log_line_nr>
<last_log_line_nr>0</last_log_line_nr>
</jobstatus>
</jobstatuslist>
</serverstatus>
</pre>
<h3>Status Codes</h3>
<table class="pentaho-table">
<tbody>
<tr>
<th>code</th>
<th>description</th>
</tr>
<tr>
<td>200</td>
<td>Request was processed.</td>
</tr>
<tr>
<td>500</td>
<td>Internal server error occurs during request processing.</td>
</tr>
</tbody>
</table>
</div>
*/
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
IOException {
if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) {
return;
}
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetStatusServlet.StatusRequested" ) );
}
response.setStatus( HttpServletResponse.SC_OK );
String root = request.getRequestURI() == null ? StatusServletUtils.PENTAHO_ROOT
: request.getRequestURI().substring( 0, request.getRequestURI().indexOf( CONTEXT_PATH ) );
String prefix = isJettyMode() ? StatusServletUtils.STATIC_PATH : root + StatusServletUtils.RESOURCES_PATH;
prefix = encodeUriComponents( prefix );
root = encodeUriComponents( root );
boolean useXML = "Y".equalsIgnoreCase( request.getParameter( "xml" ) );
boolean useLightTheme = "Y".equalsIgnoreCase( request.getParameter( "useLightTheme" ) );
if ( useXML ) {
response.setContentType( "text/xml" );
response.setCharacterEncoding( Const.XML_ENCODING );
} else {
response.setContentType( "text/html;charset=UTF-8" );
}
PrintWriter out = response.getWriter();
List<CarteObjectEntry> transEntries = getTransformationMap().getTransformationObjects();
List<CarteObjectEntry> jobEntries = getJobMap().getJobObjects();
if ( useXML ) {
out.print( XMLHandler.getXMLHeader( Const.XML_ENCODING ) );
SlaveServerStatus serverStatus = new SlaveServerStatus();
serverStatus.setStatusDescription( "Online" );
getSystemInfo( serverStatus );
for ( CarteObjectEntry entry : transEntries ) {
Trans trans = getTransformationMap().getTransformation( entry );
if ( trans != null ) {
String status = trans.getStatus();
SlaveServerTransStatus sstatus = new SlaveServerTransStatus( entry.getName(), entry.getId(), status );
sstatus.setLogDate( trans.getLogDate() );
sstatus.setPaused( trans.isPaused() );
serverStatus.getTransStatusList().add( sstatus );
}
}
for ( CarteObjectEntry entry : jobEntries ) {
Job job = getJobMap().getJob( entry );
if ( job != null ) {
String status = job.getStatus();
SlaveServerJobStatus jobStatus = new SlaveServerJobStatus( entry.getName(), entry.getId(), status );
jobStatus.setLogDate( job.getLogDate() );
serverStatus.getJobStatusList().add( jobStatus );
}
}
try {
out.println( serverStatus.getXML() );
} catch ( KettleException e ) {
throw new ServletException( "Unable to get the server status in XML format", e );
}
} else {
out.println( "<HTML>" );
out.println( "<HEAD><TITLE>"
+ BaseMessages.getString( PKG, "GetStatusServlet.KettleSlaveServerStatus" ) + "</TITLE>" );
out.println( "<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" );
int tableBorder = 1;
if ( !useLightTheme ) {
if ( isJettyMode() ) {
out.println( "<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/css/carte.css\" />" );
} else {
out.print( StatusServletUtils.getPentahoStyles( request.getSession().getServletContext(), root ) );
out.println( "<style>" );
out.println(
".pentaho-table td, tr.cellTableRow, td.gwt-MenuItem, .toolbar-button:not(.toolbar-button-disabled) {" );
out.println( " cursor: pointer;" );
out.println( "}" );
out.println( ".toolbar-button-disabled {" );
out.println( " opacity: 0.4;" );
out.println( "}" );
out.println( "div#messageDialogBody:first-letter {" );
out.println( " text-transform: capitalize;" );
out.println( "}" );
out.println( "</style>" );
}
tableBorder = 0;
}
out.println( "</HEAD>" );
out.println(
"<BODY class=\"pentaho-page-background dragdrop-dropTarget dragdrop-boundary\" style=\"overflow: auto;\">" );
// Empty div for containing currently selected item
out.println( "<div id=\"selectedTableItem\">" );
out.println( "<value></value>" ); //initialize to none
out.println( "</div>" );
out.println( "<div class=\"row\" id=\"pucHeader\">" );
String htmlClass = useLightTheme ? "h1" : "div";
out.println( "<" + htmlClass + " class=\"workspaceHeading\" style=\"padding: 0px 0px 0px 10px;\">" + BaseMessages
.getString( PKG, "GetStatusServlet.TopStatus" ) + "</" + htmlClass + ">" );
out.println( "</div>" );
// Tooltips
String run = BaseMessages.getString( PKG, "CarteStatusServlet.Run" );
String stop = BaseMessages.getString( PKG, "CarteStatusServlet.StopTrans" );
String view = BaseMessages.getString( PKG, "CarteStatusServlet.ViewTransDetails" );
String remove = BaseMessages.getString( PKG, "CarteStatusServlet.RemoveTrans" );
String runJ = BaseMessages.getString( PKG, "CarteStatusServlet.Run" );
String stopJ = BaseMessages.getString( PKG, "CarteStatusServlet.StopJob" );
String viewJ = BaseMessages.getString( PKG, "CarteStatusServlet.ViewJobDetails" );
String removeJ = BaseMessages.getString( PKG, "CarteStatusServlet.RemoveJob" );
try {
out.println( "<div class=\"row\" style=\"padding: 0px 0px 0px 30px\">" );
htmlClass = useLightTheme ? "h2" : "div";
out.println( "<div class=\"row\" style=\"padding: 25px 30px 75px 0px;\">" );
out.println(
"<" + htmlClass + " class=\"workspaceHeading\" style=\"padding: 0px 0px 0px 0px;\">Transformations</"
+ htmlClass + ">" );
out.println(
"<table id=\"trans-table\" cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td align=\"left\" width=\"100%\""
+ " style=\"vertical-align:middle;\">" );
out.println(
"<table cellspacing=\"0\" cellpadding=\"0\" class=\"toolbar\" style=\"width: 100%; height: 26px; "
+ "margin-bottom: 2px; border: 0;\">" );
out.println( "<tbody><tr>" );
out.println( "<td align=\"left\" style=\"vertical-align: middle; width: 100%\" id=\"trans-align\"></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "run-pause" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" "
+ "onClick=\"runPauseFunction( this )\" class=\"toolbar-button toolbar-button-disabled\" "
+ "id=\"run-pause\"><img style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/run.svg\" title=\"" + run + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "stop" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" onClick=\"stopFunction( "
+ "this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"stop\"><img style=\"width: 22px; height: "
+ "22px\"src=\""
+ prefix + "/images/stop.svg\" title=\"" + stop + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "view" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" onClick=\"viewFunction( "
+ "this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"view\"><img style=\"width: 22px; height: "
+ "22px\" src=\""
+ prefix + "/images/view.svg\" title=\"" + view + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "close" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px; margin-right: 10px;\" "
+ "onClick=\"removeFunction( this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"close\"><img "
+ "style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/close.svg\" title=\"" + remove + "\"/></div></td>" );
out.println( "</tr></tbody></table>" );
out.println(
"<div id=\"stopActions\" class=\"custom-dropdown-popup\" style=\"visibility: hidden; overflow: visible; "
+ "position: fixed;\" onLoad=\"repositionActions( this, document.getElementById( 'stop' ) )\" "
+ "onMouseLeave=\"this.style='visibility: hidden; overflow: visible; position: fixed;'\"><div "
+ "class=\"popupContent\"><div style=\"padding: 0;\" class=\"gwt-MenuBar "
+ "gwt-MenuBar-vertical\"><table><tbody><tr><td class=\"gwt-MenuItem\" onClick=\"stopTransSelector( this "
+ ")\" onMouseEnter=\"this.className='gwt-MenuItem gwt-MenuItem-selected'\" onMouseLeave=\"this"
+ ".className='gwt-MenuItem'\">Stop transformation</td></tr><tr><td class=\"gwt-MenuItem\" "
+ "onClick=\"stopTransSelector( this )\" onMouseEnter=\"this.className='gwt-MenuItem "
+ "gwt-MenuItem-selected'\" onMouseLeave=\"this.className='gwt-MenuItem'\">Stop input "
+ "processing</td></tr></tbody></table></div></div></div>" );
out.println( messageDialog() );
out.println( "<table class=\"pentaho-table\" border=\"" + tableBorder + "\">" );
out.print( "<tr> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.TransName" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.CarteId" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Status" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.LastLogDate" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.LastLogTime" ) + "</th> </tr>" );
Comparator<CarteObjectEntry> transComparator = ( o1, o2 ) -> {
Trans t1 = getTransformationMap().getTransformation( o1 );
Trans t2 = getTransformationMap().getTransformation( o2 );
// If transformations are null because they were removed from the map, sort them to end of list
if ( t1 == null && t2 == null ) {
return 0;
}
if ( t1 == null ) {
return 1;
}
if ( t2 == null ) {
return -1;
}
Date d1 = t1.getLogDate();
Date d2 = t2.getLogDate();
// if both transformations have last log date, desc sort by log date
if ( d1 != null && d2 != null ) {
int logDateCompare = d2.compareTo( d1 );
if ( logDateCompare != 0 ) {
return logDateCompare;
}
}
return o1.compareTo( o2 );
};
Collections.sort( transEntries, transComparator );
boolean evenRow = true;
for ( int i = 0; i < transEntries.size(); i++ ) {
String name = Encode.forHtml( transEntries.get( i ).getName() );
String id = Encode.forHtml( transEntries.get( i ).getId() );
Trans trans = getTransformationMap().getTransformation( transEntries.get( i ) );
if ( trans != null ) {
String status = Encode.forHtml( trans.getStatus() );
String trClass = evenRow ? "cellTableEvenRow" : "cellTableOddRow"; // alternating row color
String tdClass = evenRow ? "cellTableEvenRowCell" : "cellTableOddRowCell";
evenRow = !evenRow; // flip
out.print( "<tr onMouseEnter=\"mouseEnterFunction( this, '" + trClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + trClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + trClass + "' )\" "
+ "id=\"cellTableRow_" + i + "\" class=\"" + trClass + "\">" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"cellTableFirstCell_" + i + "\" class=\"cellTableCell cellTableFirstColumn " + tdClass + "\">"
+ name
+ "</td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"cellTableCell_" + i + "\" class=\"cellTableCell " + tdClass + "\">" + id + "</td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"cellTableCellStatus_" + i + "\" class=\"cellTableCell " + tdClass + "\">" + status + "</td>" );
String dateStr = XMLHandler.date2string( trans.getLogDate() );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"cellTableCell_" + i + "\" class=\"cellTableCell " + tdClass + "\">"
+ ( trans.getLogDate() == null ? "-" : dateStr.substring( 0, dateStr.indexOf( ' ' ) ) ) + "</td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"cellTableLastCell_" + i + "\" class=\"cellTableCell cellTableLastColumn " + tdClass + "\">"
+ ( trans.getLogDate() == null ? "-" : dateStr.substring( dateStr.indexOf( ' ' ), dateStr.length() ) )
+ "</td>" );
out.print( "</tr>" );
}
}
out.print( "</table></table>" );
out.print( "</div>" ); // end div
out.println( "<div class=\"row\" style=\"padding: 0px 30px 75px 0px;\">" );
out.println(
"<" + htmlClass + " class=\"workspaceHeading\" style=\"padding: 0px 0px 0px 0px;\">Jobs</" + htmlClass
+ ">" );
out.println(
"<table cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td align=\"left\" width=\"100%\" "
+ "style=\"vertical-align:middle;\">" );
out.println(
"<table cellspacing=\"0\" cellpadding=\"0\" class=\"toolbar\" style=\"width: 100%; height: 26px; "
+ "margin-bottom: 2px; border: 0;\">" );
out.println( "<tbody><tr>" );
out.println( "<td align=\"left\" style=\"vertical-align: middle; width: 100%\"></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "j-run-pause" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" "
+ "onClick=\"runPauseFunction( this )\" class=\"toolbar-button toolbar-button-disabled\" "
+ "id=\"j-run-pause\"><img style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/run.svg\" title=\"" + runJ + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "j-stop" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" onClick=\"stopFunction( "
+ "this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"j-stop\"><img style=\"width: 22px; "
+ "height: 22px\"src=\""
+ prefix + "/images/stop.svg\" title=\"" + stopJ + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "j-view" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px;\" onClick=\"viewFunction( "
+ "this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"j-view\"><img style=\"width: 22px; "
+ "height: 22px\" src=\""
+ prefix + "/images/view.svg\" title=\"" + viewJ + "\"/></div></td>" );
out.println( "<td " + setupIconEnterLeaveJavascript( "j-close" )
+ " align=\"left\" style=\"vertical-align: middle;\"><div style=\"padding: 2px; margin-right: 10px;\" "
+ "onClick=\"removeFunction( this )\" class=\"toolbar-button toolbar-button-disabled\" id=\"j-close\"><img "
+ "style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/close.svg\" title=\"" + removeJ + "\"/></div></td>" );
out.println( "</tr></tbody></table>" );
out.println( "<table class=\"pentaho-table\" border=\"" + tableBorder + "\">" );
out.print( "<tr> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.JobName" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.CarteId" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Status" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.LastLogDate" ) + "</th> <th class=\"cellTableHeader\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.LastLogTime" ) + "</th> </tr>" );
Comparator<CarteObjectEntry> jobComparator = ( o1, o2 ) -> {
Job t1 = getJobMap().getJob( o1 );
Job t2 = getJobMap().getJob( o2 );
// If jobs are null because they were removed from the map, sort them to end of list
if ( t1 == null && t2 == null ) {
return 0;
}
if ( t1 == null ) {
return 1;
}
if ( t2 == null ) {
return -1;
}
Date d1 = t1.getLogDate();
Date d2 = t2.getLogDate();
// if both jobs have last log date, desc sort by log date
if ( d1 != null && d2 != null ) {
int logDateCompare = d2.compareTo( d1 );
if ( logDateCompare != 0 ) {
return logDateCompare;
}
}
return o1.compareTo( o2 );
};
Collections.sort( jobEntries, jobComparator );
evenRow = true;
for ( int i = 0; i < jobEntries.size(); i++ ) {
String name = Encode.forHtml( jobEntries.get( i ).getName() );
String id = Encode.forHtml( jobEntries.get( i ).getId() );
Job job = getJobMap().getJob( jobEntries.get( i ) );
if ( job != null ) {
String status = Encode.forHtml( job.getStatus() );
String trClass = evenRow ? "cellTableEvenRow" : "cellTableOddRow"; // alternating row color
String tdClass = evenRow ? "cellTableEvenRowCell" : "cellTableOddRowCell";
evenRow = !evenRow; // flip
out.print( "<tr onMouseEnter=\"mouseEnterFunction( this, '" + trClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + trClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + trClass + "' )\" "
+ "id=\"j-cellTableRow_" + i + "\" class=\"cellTableCell " + trClass + "\">" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"j-cellTableFirstCell_" + i + "\" class=\"cellTableCell cellTableFirstColumn " + tdClass + "\">"
+ name + "</a></td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"j-cellTableCell_" + i + "\" class=\"cellTableCell " + tdClass + "\">" + id + "</td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"j-cellTableCell_" + i + "\" class=\"cellTableCell " + tdClass + "\">" + status + "</td>" );
String dateStr = XMLHandler.date2string( job.getLogDate() );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"j-cellTableCell_" + i + "\" class=\"cellTableCell " + tdClass + "\">"
+ ( job.getLogDate() == null ? "-" : dateStr.substring( 0, dateStr.indexOf( ' ' ) ) ) + "</td>" );
out.print( "<td onMouseEnter=\"mouseEnterFunction( this, '" + tdClass + "' )\" "
+ "onMouseLeave=\"mouseLeaveFunction( this, '" + tdClass + "' )\" "
+ "onClick=\"clickFunction( this, '" + tdClass + "' )\" "
+ "id=\"j-cellTableLastCell_" + i + "\" class=\"cellTableCell cellTableLastColumn " + tdClass + "\">"
+ ( job.getLogDate() == null ? "-" : dateStr.substring( dateStr.indexOf( ' ' ), dateStr.length() ) )
+ "</td>" );
out.print( "</tr>" );
}
}
out.print( "</table></table>" );
out.print( "</div>" ); // end div
} catch ( Exception ex ) {
out.println( "<pre>" );
ex.printStackTrace( out );
out.println( "</pre>" );
}
out.println( "<div class=\"row\" style=\"padding: 0px 0px 30px 0px;\">" );
htmlClass = useLightTheme ? "h3" : "div";
out.println( "<div><" + htmlClass + " class=\"workspaceHeading\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.ConfigurationDetails.Title" ) + "</" + htmlClass + "></div>" );
out.println( "<table border=\"" + tableBorder + "\">" );
// The max number of log lines in the back-end
//
SlaveServerConfig serverConfig = getTransformationMap().getSlaveServerConfig();
if ( serverConfig != null ) {
String maxLines = "";
if ( serverConfig.getMaxLogLines() == 0 ) {
maxLines = BaseMessages.getString( PKG, "GetStatusServlet.NoLimit" );
} else {
maxLines = serverConfig.getMaxLogLines() + BaseMessages.getString( PKG, "GetStatusServlet.Lines" );
}
out.print(
"<tr style=\"font-size: 12;\"> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell "
+ "cellTableEvenRowCell cellTableFirstColumn\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Parameter.MaxLogLines" )
+ "</td> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell cellTableEvenRowCell "
+ "cellTableLastColumn\">"
+ maxLines
+ "</td> </tr>" );
// The max age of log lines
//
String maxAge = "";
if ( serverConfig.getMaxLogTimeoutMinutes() == 0 ) {
maxAge = BaseMessages.getString( PKG, "GetStatusServlet.NoLimit" );
} else {
maxAge = serverConfig.getMaxLogTimeoutMinutes() + BaseMessages.getString( PKG, "GetStatusServlet.Minutes" );
}
out.print(
"<tr style=\"font-size: 12;\"> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell "
+ "cellTableEvenRowCell cellTableFirstColumn\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Parameter.MaxLogLinesAge" )
+ "</td> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell cellTableEvenRowCell "
+ "cellTableLastColumn\">"
+ maxAge
+ "</td> </tr>" );
// The max age of stale objects
//
String maxObjAge = "";
if ( serverConfig.getObjectTimeoutMinutes() == 0 ) {
maxObjAge = BaseMessages.getString( PKG, "GetStatusServlet.NoLimit" );
} else {
maxObjAge =
serverConfig.getObjectTimeoutMinutes() + BaseMessages.getString( PKG, "GetStatusServlet.Minutes" );
}
out.print(
"<tr style=\"font-size: 12;\"> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell "
+ "cellTableEvenRowCell cellTableFirstColumn\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Parameter.MaxObjectsAge" )
+ "</td> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell cellTableEvenRowCell "
+ "cellTableLastColumn\">"
+ maxObjAge
+ "</td> </tr>" );
// The name of the specified repository
//
String repositoryName;
try {
repositoryName = serverConfig.getRepository() != null ? serverConfig.getRepository().getName() : "";
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "GetStatusServlet.Parameter.RepositoryName.UnableToConnect",
serverConfig.getRepositoryId() ), e );
repositoryName = BaseMessages.getString( PKG, "GetStatusServlet.Parameter.RepositoryName.UnableToConnect",
serverConfig.getRepositoryId() );
}
out.print(
"<tr style=\"font-size: 12;\"> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell "
+ "cellTableEvenRowCell cellTableFirstColumn\">"
+ BaseMessages.getString( PKG, "GetStatusServlet.Parameter.RepositoryName" )
+ "</td> <td style=\"padding: 2px 10px 2px 10px\" class=\"cellTableCell cellTableEvenRowCell "
+ "cellTableLastColumn\">"
+ repositoryName + "</td> </tr>" );
out.print( "</table>" );
String filename = serverConfig.getFilename();
if ( filename == null ) {
filename = BaseMessages.getString( PKG, "GetStatusServlet.ConfigurationDetails.UsingDefaults" );
}
out.println( "</div>" ); // end div
out.print( "<div class=\"row\">" );
out
.println( "<i>"
+ BaseMessages.getString( PKG, "GetStatusServlet.ConfigurationDetails.Advice", filename )
+ "</i>" );
out.print( "</div>" );
out.print( "</div>" );
out.print( "</div>" );
}
out.println( "<script type=\"text/javascript\">" );
out.println( "if (!String.prototype.endsWith) {" );
out.println( " String.prototype.endsWith = function(suffix) {" );
out.println( " return this.indexOf(suffix, this.length - suffix.length) !== -1;" );
out.println( " };" );
out.println( "}" );
out.println( "if (!String.prototype.startsWith) {" );
out.println( " String.prototype.startsWith = function(searchString, position) {" );
out.println( " position = position || 0;" );
out.println( " return this.indexOf(searchString, position) === position;" );
out.println( " };" );
out.println( "}" );
out.println( "var selectedTransRowIndex = -1;" ); // currently selected table item
out.println( "var selectedJobRowIndex = -1;" ); // currently selected table item
out.println( "var removeElement = null;" ); // element of remove button clicked
out.println( "var selectedTransName = \"\";" );
out.println( "var selectedJobName = \"\";" );
// Click function for stop button
out.println( "function repositionActions( element, elementFrom ) {" );
out.println( "element.style.left = ( 10 + elementFrom.getBoundingClientRect().left ) + 'px';" );
out.println( "}" );
// Click function for Run, Pause, or Resume button
out.println( "function runPauseFunction( element ) {" );
out.println( "if( !element.classList.contains('toolbar-button-disabled') ) {" );
out.println( "if( element.id.startsWith( 'j-' ) && selectedJobRowIndex != -1 ) {" );
out.println( setupAjaxCall( setupJobURI( convertContextPath( StartJobServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.StartJob.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StartJob.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StartJob.Failure.Body" ) + "'" ) );
out.println(
"} else if ( !element.id.startsWith( 'j-' ) && selectedTransRowIndex != -1 && document.getElementById( "
+ "'cellTableCellStatus_' + selectedTransRowIndex ).innerHTML == 'Running') {" );
out.println( setupAjaxCall( setupTransURI( convertContextPath( PauseTransServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.PauseTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.PauseTrans.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.PauseTrans.Failure.Body" ) + "'" ) );
out.println(
"} else if( !element.id.startsWith( 'j-' ) && selectedTransRowIndex != -1 && document.getElementById( "
+ "'cellTableCellStatus_' + selectedTransRowIndex ).innerHTML == 'Paused') {" );
out.println( setupAjaxCall( setupTransURI( convertContextPath( PauseTransServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.ResumeTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.ResumeTrans.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.ResumeTrans.Failure.Body" ) + "'" ) );
out.println( "} else if( !element.id.startsWith( 'j-' ) && selectedTransRowIndex != -1 ){" );
out.println( setupAjaxCall( setupTransURI( convertContextPath( StartTransServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.StartTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StartTrans.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StartTrans.Failure.Body" ) + "'" ) );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// Click function for stop button
out.println( "function stopFunction( element ) {" );
out.println( "if( !element.classList.contains('toolbar-button-disabled') ) {" );
out.println( "if( element.id.startsWith( 'j-' ) && selectedJobRowIndex != -1 ) {" );
out.println( setupAjaxCall( setupJobURI( convertContextPath( StopJobServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.StopJob.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.StopJob.Success.Body1" ) + " " + BaseMessages
.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' " + BaseMessages
.getString( PKG, "GetStatusServlet.StopJob.Success.Body2" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StopJob.Failure.Body" ) + "'" ) );
out.println( "} else if ( !element.id.startsWith( 'j-' ) && selectedTransRowIndex != -1 ) {" );
out.println( "repositionActions( document.getElementById( 'stopActions' ), element );" );
out.println( "document.getElementById( 'stopActions' ).style.visibility = 'visible';" );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// Click function for stop button
out.println( "function stopTransSelector( element ) {" );
out.println( "if( element.innerHTML == 'Stop transformation' ) {" );
out.println( setupAjaxCall( setupTransURI( convertContextPath( StopTransServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.StopTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.StopTrans.Success.Body1" ) + " " + BaseMessages
.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' " + BaseMessages
.getString( PKG, "GetStatusServlet.StopTrans.Success.Body2" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.StopTrans.Failure.Body" ) + "'" ) );
out.println( "} else if( element.innerHTML == 'Stop input processing' ) {" );
out.println(
setupAjaxCall( setupTransURI( convertContextPath( StopTransServlet.CONTEXT_PATH ) ) + " + '&inputOnly=Y'",
BaseMessages.getString( PKG, "GetStatusServlet.StopInputTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.StopInputTrans.Success.Body1" ) + " " + BaseMessages
.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' " + BaseMessages
.getString( PKG, "GetStatusServlet.StopInputTrans.Success.Body2" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" )
+ " ' + selectedTransName + ' " + BaseMessages
.getString( PKG, "GetStatusServlet.StopInputTrans.Failure.Body" ) + "'" ) );
out.println( "}" );
out.println( "document.getElementById( 'stopActions' ).style.visibility = 'hidden';" );
out.println( "}" );
// Click function for view button
out.println( "function viewFunction( element ) {" );
out.println( "if( !element.classList.contains('toolbar-button-disabled') ) {" );
out.println( "if( element.id.startsWith( 'j-' ) && selectedJobRowIndex != -1 ) {" );
out.println( "window.location.replace( '"
+ convertContextPath( GetJobStatusServlet.CONTEXT_PATH ) + "'"
+ " + '?name=' + encodeURIComponent(document.getElementById( 'j-cellTableFirstCell_' + selectedJobRowIndex )"
+ ".innerText)"
+ " + '&id=' + document.getElementById( 'j-cellTableCell_' + selectedJobRowIndex ).innerHTML + '&from=0' );" );
out.println( "} else if ( selectedTransRowIndex != -1 ) {" );
out.println( "window.location.replace( '"
+ convertContextPath( GetTransStatusServlet.CONTEXT_PATH ) + "'"
+ " + '?name=' + encodeURIComponent(document.getElementById( 'cellTableFirstCell_' + selectedTransRowIndex )"
+ ".innerText)"
+ " + '&id=' + document.getElementById( 'cellTableCell_' + selectedTransRowIndex ).innerText + '&from=0' );" );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// Click function for remove button
out.println( "function removeFunction( element ) {" );
out.println( "if( !element.classList.contains('toolbar-button-disabled') ) {" );
out.println( "removeElement = element;" );
out.println( "if( element.id.startsWith( 'j-' ) && selectedJobRowIndex != -1 ) {" );
out.println( "openMessageDialog( '" + BaseMessages.getString( PKG, "GetStatusServlet.RemoveJob.Title" ) + "',"
+ "'" + BaseMessages.getString( PKG, "GetStatusServlet.RemoveJob.Confirm.Body" ) + " " + BaseMessages
.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + '?" + "'" + ", false );" );
out.println( "} else if ( selectedTransRowIndex != -1 ) {" );
out.println( "openMessageDialog( '" + BaseMessages.getString( PKG, "GetStatusServlet.RemoveTrans.Title" ) + "',"
+ "'" + BaseMessages.getString( PKG, "GetStatusServlet.RemoveTrans.Confirm.Body" ) + " " + BaseMessages
.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + '?" + "'"
+ ", false );" );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// OnClick function for table element
out.println( "function clickFunction( element, tableClass ) {" );
out.println( "var prefix = element.id.startsWith( 'j-' ) ? 'j-' : '';" );
out.println( "var rowNum = getRowNum( element.id );" );
out.println( "if( tableClass.endsWith( 'Row' ) ) {" );
out.println( "element.className='cellTableRow ' + tableClass + ' cellTableSelectedRow';" );
out.println( "} else {" );
out.println(
"document.getElementById( prefix + 'cellTableFirstCell_' + rowNum ).className='cellTableCell "
+ "cellTableFirstColumn ' + tableClass + ' cellTableSelectedRowCell';" );
out.println( "element.className='cellTableCell ' + tableClass + ' cellTableSelectedRowCell';" );
out.println( "}" );
out.println( "if( element.id.startsWith( 'j-' ) ) {" );
out.println( "document.getElementById( \"j-run-pause\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"j-stop\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"j-view\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"j-close\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "if( selectedJobRowIndex != -1 && rowNum != selectedJobRowIndex ) {" );
out.println(
"document.getElementById( prefix + 'cellTableRow_' + selectedJobRowIndex ).className='cellTableRow ' + "
+ "tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableFirstCell_' + selectedJobRowIndex ).className='cellTableCell "
+ "cellTableFirstColumn ' + tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableCell_' + selectedJobRowIndex ).className='cellTableCell ' + "
+ "tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableLastCell_' + selectedJobRowIndex ).className='cellTableCell "
+ "cellTableLastColumn ' + tableClass;" );
out.println( "}" );
out.println( "selectedJobRowIndex = rowNum;" );
out.println( "} else {" );
out.println( "document.getElementById( \"run-pause\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"stop\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"view\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "document.getElementById( \"close\" ).classList.remove( \"toolbar-button-disabled\" )" );
out.println( "if( selectedTransRowIndex != -1 && rowNum != selectedTransRowIndex ) {" );
out.println(
"document.getElementById( prefix + 'cellTableRow_' + selectedTransRowIndex ).className='cellTableRow ' + "
+ "tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableFirstCell_' + selectedTransRowIndex ).className='cellTableCell "
+ "cellTableFirstColumn ' + tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableCell_' + selectedTransRowIndex ).className='cellTableCell ' + "
+ "tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableLastCell_' + selectedTransRowIndex ).className='cellTableCell "
+ "cellTableLastColumn ' + tableClass;" );
out.println( "}" );
out.println( "selectedTransRowIndex = rowNum;" );
out.println(
"if( document.getElementById( 'cellTableCellStatus_' + selectedTransRowIndex ).innerHTML == 'Running' ) {" );
out.println( "document.getElementById( 'run-pause' ).innerHTML = '<img style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/pause.svg\"/ title=\"" + BaseMessages.getString( PKG, "GetStatusServlet.PauseTrans" )
+ "\">';" );
out.println(
"} else if( document.getElementById( 'cellTableCellStatus_' + selectedTransRowIndex ).innerHTML == 'Paused' )"
+ " {" );
out.println( "document.getElementById( 'run-pause' ).innerHTML = '<img style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/pause.svg\" title=\"" + BaseMessages.getString( PKG, "GetStatusServlet.ResumeTrans" )
+ "\"/>';" );
out.println( "} else {" );
out.println( "document.getElementById( 'run-pause' ).innerHTML = '<img style=\"width: 22px; height: 22px\" src=\""
+ prefix + "/images/run.svg\" title=\"" + run + "\"/>';" );
out.println( "}" );
out.println( "}" );
out.println( "setSelectedNames();" );
out.println( "}" );
// Function to set the trans or job name of the selected trans or job
out.println( "function setSelectedNames() {" );
out.println( " selectedJobName = selectedTransName = \"\";" );
out.println(
" var selectedElementNames = document.getElementsByClassName( \"cellTableFirstColumn "
+ "cellTableSelectedRowCell\" );" );
out.println( " if( selectedElementNames ) {" );
out.println( " for(var i = 0; i < selectedElementNames.length; i++) {" );
out.println( " if(selectedElementNames[i].id.startsWith(\"j-\")) {" );
out.println( " selectedJobName = selectedElementNames[i].innerHTML;" );
out.println( " } else {" );
out.println( " selectedTransName = selectedElementNames[i].innerHTML;" );
out.println( " }" );
out.println( " }" );
out.println( " }" );
out.println( "}" );
// OnMouseEnter function
out.println( "function mouseEnterFunction( element, tableClass ) {" );
out.println( "var prefix = '';" );
out.println( "var rowNum = getRowNum( element.id );" );
out.println( "var selectedIndex = selectedTransRowIndex;" );
out.println( "if( element.id.startsWith( 'j-' ) ) {" );
out.println( "prefix = 'j-';" );
out.println( "selectedIndex = selectedJobRowIndex;" );
out.println( "}" );
out.println( "if( rowNum != selectedIndex ) {" );
out.println( "if( tableClass.endsWith( 'Row' ) ) {" );
out.println( "element.className='cellTableRow ' + tableClass + ' cellTableHoveredRow';" );
out.println( "} else {" );
out.println(
"document.getElementById( prefix + 'cellTableFirstCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell cellTableFirstColumn ' + tableClass + ' cellTableHoveredRowCell';" );
out.println(
"document.getElementById( prefix + 'cellTableCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell ' + tableClass + ' cellTableHoveredRowCell';" );
out.println(
"document.getElementById( prefix + 'cellTableLastCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell cellTableLastColumn ' + tableClass + ' cellTableHoveredRowCell';" );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// OnMouseLeave function
out.println( "function mouseLeaveFunction( element, tableClass ) {" );
out.println( "var prefix = '';" );
out.println( "var rowNum = getRowNum( element.id );" );
out.println( "var selectedIndex = selectedTransRowIndex;" );
out.println( "if( element.id.startsWith( 'j-' ) ) {" );
out.println( "prefix = 'j-';" );
out.println( "selectedIndex = selectedJobRowIndex;" );
out.println( "}" );
out.println( "if( rowNum != selectedIndex ) {" );
out.println( "if( tableClass.endsWith( 'Row' ) ) {" );
out.println( "element.className='cellTableRow ' + tableClass;" );
out.println( "} else {" );
out.println(
"document.getElementById( prefix + 'cellTableFirstCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell cellTableFirstColumn ' + tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell ' + tableClass;" );
out.println(
"document.getElementById( prefix + 'cellTableLastCell_' + element.id.charAt( element.id.length - 1 ) )"
+ ".className='cellTableCell cellTableLastColumn ' + tableClass;" );
out.println( "}" );
out.println( "}" );
out.println( "}" );
// Onclick function for closing message dialog-->make it hidden
out.println( "function closeMessageDialog( refresh ) {" );
out.println( " document.getElementById( \"messageDialogBackdrop\" ).style.visibility = 'hidden';" );
out.println( " document.getElementById( \"messageDialog\" ).style.visibility = 'hidden';" );
out.println( " if( refresh ) {" );
out.println( " window.location.reload();" );
out.println( " }" );
out.println( "}" );
// Function to open the message dialog--> make it visible
out.println( "function openMessageDialog( title, body, single ) {" );
out.println( " document.getElementById( \"messageDialogBackdrop\" ).style.visibility = 'visible';" );
out.println( " document.getElementById( \"messageDialog\" ).style.visibility = 'visible';" );
out.println( " document.getElementById( \"messageDialogTitle\" ).innerHTML = title;" );
out.println( " document.getElementById( \"messageDialogBody\" ).innerHTML = body;" );
out.println( " if( single ) {" );
out.println( " document.getElementById( \"singleButton\" ).style.display = 'block';" );
out.println( " document.getElementById( \"doubleButton\" ).style.display = 'none';" );
out.println( " } else {" );
out.println( " document.getElementById( \"singleButton\" ).style.display = 'none';" );
out.println( " document.getElementById( \"doubleButton\" ).style.display = 'block';" );
out.println( " }" );
out.println( "}" );
// Function to remove selected trans/job after user confirms
out.println( "function removeSelection() {" );
out.println( " if( removeElement !== null ) {" );
out.println( " if( removeElement.id.startsWith( 'j-' ) && selectedJobRowIndex != -1 ) {" );
out.println( setupAjaxCall( setupJobURI( convertContextPath( RemoveJobServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.RemoveJob.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.RemoveJob.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheJob.Label" ) + " ' + selectedJobName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.RemoveJob.Failure.Body" ) + "'" ) );
out.println( "} else if ( selectedTransRowIndex != -1 ) {" );
out.println( setupAjaxCall( setupTransURI( convertContextPath( RemoveTransServlet.CONTEXT_PATH ) ),
BaseMessages.getString( PKG, "GetStatusServlet.RemoveTrans.Title" ),
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.RemoveTrans.Success.Body" ) + "'",
"'" + BaseMessages.getString( PKG, "GetStatusServlet.TheTransformation.Label" ) + " ' + selectedTransName + ' "
+ BaseMessages.getString( PKG, "GetStatusServlet.RemoveTrans.Failure.Body" ) + "'" ) );
out.println( " }" );
out.println( " }" );
out.println( "}" );
out.println( "function getRowNum( id ) {" );
out.println( " return id.substring( id.indexOf('_') + 1, id.length);" );
out.println( "}" );
out.println( "</script>" );
out.println( "</BODY>" );
out.println( "</HTML>" );
}
}
private String encodeUriComponents( String path ) {
return Arrays.stream( path.split( "/" ) )
.map( Encode::forUriComponent )
.collect( Collectors.joining( "/" ) );
}
private static void getSystemInfo( SlaveServerStatus serverStatus ) {
OperatingSystemMXBean operatingSystemMXBean =
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
ThreadMXBean threadMXBean = java.lang.management.ManagementFactory.getThreadMXBean();
RuntimeMXBean runtimeMXBean = java.lang.management.ManagementFactory.getRuntimeMXBean();
int cores = Runtime.getRuntime().availableProcessors();
long freeMemory = Runtime.getRuntime().freeMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
String osArch = operatingSystemMXBean.getArch();
String osName = operatingSystemMXBean.getName();
String osVersion = operatingSystemMXBean.getVersion();
double loadAvg = operatingSystemMXBean.getSystemLoadAverage();
int threadCount = threadMXBean.getThreadCount();
long allThreadsCpuTime = 0L;
long[] threadIds = threadMXBean.getAllThreadIds();
for ( int i = 0; i < threadIds.length; i++ ) {
allThreadsCpuTime += threadMXBean.getThreadCpuTime( threadIds[ i ] );
}
long uptime = runtimeMXBean.getUptime();
serverStatus.setCpuCores( cores );
serverStatus.setCpuProcessTime( allThreadsCpuTime );
serverStatus.setUptime( uptime );
serverStatus.setThreadCount( threadCount );
serverStatus.setLoadAvg( loadAvg );
serverStatus.setOsName( osName );
serverStatus.setOsVersion( osVersion );
serverStatus.setOsArchitecture( osArch );
serverStatus.setMemoryFree( freeMemory );
serverStatus.setMemoryTotal( totalMemory );
}
public String toString() {
return "Status Handler";
}
public String getService() {
return CONTEXT_PATH + " (" + toString() + ")";
}
public String getContextPath() {
return CONTEXT_PATH;
}
private String setupIconEnterLeaveJavascript( String id ) {
return "onMouseEnter=\"if( !document.getElementById('"
+ id + "').classList.contains('toolbar-button-disabled') ) { document.getElementById('"
+ id + "').classList.add('toolbar-button-hovering') }\" onMouseLeave=\"document.getElementById('"
+ id + "').classList.remove('toolbar-button-hovering')\"";
}
private String messageDialog() {
String retVal =
"<div id=\"messageDialogBackdrop\" style=\"visibility: hidden; position: absolute; top: 0; right: 0; bottom: 0;"
+ " left: 0; opacity: 0.5; background-color: #000; z-index: 1000;\"></div>\n";
retVal +=
"<div class=\"pentaho-dialog\" id=\"messageDialog\" style=\"visibility: hidden; margin: 0; position: absolute; "
+ "top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%);"
+ "-webkit-transform: translate(-50%, -50%); padding: 30px; height: auto; width: 423px; border: 1px solid "
+ "#CCC; -webkit-box-shadow: none; -moz-box-shadow: none;"
+ "box-shadow: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; "
+ "overflow: hidden; line-height: 20px; background-color: #FFF; z-index: 10000;\">\n";
retVal += "<div id=\"messageDialogTitle\" class=\"Caption\"></div>\n";
retVal += "<div id=\"messageDialogBody\" class=\"dialog-content\"></div>\n";
retVal +=
"<div id=\"singleButton\" style=\"margin-top: 30px;\">\n<button class=\"pentaho-button\" style=\"float: right;"
+ "\" onclick=\"closeMessageDialog( true );\">\n<span>"
+ BaseMessages.getString( PKG, "GetStatusServlet.Button.OK" ) + "</span>\n</button>\n</div>\n";
retVal +=
"<div id=\"doubleButton\" style=\"margin-top: 30px;\">\n<button class=\"pentaho-button\" style=\"float: right; "
+ "margin-left: 10px;\" onclick=\"closeMessageDialog( false );\">\n<span>"
+ BaseMessages.getString( PKG, "GetStatusServlet.Button.No" )
+ "</span>\n</button>\n<button class=\"pentaho-button\" style=\"float: right;\" onclick=\"closeMessageDialog("
+ " false ); removeSelection();\">\n<span>"
+ BaseMessages.getString( PKG, "GetStatusServlet.Button.YesRemove" ) + "</span>\n</button>\n</div>\n";
retVal += "</div>\n";
return retVal;
}
private String setupAjaxCall( String uri, String title, String success, String failure ) {
String retVal = "";
retVal += "var xhttp = new XMLHttpRequest();\n";
retVal += "xhttp.onreadystatechange = function() {\n";
retVal += " if ( this.readyState === 4 ) {\n";
retVal += " if ( this.status === 200 ) {\n";
retVal += " openMessageDialog( '" + title + "', " + success + ", true );\n";
retVal += " } else {\n";
retVal += " openMessageDialog( '" + BaseMessages.getString( PKG, "GetStatusServlet.UnableTo.Label" )
+ " " + title + "', " + failure + ", true );\n";
retVal += " }\n";
retVal += " }\n";
retVal += "};\n";
retVal += "xhttp.open( \"GET\", " + uri + ", true );\n";
retVal += "xhttp.send();\n";
return retVal;
}
private String setupTransURI( String context ) {
return "'" + context + "'"
+ " + '?name=' + encodeURIComponent(document.getElementById( 'cellTableFirstCell_' + selectedTransRowIndex )"
+ ".innerText)"
+ " + '&id=' + document.getElementById( 'cellTableCell_' + selectedTransRowIndex ).innerText";
}
private String setupJobURI( String context ) {
return "'" + context + "'"
+ " + '?name=' + encodeURIComponent(document.getElementById( 'j-cellTableFirstCell_' + selectedJobRowIndex )"
+ ".innerText)"
+ " + '&id=' + document.getElementById( 'j-cellTableCell_' + selectedJobRowIndex ).innerText";
}
}
| pentaho/pentaho-kettle | engine/src/main/java/org/pentaho/di/www/GetStatusServlet.java |
45,325 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.vaticle.typedb.core.database;
import com.vaticle.typedb.core.encoding.key.Key;
import org.rocksdb.BlockBasedTableConfig;
import org.rocksdb.BloomFilter;
import org.rocksdb.ColumnFamilyOptions;
import org.rocksdb.DBOptions;
import org.rocksdb.IndexType;
import org.rocksdb.LRUCache;
import org.rocksdb.Statistics;
import org.rocksdb.UInt64AddOperator;
import static com.vaticle.typedb.common.collection.Collections.list;
import static com.vaticle.typedb.core.common.collection.Bytes.KB;
import static com.vaticle.typedb.core.common.collection.Bytes.MB;
import static org.rocksdb.CompressionType.LZ4_COMPRESSION;
import static org.rocksdb.CompressionType.NO_COMPRESSION;
public class RocksConfiguration {
private final Schema schemaOptions;
private final Data dataOptions;
private final boolean loggingEnabled;
public RocksConfiguration(long dataCacheSize, long indexCacheSize, boolean loggingEnabled, int logStatisticsPeriodSec) {
this.schemaOptions = new Schema();
this.dataOptions = new Data(dataCacheSize, indexCacheSize, loggingEnabled, logStatisticsPeriodSec);
this.loggingEnabled = loggingEnabled;
}
public Schema schema() {
return schemaOptions;
}
public Data data() {
return dataOptions;
}
public boolean isLoggingEnabled() {
return loggingEnabled;
}
public static class Schema {
public org.rocksdb.DBOptions dbOptions() {
return new DBOptions().setCreateIfMissing(true);
}
/**
* WARNING: we can break backward compatibility or corrupt user data by changing these options and using them
* with existing databases
*/
public org.rocksdb.ColumnFamilyOptions defaultCFOptions() {
return new org.rocksdb.ColumnFamilyOptions()
.setCompressionType(NO_COMPRESSION)
.setTableFormatConfig(defaultCFTableOptions());
}
private BlockBasedTableConfig defaultCFTableOptions() {
BlockBasedTableConfig rocksDBTableOptions = new BlockBasedTableConfig();
LRUCache uncompressedCache = new LRUCache(64 * MB);
rocksDBTableOptions.setBlockSize(16 * KB);
rocksDBTableOptions.setFormatVersion(5);
rocksDBTableOptions.setIndexBlockRestartInterval(16);
rocksDBTableOptions.setEnableIndexCompression(false);
rocksDBTableOptions.setBlockCache(uncompressedCache);
return rocksDBTableOptions;
}
}
static class Data {
private final LRUCache blockCache;
private final boolean logStatistics;
private final int logStatisticsPeriodSec;
Data(long dataCacheSize, long indexCacheSize, boolean logStatistics, int logStatisticsPeriodSec) {
this.blockCache = lruCache(dataCacheSize, indexCacheSize);
this.logStatistics = logStatistics;
this.logStatisticsPeriodSec = logStatisticsPeriodSec;
}
/**
* Even a moderate block cache has a huge performance impact -- disabled vs enabled (800MB) block cache leads to a 20% reduction
* in load time. However, there is a memory cost of about 2x the set cache size for using the cache size. So for example,
* setting a 1GB block cache will lead to 2GB of ram usage during operation, from empirical tests.
*
* From various sources (https://smalldatum.blogspot.com/2016/09/tuning-rocksdb-block-cache.html is an explicit guideline)
* when most data/working data subset doesn't fit into memory, it is best to give the block cache around 20% of the total memory,
* and let the OS use the remaining space to prefetch and buffer pages read from disk.
*
* This guide also has a comment outlining that the compressed cache is not commonly used and note widely tested,
* and it is better to let the OS handle pre-fetching pages from disk.
*
* Note: the ClockCache exposed in the JNI does not work: setting a 1GB clock cache still leads to an 8MB cache size.
* In addition, the ClockCache should not be used in production, due to a critical bug that is known:
* https://github.com/facebook/rocksdb/wiki/Block-Cache.
*
* We set aside a portion of the cache for high-priority blocks such as index/bloom filter structures, otherwise we get
* unacceptable cache thrashing and a performance drop.
*/
private static LRUCache lruCache(long dataCacheSize, long indexCacheSize) {
long blockCacheSize = dataCacheSize + indexCacheSize;
float indexAndFilterRatio = ((float) indexCacheSize) / (blockCacheSize);
// block cache will contain data, plus space reserved for index and bloom filters to make memory usage predictable
return new LRUCache(blockCacheSize, -1, false, indexAndFilterRatio);
}
org.rocksdb.DBOptions dbOptions() {
DBOptions dbOptions = new DBOptions().setCreateIfMissing(true);
configureWriteConcurrency(dbOptions);
if (logStatistics) configureStatistics(dbOptions);
return dbOptions;
}
/**
* By default RocksDB uses 1 thread for flush and 1 thread for compaction. We can give RocksDB permission to use many threads
* for background jobs (eg. compaction and flush) with `maxBackgroundJobs`.
*
* To help relieve write stalls due to compaction at the higher levels (L0 -> L1 is single threaded), we can allow subcompactions
* by setting max subcompaction threads to a value higher than 0 as well.
*
* To enable higher memtable throughput we can set `concurrentMemtableWrite` to `true`, along with a `enableWriteThreadAdaptiveYield`,
* though we have not provably seen much benefit from these.
*/
private void configureWriteConcurrency(DBOptions options) {
options.setMaxSubcompactions(CoreDatabaseManager.MAX_THREADS).setMaxBackgroundJobs(CoreDatabaseManager.MAX_THREADS)
.setEnableWriteThreadAdaptiveYield(true)
.setAllowConcurrentMemtableWrite(true);
}
/**
* We can make RocksDB print statistics for block cache, filtering, get/write timing statistics, we have to set two options:
* `setStatistics(new Statistics())` is required, and one can read the the Java statistics option to get the values back.
* However, if we want RocksDB to print the statistics into its own LOG file with `statsDumpPeriodSec`.
*/
private void configureStatistics(DBOptions options) {
options.setStatistics(new Statistics());
options.setStatsDumpPeriodSec(logStatisticsPeriodSec);
}
/*
######## Column Family Configuration ########
Each column family maintains a separate LSM tree, memtables, compaction, compression options, etc.
*/
/**
* WARNING: we can break backward compatibility or corrupt user data by changing these options and using them
* with existing databases
*
* The default CF contains vertices. We optimise for point lookups with whole key bloom filters
* Since this will contain attributes we make larger write buffers
*/
org.rocksdb.ColumnFamilyOptions defaultCFOptions() {
org.rocksdb.ColumnFamilyOptions options = new org.rocksdb.ColumnFamilyOptions();
writeOptimisedWriteBuffers(options);
configureSST(options);
configureCompression(options);
options.setTableFormatConfig(tableOptions(true, true));
return options;
}
/**
* This CF contains edges starting from attributes, which cannot be optimised with prefix filters
* and we rarely do edge lookups in their entirety, so we disable whole key filters as well
* Since this will contain attributes (attribute -> owner) we make larger write buffers
*/
public ColumnFamilyOptions variableStartEdgeCFOptions() {
org.rocksdb.ColumnFamilyOptions options = new org.rocksdb.ColumnFamilyOptions();
writeOptimisedWriteBuffers(options);
configureSST(options);
configureCompression(options);
options.setTableFormatConfig(tableOptions(false, false));
return options;
}
/**
* This CF contains edges starting not starting from attributes, which can be prefix filtered
* Since this will contain attributes (owner -> attribute) we make larger write buffers
*/
org.rocksdb.ColumnFamilyOptions fixedStartEdgeCFOptions() {
org.rocksdb.ColumnFamilyOptions options = new org.rocksdb.ColumnFamilyOptions();
writeOptimisedWriteBuffers(options);
configureSST(options);
configureCompression(options);
configurePrefixExtractor(options, Key.Partition.FIXED_START_EDGE.fixedStartBytes().get());
options.setTableFormatConfig(tableOptions(true, false));
return options;
}
org.rocksdb.ColumnFamilyOptions optimisationEdgeCFOptions() {
org.rocksdb.ColumnFamilyOptions options = new org.rocksdb.ColumnFamilyOptions();
readOptimisedWriteBuffers(options);
configureSST(options);
configureCompression(options);
configurePrefixExtractor(options, Key.Partition.OPTIMISATION_EDGE.fixedStartBytes().get());
options.setTableFormatConfig(tableOptions(true, false));
return options;
}
org.rocksdb.ColumnFamilyOptions metadataCFOptions() {
org.rocksdb.ColumnFamilyOptions options = new org.rocksdb.ColumnFamilyOptions();
readOptimisedWriteBuffers(options);
configureSST(options);
configureCompression(options);
configureMergeOperator(options);
BlockBasedTableConfig rocksDBTableOptions = new BlockBasedTableConfig();
configureBlocks(rocksDBTableOptions);
rocksDBTableOptions.setEnableIndexCompression(false);
rocksDBTableOptions.setWholeKeyFiltering(false);
rocksDBTableOptions.setBlockCache(new LRUCache(8 * MB));
rocksDBTableOptions.setPinL0FilterAndIndexBlocksInCache(true);
rocksDBTableOptions.setPinTopLevelIndexAndFilter(false);
rocksDBTableOptions.setCacheIndexAndFilterBlocksWithHighPriority(false);
configureBlocks(rocksDBTableOptions);
return options;
}
private BlockBasedTableConfig tableOptions(boolean enableFilter, boolean enableWholeKeyFilter) {
assert enableFilter || !enableWholeKeyFilter;
BlockBasedTableConfig rocksDBTableOptions = new BlockBasedTableConfig();
configureBlocks(rocksDBTableOptions);
rocksDBTableOptions.setEnableIndexCompression(false);
rocksDBTableOptions.setBlockCache(blockCache);
if (enableFilter) configureBloomFilter(rocksDBTableOptions);
rocksDBTableOptions.setWholeKeyFiltering(enableWholeKeyFilter);
return rocksDBTableOptions;
}
/**
* Much of this information comes from: https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide
*
* Write buffers determine how much unsorted, uncompacted data is kept in memory before being flushed to L0.
*
* Tradeoff: the more we can delay compaction and accumulate writes in the write buffer, the faster our pure write speed.
* However, through this process we lose reads, since the data is unsorted.
*
* We increase the default 64Mb to 128MB write buffer, and set the number of write buffers maximum to 4 from the default of 2.
* This means we can have up to 512MB of unsorted data in memory in this cf. This gives a decent tradeoff between write speed, memory usage,
* and read speed. The more write buffers there are, the slower reads: for each read, all write buffers have to be checked.
*
* To achieve the best performance, we should match the size of L1 with the size of L0. To do this we should set
* `maxBytesForLevelBase` to the number of write buffers * size of memtable. This makes L0 -> L1 compactions fast as possible,
* which is a single-threaded operation that doesn't scale very well. So in addition, the larger we make L0/L1, the
* more we rely on the single-threaded compaction during contious loading/mixed read-write operation.
*
* According to the option documentation (https://javadoc.io/static/org.rocksdb/rocksdbjni/6.25.3/org/rocksdb/Options.html)
* `maxWriteBufferNumberToMaintain`, is used to control how long _old_ write buffers are retained for conflict checking
* open snapshots against past writes. Given that in TypeDB we perform our own consistency checks,
* we do not need to keep any at all, freeing up memory. So, we should always set it to 0.
*
* With 4x128MB write buffers, with concurrent memtable writes and adaptive yield, during a bulk load we saw only
* 25 seconds of stalling in 8 hours of data loading. Stalls are also only really seen when doing straight writes,
* without mixed reads (the norm).
*/
private void writeOptimisedWriteBuffers(ColumnFamilyOptions options) {
configureWriteBuffersAndL1(options, 128 * MB, 4);
}
private void readOptimisedWriteBuffers(ColumnFamilyOptions options) {
configureWriteBuffersAndL1(options, 64 * MB, 2);
}
private void configureWriteBuffersAndL1(ColumnFamilyOptions options, long writeBufferSize, int writeBuffersMaxCount) {
options.setWriteBufferSize(writeBufferSize)
.setMaxWriteBufferNumber(writeBuffersMaxCount)
// don't maintain any old write buffers since we handle key conflict detection ourselves
.setMaxWriteBufferNumberToMaintain(0)
// L1 should match L0 size for best performance, since L0 -> L1 compaction is single threaded
.setMaxBytesForLevelBase(writeBufferSize * writeBuffersMaxCount);
}
/**
* SST Size
* By default, RocksDB will use a 64MB SST size, constant on each level (we could set a multiplier `targetFileSizeMultiplier`,
* but we use RocksDB defaults here). We can use `targetFileSizeBase` to set the SST size for L0. This affects compaction
* and bloom filters if we set them (larger SST = higher false positive rate in bloom filters).
*
* With a 64MB SST file, and 50 byte keys on average and no compression, an SST will contain on average 1.2 million keys.
* With 4x compression (like from LZ4), we fit 5 million keys into a 64MB SST.
*
* Note: with 64MB SST files, if we have a max_open_files from the OS of 1024, we can only end up with a 64GB data set, etc.
* As such, we should clearly tell the users to configure the max open files to be around 48k (~ enough for 3TB of data)
*/
private void configureSST(ColumnFamilyOptions options) {
options
// explicitly set SST file size to avoid relying on RocksDB defaults that could change
.setTargetFileSizeBase(64 * MB);
}
/**
* Without much evidence to support the best file size, we follow RocksDB's default of 64MB SST files.
*
* Compression
* We tested with various compression levels. Not having any compression leads to an approximately 5x write amplification
* when comparing an uncompressed CSV source to the database size. However, a compressed CSV compared to an uncompressed
* database is a 20x write amplification!
*
* There are many compression options available in RocksDB. The best "heavy" compression is ZLIB, and the best "light"
* compression is LZ4. ZLIB comes with a heavy penalty of about 20% performance, and compresses data by 7x.
* LZ4 has no noticable cost, and compresses data by about 3x, and great compression and decompression speeds (https://github.com/lz4/lz4).
*
* It may actually be true for us that compression on some level pays for itself in terms of cost: the OS will keep
* pages from memory cached under the hood. If the data is compressed, more data can be kept in memory by the OS,
* leading to less disk access and faster overall performance. This hasn't been observed yet, but may already be in play
* which leads to LZ4 compression having "no" visible performance impact.
*
* We end up using the same settings as RockSet (https://rockset.com/blog/how-we-use-rocksdb-at-rockset/), by setting
* no compression on L0 and L1, where a many smaller sets of data flow through rapidly before being written into lower levels,
* and using lightweight LZ4 compression below that (levels 2 to 7).
*
* Following RocksDB advise at https://github.com/facebook/rocksdb/wiki/Space-Tuning, we should disable
* index compression, to make sure indexes are always rapidly accessible (at the expense of some CPU and memory).
*/
private void configureCompression(ColumnFamilyOptions options) {
options
// best performance-space tradeoff: apply lightweight LZ4 compression to levels that change less
.setCompressionPerLevel(list(NO_COMPRESSION, NO_COMPRESSION, LZ4_COMPRESSION, LZ4_COMPRESSION,
LZ4_COMPRESSION, LZ4_COMPRESSION, LZ4_COMPRESSION));
}
/**
* Statistics requires a merge operator
*/
private void configureMergeOperator(ColumnFamilyOptions options) {
options.setMergeOperator(new UInt64AddOperator());
}
/**
* Note that when using a prefix extractor, when iteratoring over a prefix shorter than the extractor,
* we just disable prefix checks else rocks may return invalid answers. This can be automated with
* ReadOptions.setAutoPrefixMode(true). However, this is not available in RocksDBJNI yet! So we have to
* manually disable by using ReadOptions.setTotalOrderSeek(true) when iteratoring over a shorter prefix than
* the bloom prefix extractor.
*
* We can change the prefix extractor on reboot, and old prefix filters will be ignored by RocksDB automatically
*/
private void configurePrefixExtractor(ColumnFamilyOptions options, int prefixLength) {
options.useFixedLengthPrefixExtractor(prefixLength);
}
/**
* The default RocksDB block size is 4KB. We increase it to 16KB - the larger the data blocks, the smaller the overall size
* of indexes in the database. However, if the block is too large, doing a point lookup of a particular key can cost more
* if it is not already in memory, since we have to fetch the entire 16KB block first!
*
* The rough formula for index size is `~= (database size / block size) * avg key size`. See https://github.com/facebook/rocksdb/issues/719
* for the source of the equation. In general, we see that around 1% of data size is index size, and the index should live in memory.
* The larger the block size, the less memory we require for index structures.
*/
private void configureBlocks(BlockBasedTableConfig rocksDBTableOptions) {
// hardcode block size and format version to avoid relying on RocksDB defaults that could change
rocksDBTableOptions.setBlockSize(16 * KB);
rocksDBTableOptions.setFormatVersion(5);
rocksDBTableOptions.setIndexBlockRestartInterval(16);
}
/**
* A bloom filter has a similar performance impact (~20%) to a block cache, but the memory cost grows linearly for optimal performance.
*
* We can estimate the footprint of bloom filters with: `num_keys * per_key_bloom_size`. In a test, we loaded 150 million
* concepts, which turned into 1.7 billion keys, into a 22GB rocks database with LZ4 compression. The size of the bloom
* with 10 bits per key is filter is predicted to be 17 billion bits ~= 2 billion bytes = 2 GB of data. The actual test
* gave 1.8GB of space for bloom filters, so this is a good predictor.
*
* Note that in a compressed 22GB rocks database, we end up with 5-10% of data as bloom filter.
*
* _There is a huge penalty_ if the bloom filters do not entirely fit into memory. However, to avoid a ballooning memory
* footprint, we want to restrict the filters to fit into a predictable memory size. This is done with
* `cacheIndexAndFilterBlocksWithHighPriority`, and setting aside a part of the block cache for filter/index blocks.
*
* However, if the cache is not large enough, we get a 10x performance drop. To help with this, Rocks introduced filter
* partitioning, which introduces an index over the bloom filters. To utilise this, one must also set
* `indexType(kTwoLevelIndexSearch)` with `partitionFilters`. Using this, along with `cacheIndexAndFilterBlocksWithHighPriority` and
* the further option `pinTopLevelIndexAndFilter` which keeps indexes and filter partitions in the cache,
* we can keep good performance when the bloom filters don't ALL fit in memory, and only the partitions do.
* With these settings, we find a minimal performance drop when memory startings being restricted to a
* reasonable level.
*
* *Bloom filter efficiency*: with "full" bloom filters, where one filter is compute per SST, and 64MB files,
* and LZ4 compression that gives a 4x compression ratio, we end up with about 5 million keys per file.
* With 10 bits per key we end up with 50 mil bits = 6 mil bytes = 6MB bloom filter per file (10%, empirically
* confirmed). Using online calculators, we can confirm 10 bits per keys gives a good false positive rate 1%.
* So if we do enable bloom filters, 10 bits per key given 10 million keys per SST is a good tradeoff. 8 bits per key
* leads to 5MB filter, and a 2% false positive rate, which is still good.
*
* *Prefix filter*: we see a solid performance increase (> 10%) when enabling bloom filters for prefixes compared
* to just full-key filters.
* Note: prefix extractors are defined directly on Options, not tableOptions
*/
private void configureBloomFilter(BlockBasedTableConfig rocksDBTableOptions) {
// bloom filter is important for good random-read performance
rocksDBTableOptions.setFilterPolicy(new BloomFilter(10, false));
// partition bloom filters to avoid needing to have all bloom filters reside in memory - only index over blooms must
rocksDBTableOptions.setPartitionFilters(true);
// WARNING: this must be set to make partitioned filters take effect
rocksDBTableOptions.setIndexType(IndexType.kTwoLevelIndexSearch);
rocksDBTableOptions.setOptimizeFiltersForMemory(true);
// ensure that the bloom filter partitioning index, plus the data index live in the cache always
rocksDBTableOptions.setPinTopLevelIndexAndFilter(true);
// L0 index/filter should always be in memory, and is small
rocksDBTableOptions.setPinL0FilterAndIndexBlocksInCache(true);
// to cap memory usage, we must pin filter blocks and indexes in memory
rocksDBTableOptions.setCacheIndexAndFilterBlocks(true);
// use reserved section of block cache for blooms/index - cause massive thrashing if not using the high priority cache section
// WARNING: must configure block cache with a reserved region for high priority blocks
rocksDBTableOptions.setCacheIndexAndFilterBlocksWithHighPriority(true);
}
}
}
| vaticle/typedb | database/RocksConfiguration.java |
45,326 | /**
* $Id: EmbedServlet.java,v 1.18 2014/01/31 22:27:07 gaudenz Exp $
* Copyright (c) 2011-2012, JGraph Ltd
*
* TODO
*
* We could split the static part and the stencils into two separate requests
* in order for multiple graphs in the pages to not load the static part
* multiple times. This is only relevant if the embed arguments are different,
* in which case there is a problem with parsin the graph model too soon, ie.
* before certain stencils become available.
*
* Easier solution is for the user to move the embed script to after the last
* graph in the page and merge the stencil arguments.
*
* Note: The static part is roundly 105K, the stencils are much smaller in size.
* This means if the embed function is widely used, it will make sense to factor
* out the static part because only stencils will change between pages.
*/
package com.mxgraph.online;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.text.StringEscapeUtils;
import com.google.appengine.api.utils.SystemProperty;
import com.mxgraph.online.Utils.SizeLimitExceededException;
/**
* Servlet implementation class OpenServlet
*/
public class EmbedServlet2 extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
protected static String SHAPES_PATH = "/shapes";
/**
*
*/
protected static String STENCIL_PATH = "/stencils";
/**
*
*/
protected static String lastModified = null;
/**
*
*/
protected HashMap<String, String> stencils = new HashMap<String, String>();
/**
*
*/
protected HashMap<String, String[]> libraries = new HashMap<String, String[]>();
/**
* @see HttpServlet#HttpServlet()
*/
public EmbedServlet2()
{
if (lastModified == null)
{
// Uses deployment date as lastModified header
String applicationVersion = SystemProperty.applicationVersion.get();
Date uploadDate = new Date(Long
.parseLong(applicationVersion
.substring(applicationVersion.lastIndexOf(".") + 1))
/ (2 << 27) * 1000);
DateFormat httpDateFormat = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
lastModified = httpDateFormat.format(uploadDate);
}
initLibraries(libraries);
}
/**
* Sets up collection of stencils
*/
public static void initLibraries(HashMap<String, String[]> libraries)
{
libraries.put("mockup",
new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" });
libraries.put("arrows2", new String[] { SHAPES_PATH + "/mxArrows.js" });
libraries.put("bpmn",
new String[] { SHAPES_PATH + "/bpmn/mxBpmnShape2.js",
STENCIL_PATH + "/bpmn.xml" });
libraries.put("er", new String[] { SHAPES_PATH + "/er/mxER.js" });
libraries.put("ios",
new String[] { SHAPES_PATH + "/mockup/mxMockupiOS.js" });
libraries.put("rackGeneral",
new String[] { SHAPES_PATH + "/rack/mxRack.js",
STENCIL_PATH + "/rack/general.xml" });
libraries.put("rackF5", new String[] { STENCIL_PATH + "/rack/f5.xml" });
libraries.put("lean_mapping",
new String[] { SHAPES_PATH + "/mxLeanMap.js",
STENCIL_PATH + "/lean_mapping.xml" });
libraries.put("basic", new String[] { SHAPES_PATH + "/mxBasic.js",
STENCIL_PATH + "/basic.xml" });
libraries.put("ios7icons",
new String[] { STENCIL_PATH + "/ios7/icons.xml" });
libraries.put("ios7ui",
new String[] { SHAPES_PATH + "/ios7/mxIOS7Ui.js",
STENCIL_PATH + "/ios7/misc.xml" });
libraries.put("android", new String[] { SHAPES_PATH + "/mxAndroid.js",
STENCIL_PATH + "electrical/transmission" });
libraries.put("electrical/transmission",
new String[] { SHAPES_PATH + "/mxElectrical.js",
STENCIL_PATH + "/electrical/transmission.xml" });
libraries.put("mockup/buttons",
new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" });
libraries.put("mockup/containers",
new String[] { SHAPES_PATH + "/mockup/mxMockupContainers.js" });
libraries.put("mockup/forms",
new String[] { SHAPES_PATH + "/mockup/mxMockupForms.js" });
libraries.put("mockup/graphics",
new String[] { SHAPES_PATH + "/mockup/mxMockupGraphics.js",
STENCIL_PATH + "/mockup/misc.xml" });
libraries.put("mockup/markup",
new String[] { SHAPES_PATH + "/mockup/mxMockupMarkup.js" });
libraries.put("mockup/misc",
new String[] { SHAPES_PATH + "/mockup/mxMockupMisc.js",
STENCIL_PATH + "/mockup/misc.xml" });
libraries.put("mockup/navigation",
new String[] { SHAPES_PATH + "/mockup/mxMockupNavigation.js",
STENCIL_PATH + "/mockup/misc.xml" });
libraries.put("mockup/text",
new String[] { SHAPES_PATH + "/mockup/mxMockupText.js" });
libraries.put("floorplan",
new String[] { SHAPES_PATH + "/mxFloorplan.js",
STENCIL_PATH + "/floorplan.xml" });
libraries.put("bootstrap",
new String[] { SHAPES_PATH + "/mxBootstrap.js",
STENCIL_PATH + "/bootstrap.xml" });
libraries.put("gmdl", new String[] { SHAPES_PATH + "/mxGmdl.js",
STENCIL_PATH + "/gmdl.xml" });
libraries.put("cabinets", new String[] { SHAPES_PATH + "/mxCabinets.js",
STENCIL_PATH + "/cabinets.xml" });
libraries.put("archimate",
new String[] { SHAPES_PATH + "/mxArchiMate.js" });
libraries.put("archimate3",
new String[] { SHAPES_PATH + "/mxArchiMate3.js" });
libraries.put("sysml", new String[] { SHAPES_PATH + "/mxSysML.js" });
libraries.put("eip", new String[] { SHAPES_PATH + "/mxEip.js",
STENCIL_PATH + "/eip.xml" });
libraries.put("networks", new String[] { SHAPES_PATH + "/mxNetworks.js",
STENCIL_PATH + "/networks.xml" });
libraries.put("aws3d", new String[] { SHAPES_PATH + "/mxAWS3D.js",
STENCIL_PATH + "/aws3d.xml" });
libraries.put("pid2inst",
new String[] { SHAPES_PATH + "/pid2/mxPidInstruments.js" });
libraries.put("pid2misc",
new String[] { SHAPES_PATH + "/pid2/mxPidMisc.js",
STENCIL_PATH + "/pid/misc.xml" });
libraries.put("pid2valves",
new String[] { SHAPES_PATH + "/pid2/mxPidValves.js" });
libraries.put("pidFlowSensors",
new String[] { STENCIL_PATH + "/pid/flow_sensors.xml" });
libraries.put("emoji",
new String[] { SHAPES_PATH + "/emoji/mxEmoji.js" });
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
String qs = request.getQueryString();
if (qs != null && qs.equals("stats"))
{
writeStats(response);
}
else
{
// Checks or sets last modified date of delivered content.
// Date comparison not needed. Only return 304 if
// delivered by this servlet instance.
String modSince = request.getHeader("If-Modified-Since");
if (modSince != null && modSince.equals(lastModified)
&& request.getParameter("fetch") == null)
{
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
else
{
writeEmbedResponse(request, response);
}
}
}
catch (SizeLimitExceededException e)
{
response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
throw e;
}
catch (Exception e)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
throw e;
}
}
public void writeEmbedResponse(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setStatus(HttpServletResponse.SC_OK);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/javascript; charset=UTF-8");
response.setHeader("Last-Modified", lastModified);
if (request.getParameter("fetch") != null)
{
response.setHeader("Cache-Control", "no-store");
}
OutputStream out = response.getOutputStream();
// Creates XML for stencils
PrintWriter writer = new PrintWriter(out);
// Writes JavaScript and adds function call with
// stylesheet and stencils as arguments
writer.println(createEmbedJavaScript(request));
writer.flush();
writer.close();
}
public String createEmbedJavaScript(HttpServletRequest request)
throws IOException
{
String sparam = request.getParameter("s");
String dev = request.getParameter("dev");
StringBuffer result = new StringBuffer("[");
StringBuffer js = new StringBuffer("");
// Processes each stencil only once
HashSet<String> done = new HashSet<String>();
// Processes each lib only once
HashSet<String> libsLoaded = new HashSet<String>();
if (sparam != null)
{
String[] names = sparam.split(";");
for (int i = 0; i < names.length; i++)
{
if (names[i].indexOf("..") < 0 && !done.contains(names[i]) && names[i].length() > 0)
{
if (names[i].equals("*"))
{
js.append(readXmlFile("/js/shapes-14-6-5.min.js", false));
result.append(
"'" + readXmlFile("/stencils.xml", true) + "'");
}
else
{
// Makes name canonical
names[i] = new File("/" + names[i]).getCanonicalPath().substring(1);
// Checks if any JS files are associated with the library
// name and injects the JS into the page
String[] libs = libraries.get(names[i]);
if (libs != null)
{
for (int j = 0; j < libs.length; j++)
{
if (!libsLoaded.contains(libs[j]))
{
String tmp = stencils.get(libs[j]);
libsLoaded.add(libs[j]);
if (tmp == null)
{
try
{
tmp = readXmlFile(libs[j],
!libs[j].toLowerCase()
.endsWith(".js"));
// Cache for later use
if (tmp != null)
{
stencils.put(libs[j], tmp);
}
}
catch (NullPointerException e)
{
// This seems possible according to access log so ignore stencil
}
}
if (tmp != null)
{
// TODO: Add JS to Javascript code inline. This had to be done to quickly
// add JS-based dynamic loading to the existing embed setup where everything
// dynamic is passed via function call, so an indirection via eval must be
// used even though the JS could be parsed directly by adding it to JS.
if (libs[j].toLowerCase()
.endsWith(".js"))
{
js.append(tmp);
}
else
{
if (result.length() > 1)
{
result.append(",");
}
result.append("'" + tmp + "'");
}
}
}
}
}
else
{
String tmp = stencils.get(names[i]);
if (tmp == null)
{
try
{
tmp = readXmlFile(
"/stencils/" + names[i] + ".xml",
true);
// Cache for later use
if (tmp != null)
{
stencils.put(names[i], tmp);
}
}
catch (NullPointerException e)
{
// This seems possible according to access log so ignore stencil
}
}
if (tmp != null)
{
if (result.length() > 1)
{
result.append(",");
}
result.append("'" + tmp + "'");
}
}
}
done.add(names[i]);
}
}
}
result.append("]");
// LATER: Detect protocol of request in dev
// mode to avoid security errors
String proto = "https://";
String setCachedUrls = "";
String[] urls = request.getParameterValues("fetch");
if (urls != null)
{
HashSet<String> completed = new HashSet<String>();
int sizeLimit = Utils.MAX_SIZE;
for (int i = 0; i < urls.length; i++)
{
// Checks if URL already fetched to avoid duplicates
if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i]))
{
completed.add(urls[i]);
URL url = new URL(urls[i]);
URLConnection connection = url.openConnection();
((HttpURLConnection) connection).setInstanceFollowRedirects(false);
connection.setRequestProperty("User-Agent", "draw.io");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
String contentLength = connection.getHeaderField("Content-Length");
// If content length is available, use it to enforce maximum size
if (contentLength != null && Long.parseLong(contentLength) > sizeLimit)
{
break;
}
sizeLimit -= Utils.copyRestricted(connection.getInputStream(), stream);
setCachedUrls += "GraphViewer.cachedUrls['"
+ StringEscapeUtils.escapeEcmaScript(urls[i])
+ "'] = decodeURIComponent('"
+ StringEscapeUtils.escapeEcmaScript(
Utils.encodeURIComponent(
stream.toString("UTF-8"),
Utils.CHARSET_FOR_URL_ENCODING))
+ "');";
}
}
}
// Installs a callback to load the stencils after the viewer was injected
return "window.onDrawioViewerLoad = function() {" + setCachedUrls
+ "mxStencilRegistry.parseStencilSets(" + result.toString()
+ ");" + js + "GraphViewer.processElements(); };"
+ "var t = document.getElementsByTagName('script');"
+ "if (t != null && t.length > 0) {"
+ "var script = document.createElement('script');"
+ "script.type = 'text/javascript';" + "script.src = '" + proto
+ ((dev != null && dev.equals("1")) ? "test" : "www")
+ ".draw.io/js/viewer-static.min.js';"
+ "t[0].parentNode.appendChild(script);}";
}
public void writeStats(HttpServletResponse response) throws IOException
{
PrintWriter writer = new PrintWriter(response.getOutputStream());
writer.println("<html>");
writer.println("<body>");
writer.println("Deployed: " + lastModified);
writer.println("</body>");
writer.println("</html>");
writer.flush();
}
public String readXmlFile(String filename, boolean xmlContent)
throws IOException
{
String result = readFile(filename);
if (xmlContent)
{
result = result.replaceAll("'", "\\\\'").replaceAll("\t", "")
.replaceAll("\n", "");
}
return result;
}
public String readFile(String filename) throws IOException
{
InputStream is = getServletContext().getResourceAsStream(filename);
return Utils.readInputStream(is);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/EmbedServlet2.java |
45,327 | 404: Not Found | sohutv/cachecloud | cachecloud-web/src/main/java/com/sohu/cache/util/EnvUtil.java |
45,328 | /**
* Copyright (c) 2006-2016, JGraph Ltd
* Copyright (c) 2006-2016, Gaudenz Alder
*/
package com.mxgraph.online;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
*
* String/byte array encoding/manipulation utilities
*
*/
public class Utils
{
private static SecureRandom randomSecure = new SecureRandom();
/**
*
*/
public static String CHARSET_FOR_URL_ENCODING = "ISO-8859-1";
/**
*
*/
public static int MAX_SIZE = 20 * 1024 * 1024; // 20 MB
/**
*
*/
public static final int IO_BUFFER_SIZE = 4 * 1024;
/**
* Alphabet for global unique IDs.
*/
public static final String TOKEN_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
private static Set<Integer> allowedPorts = new HashSet<>();
static {
// -1 is for no port urls (ports 80, 443)
allowedPorts.add(-1);
String allowedPortsStr = System.getenv("DRAWIO_PROXY_ALLOWED_PORTS");
if (allowedPortsStr != null)
{
String[] ports = allowedPortsStr.split(",");
for (String port : ports)
{
try
{
allowedPorts.add(Integer.parseInt(port));
}
catch (NumberFormatException e)
{
System.out.println("Invalid DRAWIO_PROXY_ALLOWED_PORTS port: " + port);
}
}
}
}
/**
* Returns a random string of the given length.
*/
public static String generateToken(int length)
{
StringBuffer rtn = new StringBuffer();
for (int i = 0; i < length; i++)
{
int offset = randomSecure.nextInt(TOKEN_ALPHABET.length());
rtn.append(TOKEN_ALPHABET.substring(offset,offset+1));
}
return rtn.toString();
};
/**
* Applies a standard inflate algo to the input byte array
* @param binary the byte array to inflate
* @return the inflated String
*
*/
public static String inflate(byte[] binary) throws IOException
{
StringBuffer result = new StringBuffer();
InputStream in = new InflaterInputStream(
new ByteArrayInputStream(binary), new Inflater(true));
while (in.available() != 0)
{
byte[] buffer = new byte[IO_BUFFER_SIZE];
int len = in.read(buffer, 0, IO_BUFFER_SIZE);
if (len <= 0)
{
break;
}
result.append(new String(buffer, 0, len));
}
in.close();
return result.toString();
}
/**
* Applies a standard deflate algo to the input String
* @param inString the String to deflate
* @return the deflated byte array
*
*/
public static byte[] deflate(String inString) throws IOException
{
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
byte[] inBytes = inString.getBytes("UTF-8");
deflater.setInput(inBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
inBytes.length);
deflater.finish();
byte[] buffer = new byte[IO_BUFFER_SIZE];
while (!deflater.finished())
{
int count = deflater.deflate(buffer); // returns the generated code... index
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
return output;
}
/**
* Copies the input stream to the output stream using the default buffer size
* @param in the input stream
* @param out the output stream
* @throws IOException
*/
public static void copy(InputStream in, OutputStream out) throws IOException
{
copy(in, out, IO_BUFFER_SIZE);
}
/**
* Copies the input stream to the output stream using the default buffer size
* @param in the input stream
* @param out the output stream
* @param sizeLimit the maximum number of bytes to copy
* @throws IOException
*/
public static int copyRestricted(InputStream in, OutputStream out) throws IOException
{
return copy(in, out, IO_BUFFER_SIZE, MAX_SIZE);
}
/**
* Copies the input stream to the output stream using the default buffer size
* @param in the input stream
* @param out the output stream
* @param sizeLimit the maximum number of bytes to copy
* @throws IOException
*/
public static int copyRestricted(InputStream in, OutputStream out, int sizeLimit) throws IOException
{
return copy(in, out, IO_BUFFER_SIZE, sizeLimit);
}
/**
* Copies the input stream to the output stream using the specified buffer size
* @param in the input stream
* @param out the output stream
* @param bufferSize the buffer size to use when copying
* @throws IOException
*/
public static void copy(InputStream in, OutputStream out, int bufferSize)
throws IOException
{
copy(in, out, bufferSize, 0);
}
/**
* Copies the input stream to the output stream using the specified buffer size
* @param in the input stream
* @param out the output stream
* @param bufferSize the buffer size to use when copying
* @param sizeLimit the maximum number of bytes to copy
* @throws IOException
*/
public static int copy(InputStream in, OutputStream out, int bufferSize, int sizeLimit)
throws IOException
{
byte[] b = new byte[bufferSize];
int read, total = 0;
while ((read = in.read(b)) != -1)
{
total += read;
if (sizeLimit > 0 && total > sizeLimit)
{
throw new SizeLimitExceededException();
}
out.write(b, 0, read);
}
return total;
}
/**
* Reads an input stream and returns the result as a String
* @param stream the input stream to read
* @return a String representation of the input stream
* @throws IOException
*/
public static String readInputStream(InputStream stream) throws IOException
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
StringBuffer result = new StringBuffer();
String tmp = reader.readLine();
while (tmp != null)
{
result.append(tmp + "\n");
tmp = reader.readLine();
}
reader.close();
return result.toString();
}
/**
* Encodes the passed String as UTF-8 using an algorithm that's compatible
* with JavaScript's <code>encodeURIComponent</code> function. Returns
* <code>null</code> if the String is <code>null</code>.
*
* @param s The String to be encoded
* @param charset the character set to base the encoding on
* @return the encoded String
*/
public static String encodeURIComponent(String s, String charset)
{
if (s == null)
{
return null;
}
else
{
String result;
try
{
result = URLEncoder.encode(s, charset).replaceAll("\\+", "%20")
.replaceAll("\\%21", "!").replaceAll("\\%27", "'")
.replaceAll("\\%28", "(").replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
}
catch (UnsupportedEncodingException e)
{
// This exception should never occur
result = s;
}
return result;
}
}
/**
* Checks the file type of an input stream and returns the
* bytes that have been read (because URL connections to not
* have support for mark/reset).
*/
static public byte[] checkStreamContent(InputStream is)
throws IOException, UnsupportedContentException
{
byte[] head = new byte[16];
boolean valid = false;
if (is.read(head) == head.length)
{
int c1 = head[0] & 0xFF;
int c2 = head[1] & 0xFF;
int c3 = head[2] & 0xFF;
int c4 = head[3] & 0xFF;
int c5 = head[4] & 0xFF;
int c6 = head[5] & 0xFF;
int c7 = head[6] & 0xFF;
int c8 = head[7] & 0xFF;
int c9 = head[8] & 0xFF;
int c10 = head[9] & 0xFF;
int c11 = head[10] & 0xFF;
int c12 = head[11] & 0xFF;
int c13 = head[12] & 0xFF;
int c14 = head[13] & 0xFF;
int c15 = head[14] & 0xFF;
int c16 = head[15] & 0xFF;
if (c1 == '<')
{
// text/html
if (c2 == '!'
|| ((c2 == 'h'
&& (c3 == 't' && c4 == 'm' && c5 == 'l'
|| c3 == 'e' && c4 == 'a' && c5 == 'd')
|| (c2 == 'b' && c3 == 'o' && c4 == 'd'
&& c5 == 'y')))
|| ((c2 == 'H'
&& (c3 == 'T' && c4 == 'M' && c5 == 'L'
|| c3 == 'E' && c4 == 'A' && c5 == 'D')
|| (c2 == 'B' && c3 == 'O' && c4 == 'D'
&& c5 == 'Y'))))
{
valid = true;
}
// application/xml
if (c2 == '?' && c3 == 'x' && c4 == 'm' && c5 == 'l'
&& c6 == ' ')
{
valid = true;
}
// application/svg+xml
if (c2 == 's' && c3 == 'v' && c4 == 'g' && c5 == ' ')
{
valid = true;
}
}
// big and little (identical) endian UTF-8 encodings, with BOM
// application/xml
if (c1 == 0xef && c2 == 0xbb && c3 == 0xbf)
{
if (c4 == '<' && c5 == '?' && c6 == 'x')
{
valid = true;
}
}
// big and little endian UTF-16 encodings, with byte order mark
// application/xml
if (c1 == 0xfe && c2 == 0xff)
{
if (c3 == 0 && c4 == '<' && c5 == 0 && c6 == '?' && c7 == 0
&& c8 == 'x')
{
valid = true;
}
}
// application/xml
if (c1 == 0xff && c2 == 0xfe)
{
if (c3 == '<' && c4 == 0 && c5 == '?' && c6 == 0 && c7 == 'x'
&& c8 == 0)
{
valid = true;
}
}
// big and little endian UTF-32 encodings, with BOM
// application/xml
if (c1 == 0x00 && c2 == 0x00 && c3 == 0xfe && c4 == 0xff)
{
if (c5 == 0 && c6 == 0 && c7 == 0 && c8 == '<' && c9 == 0
&& c10 == 0 && c11 == 0 && c12 == '?' && c13 == 0
&& c14 == 0 && c15 == 0 && c16 == 'x')
{
valid = true;
}
}
// application/xml
if (c1 == 0xff && c2 == 0xfe && c3 == 0x00 && c4 == 0x00)
{
if (c5 == '<' && c6 == 0 && c7 == 0 && c8 == 0 && c9 == '?'
&& c10 == 0 && c11 == 0 && c12 == 0 && c13 == 'x'
&& c14 == 0 && c15 == 0 && c16 == 0)
{
valid = true;
}
}
// image/gif
if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8')
{
valid = true;
}
// image/x-bitmap
if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f')
{
valid = true;
}
// image/x-pixmap
if (c1 == '!' && c2 == ' ' && c3 == 'X' && c4 == 'P' && c5 == 'M'
&& c6 == '2')
{
valid = true;
}
// image/png
if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13
&& c6 == 10 && c7 == 26 && c8 == 10)
{
valid = true;
}
// image/jpeg
if (c1 == 0xFF && c2 == 0xD8 && c3 == 0xFF)
{
if (c4 == 0xE0 || c4 == 0xEE)
{
valid = true;
}
/**
* File format used by digital cameras to store images.
* Exif Format can be read by any application supporting
* JPEG. Exif Spec can be found at:
* http://www.pima.net/standards/it10/PIMA15740/Exif_2-1.PDF
*/
if ((c4 == 0xE1) && (c7 == 'E' && c8 == 'x' && c9 == 'i'
&& c10 == 'f' && c11 == 0))
{
valid = true;
}
}
// Additional signatures
// See https://www.garykessler.net/library/file_sigs.html
// and https://en.wikipedia.org/wiki/List_of_file_signatures
// TODO: Add check for .eot fonts
// ttf
if (c1 == 0x00 && c2 == 0x01 && c3 == 0x00 && c4 == 0x00
&& c5 == 0x00)
{
valid = true;
}
// otf
if (c1 == 0x4F && c2 == 0x54 && c3 == 0x54 && c4 == 0x4F
&& c5 == 0x00)
{
valid = true;
}
// woff
if (c1 == 0x77 && c2 == 0x4F && c3 == 0x46 && c4 == 0x46)
{
valid = true;
}
// woff2
if (c1 == 0x77 && c2 == 0x4F && c3 == 0x46 && c4 == 0x32)
{
valid = true;
}
// vsdx, vssx (also zip, jar, odt, ods, odp, docx, xlsx, pptx, apk, aar)
if (c1 == 0x50 && c2 == 0x4B && c3 == 0x03 && c4 == 0x04)
{
valid = true;
}
else if (c1 == 0x50 && c2 == 0x4B && c3 == 0x03 && c4 == 0x06)
{
valid = true;
}
// vsd, ppt
if (c1 == 0xD0 && c2 == 0xCF && c3 == 0x11 && c4 == 0xE0
&& c5 == 0xA1 && c6 == 0xB1 && c7 == 0x1A && c8 == 0xE1)
{
valid = true;
}
// mxfile, mxlibrary, mxGraphModel
if (c1 == '<' && c2 == 'm' && c3 == 'x')
{
valid = true;
}
if (c1 == '<' && c2 == 'D' && c3 == 'O' && c4 == 'C' && c5 == 'T'
&& c6 == 'Y' && c7 == 'P' && c8 == 'E')
{
valid = true;
}
if (c1 == '<' && c2 == '!' && c3 == '-' && c4 == '-' && c5 == '['
&& c6 == 'i' && c7 == 'f' && c8 == ' ')
{
valid = true;
}
// Gliffy
if (c1 == '{' && c2 == '"' && c3 == 'c' && c4 == 'o' && c5 == 'n'
&& c6 == 't' && c7 == 'e' && c8 == 'n' && c9 == 't'
&& c10 == 'T' && c11 == 'y' && c12 == 'p' && c13 == 'e'
&& c14 == '"' && c15 == ':')
{
valid = true;
}
// Lucidchart
if (c1 == '{' && c2 == '"' && c3 == 's' && c4 == 't' && c5 == 'a'
&& c6 == 't' && c7 == 'e' && c8 == '"' && c9 == ':')
{
valid = true;
}
}
if (!valid)
{
throw new UnsupportedContentException();
}
return head;
}
public static boolean isNumeric (String str)
{
try
{
Double.parseDouble(str);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
/**
* Checks if the URL parameter is legal, i.e. isn't attempting an SSRF
*
* @param url the URL to check
* @return true if the URL is permitted
*/
public static boolean sanitizeUrl(String url)
{
if (url != null)
{
try
{
URL parsedUrl = new URL(url);
String protocol = parsedUrl.getProtocol();
String host = parsedUrl.getHost();
InetAddress address = InetAddress.getByName(host);
String hostAddress = address.getHostAddress();
host = host.toLowerCase();
return (protocol.equals("http") || protocol.equals("https"))
&& !address.isAnyLocalAddress()
&& !address.isLoopbackAddress()
&& !address.isLinkLocalAddress()
&& allowedPorts.contains(parsedUrl.getPort())
&& !host.endsWith(".internal") // Redundant
&& !host.endsWith(".local") // Redundant
&& !host.contains("localhost") // Redundant
&& !hostAddress.startsWith("0.") // 0.0.0.0/8
&& !hostAddress.startsWith("10.") // 10.0.0.0/8
&& !hostAddress.startsWith("127.") // 127.0.0.0/8
&& !hostAddress.startsWith("169.254.") // 169.254.0.0/16
&& !hostAddress.startsWith("172.16.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.17.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.18.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.19.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.20.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.21.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.22.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.23.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.24.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.25.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.26.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.27.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.28.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.29.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.30.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.31.") // 172.16.0.0/12
&& !hostAddress.startsWith("192.0.0.") // 192.0.0.0/24
&& !hostAddress.startsWith("192.168.") // 192.168.0.0/16
&& !hostAddress.startsWith("198.18.") // 198.18.0.0/15
&& !hostAddress.startsWith("198.19.") // 198.18.0.0/15
&& !hostAddress.startsWith("fc00::") // fc00::/7 https://stackoverflow.com/questions/53764109/is-there-a-java-api-that-will-identify-the-ipv6-address-fd00-as-local-private
&& !hostAddress.startsWith("fd00::") // fd00::/8
&& !host.endsWith(".arpa"); // reverse domain (needed?)
}
catch (MalformedURLException e)
{
return false;
}
catch (UnknownHostException e)
{
return false;
}
}
else
{
return false;
}
}
/**
*
*/
public static class UnsupportedContentException extends Exception
{
private static final long serialVersionUID = 1239597891574347740L;
}
/**
* Exception for size limit exceeeded in copy request.
*/
public static class SizeLimitExceededException extends IOException
{
public SizeLimitExceededException()
{
super("Size limit exceeded");
}
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/Utils.java |
45,329 | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.app;
import bisq.core.account.sign.SignedWitness;
import bisq.core.account.sign.SignedWitnessStorageService;
import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.alert.Alert;
import bisq.core.alert.AlertManager;
import bisq.core.alert.PrivateNotificationManager;
import bisq.core.alert.PrivateNotificationPayload;
import bisq.core.btc.model.AddressEntry;
import bisq.core.btc.nodes.LocalBitcoinNode;
import bisq.core.btc.setup.WalletsSetup;
import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.btc.wallet.WalletsManager;
import bisq.core.btc.wallet.http.MemPoolSpaceTxBroadcaster;
import bisq.core.dao.governance.voteresult.VoteResultException;
import bisq.core.dao.state.unconfirmed.UnconfirmedBsqChangeOutputListService;
import bisq.core.locale.Res;
import bisq.core.offer.OpenOfferManager;
import bisq.core.payment.AmazonGiftCardAccount;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.RevolutAccount;
import bisq.core.payment.payload.PaymentMethod;
import bisq.core.support.dispute.Dispute;
import bisq.core.support.dispute.arbitration.ArbitrationManager;
import bisq.core.support.dispute.mediation.MediationManager;
import bisq.core.support.dispute.refund.RefundManager;
import bisq.core.trade.TradeManager;
import bisq.core.trade.bisq_v1.TradeTxException;
import bisq.core.user.BlockChainExplorer;
import bisq.core.user.Preferences;
import bisq.core.user.User;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;
import bisq.network.Socks5ProxyProvider;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.P2PService;
import bisq.network.p2p.storage.payload.PersistableNetworkPayload;
import bisq.network.utils.Utils;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.app.Log;
import bisq.common.app.Version;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.common.util.Utilities;
import org.bitcoinj.core.Coin;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.monadic.MonadicBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.SetChangeListener;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import ch.qos.logback.classic.Level;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static bisq.core.util.FormattingUtils.formatBytes;
@Slf4j
@Singleton
public class BisqSetup {
private static final String VERSION_FILE_NAME = "version";
private static final String RESYNC_SPV_FILE_NAME = "resyncSpv";
public interface BisqSetupListener {
default void onInitP2pNetwork() {
}
default void onInitWallet() {
}
default void onRequestWalletPassword() {
}
void onSetupComplete();
}
private static final long STARTUP_TIMEOUT_MINUTES = 4;
private final DomainInitialisation domainInitialisation;
private final P2PNetworkSetup p2PNetworkSetup;
private final WalletAppSetup walletAppSetup;
private final WalletsManager walletsManager;
private final WalletsSetup walletsSetup;
private final BtcWalletService btcWalletService;
private final P2PService p2PService;
private final PrivateNotificationManager privateNotificationManager;
private final SignedWitnessStorageService signedWitnessStorageService;
private final TradeManager tradeManager;
private final OpenOfferManager openOfferManager;
private final Preferences preferences;
private final User user;
private final AlertManager alertManager;
private final UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService;
private final Config config;
private final AccountAgeWitnessService accountAgeWitnessService;
private final CoinFormatter formatter;
private final LocalBitcoinNode localBitcoinNode;
private final AppStartupState appStartupState;
private final MediationManager mediationManager;
private final RefundManager refundManager;
private final ArbitrationManager arbitrationManager;
@Setter
@Nullable
private Consumer<Runnable> displayTacHandler;
@Setter
@Nullable
private Consumer<String> chainFileLockedExceptionHandler,
spvFileCorruptedHandler, lockedUpFundsHandler, daoErrorMessageHandler, daoWarnMessageHandler,
filterWarningHandler, displaySecurityRecommendationHandler, displayLocalhostHandler,
wrongOSArchitectureHandler, displaySignedByArbitratorHandler,
displaySignedByPeerHandler, displayPeerLimitLiftedHandler, displayPeerSignerHandler,
rejectedTxErrorMessageHandler, diskSpaceWarningHandler, offerDisabledHandler, chainNotSyncedHandler;
@Setter
@Nullable
private Consumer<Boolean> displayTorNetworkSettingsHandler;
@Setter
@Nullable
private Runnable showFirstPopupIfResyncSPVRequestedHandler;
@Setter
@Nullable
private Consumer<Consumer<KeyParameter>> requestWalletPasswordHandler;
@Setter
@Nullable
private Consumer<Alert> displayAlertHandler;
@Setter
@Nullable
private BiConsumer<Alert, String> displayUpdateHandler;
@Setter
@Nullable
private Consumer<VoteResultException> voteResultExceptionHandler;
@Setter
@Nullable
private Consumer<PrivateNotificationPayload> displayPrivateNotificationHandler;
@Setter
@Nullable
private Runnable showPopupIfInvalidBtcConfigHandler;
@Setter
@Nullable
private Consumer<List<RevolutAccount>> revolutAccountsUpdateHandler;
@Setter
@Nullable
private Consumer<List<AmazonGiftCardAccount>> amazonGiftCardAccountsUpdateHandler;
@Setter
@Nullable
private Runnable qubesOSInfoHandler;
@Setter
@Nullable
private Runnable daoRequiresRestartHandler;
@Setter
@Nullable
private Runnable torAddressUpgradeHandler;
@Setter
@Nullable
private Consumer<String> downGradePreventionHandler;
@Getter
final BooleanProperty newVersionAvailableProperty = new SimpleBooleanProperty(false);
private BooleanProperty p2pNetworkReady;
private final BooleanProperty walletInitialized = new SimpleBooleanProperty();
private boolean allBasicServicesInitialized;
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<Boolean> p2pNetworkAndWalletInitialized;
private final List<BisqSetupListener> bisqSetupListeners = new ArrayList<>();
@Inject
public BisqSetup(DomainInitialisation domainInitialisation,
P2PNetworkSetup p2PNetworkSetup,
WalletAppSetup walletAppSetup,
WalletsManager walletsManager,
WalletsSetup walletsSetup,
BtcWalletService btcWalletService,
P2PService p2PService,
PrivateNotificationManager privateNotificationManager,
SignedWitnessStorageService signedWitnessStorageService,
TradeManager tradeManager,
OpenOfferManager openOfferManager,
Preferences preferences,
User user,
AlertManager alertManager,
UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService,
Config config,
AccountAgeWitnessService accountAgeWitnessService,
@Named(FormattingUtils.BTC_FORMATTER_KEY) CoinFormatter formatter,
LocalBitcoinNode localBitcoinNode,
AppStartupState appStartupState,
Socks5ProxyProvider socks5ProxyProvider,
MediationManager mediationManager,
RefundManager refundManager,
ArbitrationManager arbitrationManager) {
this.domainInitialisation = domainInitialisation;
this.p2PNetworkSetup = p2PNetworkSetup;
this.walletAppSetup = walletAppSetup;
this.walletsManager = walletsManager;
this.walletsSetup = walletsSetup;
this.btcWalletService = btcWalletService;
this.p2PService = p2PService;
this.privateNotificationManager = privateNotificationManager;
this.signedWitnessStorageService = signedWitnessStorageService;
this.tradeManager = tradeManager;
this.openOfferManager = openOfferManager;
this.preferences = preferences;
this.user = user;
this.alertManager = alertManager;
this.unconfirmedBsqChangeOutputListService = unconfirmedBsqChangeOutputListService;
this.config = config;
this.accountAgeWitnessService = accountAgeWitnessService;
this.formatter = formatter;
this.localBitcoinNode = localBitcoinNode;
this.appStartupState = appStartupState;
this.mediationManager = mediationManager;
this.refundManager = refundManager;
this.arbitrationManager = arbitrationManager;
MemPoolSpaceTxBroadcaster.init(socks5ProxyProvider, preferences, localBitcoinNode);
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void displayAlertIfPresent(Alert alert, boolean openNewVersionPopup) {
if (alert == null)
return;
if (alert.isSoftwareUpdateNotification()) {
// only process if the alert version is "newer" than ours
if (alert.isNewVersion(preferences)) {
user.setDisplayedAlert(alert); // save context to compare later
newVersionAvailableProperty.set(true); // shows link in footer bar
if ((alert.canShowPopup(preferences) || openNewVersionPopup) && displayUpdateHandler != null) {
displayUpdateHandler.accept(alert, alert.showAgainKey());
}
}
} else {
// it is a normal message alert
final Alert displayedAlert = user.getDisplayedAlert();
if ((displayedAlert == null || !displayedAlert.equals(alert)) && displayAlertHandler != null)
displayAlertHandler.accept(alert);
}
}
public void displayOfferDisabledMessage(String message) {
if (offerDisabledHandler != null) {
offerDisabledHandler.accept(message);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// Main startup tasks
///////////////////////////////////////////////////////////////////////////////////////////
public void addBisqSetupListener(BisqSetupListener listener) {
bisqSetupListeners.add(listener);
}
public void start() {
// If user tried to downgrade we require a shutdown
if (Config.baseCurrencyNetwork() == BaseCurrencyNetwork.BTC_MAINNET &&
hasDowngraded(downGradePreventionHandler)) {
return;
}
persistBisqVersion();
maybeReSyncSPVChain();
maybeShowTac(this::step2);
}
private void step2() {
readMapsFromResources(this::step3);
checkForCorrectOSArchitecture();
checkIfRunningOnQubesOS();
}
private void step3() {
startP2pNetworkAndWallet(this::step4);
}
private void step4() {
initDomainServices();
bisqSetupListeners.forEach(BisqSetupListener::onSetupComplete);
// We set that after calling the setupCompleteHandler to not trigger a popup from the dev dummy accounts
// in MainViewModel
maybeShowSecurityRecommendation();
maybeShowLocalhostRunningInfo();
maybeShowAccountSigningStateInfo();
maybeShowTorAddressUpgradeInformation();
maybeUpgradeBsqExplorerUrl();
checkInboundConnections();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Sub tasks
///////////////////////////////////////////////////////////////////////////////////////////
private void maybeReSyncSPVChain() {
// We do the delete of the spv file at startup before BitcoinJ is initialized to avoid issues with locked files under Windows.
if (getResyncSpvSemaphore()) {
try {
walletsSetup.reSyncSPVChain();
// In case we had an unconfirmed change output we reset the unconfirmedBsqChangeOutputList so that
// after a SPV resync we do not have any dangling BSQ utxos in that list which would cause an incorrect
// BSQ balance state after the SPV resync.
unconfirmedBsqChangeOutputListService.onSpvResync();
} catch (IOException e) {
log.error(e.toString());
e.printStackTrace();
}
}
}
private void maybeShowTac(Runnable nextStep) {
if (!preferences.isTacAcceptedV120() && !DevEnv.isDevMode()) {
if (displayTacHandler != null)
displayTacHandler.accept(() -> {
preferences.setTacAcceptedV120(true);
nextStep.run();
});
} else {
nextStep.run();
}
}
private void readMapsFromResources(Runnable completeHandler) {
String postFix = "_" + config.baseCurrencyNetwork.name();
p2PService.getP2PDataStorage().readFromResources(postFix, completeHandler);
}
private void startP2pNetworkAndWallet(Runnable nextStep) {
ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> {
// TODO that seems to be called too often if Tor takes longer to start up...
if (newValue && !p2pNetworkReady.get() && displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(true);
};
Timer startupTimeout = UserThread.runAfter(() -> {
if (p2PNetworkSetup.p2pNetworkFailed.get() || walletsSetup.walletsSetupFailed.get()) {
// Skip this timeout action if the p2p network or wallet setup failed
// since an error prompt will be shown containing the error message
return;
}
log.warn("startupTimeout called");
if (walletsManager.areWalletsEncrypted())
walletInitialized.addListener(walletInitializedListener);
else if (displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(true);
log.info("Set log level for org.berndpruenster.netlayer classes to DEBUG to show more details for " +
"Tor network connection issues");
Log.setCustomLogLevel("org.berndpruenster.netlayer", Level.DEBUG);
}, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES);
log.info("Init P2P network");
bisqSetupListeners.forEach(BisqSetupListener::onInitP2pNetwork);
p2pNetworkReady = p2PNetworkSetup.init(this::initWallet, displayTorNetworkSettingsHandler);
// We only init wallet service here if not using Tor for bitcoinj.
// When using Tor, wallet init must be deferred until Tor is ready.
// TODO encapsulate below conditional inside getUseTorForBitcoinJ
if (!preferences.getUseTorForBitcoinJ() || localBitcoinNode.shouldBeUsed()) {
initWallet();
}
// need to store it to not get garbage collected
p2pNetworkAndWalletInitialized = EasyBind.combine(walletInitialized, p2pNetworkReady,
(a, b) -> {
log.info("walletInitialized={}, p2pNetWorkReady={}", a, b);
return a && b;
});
p2pNetworkAndWalletInitialized.subscribe((observable, oldValue, newValue) -> {
if (newValue) {
startupTimeout.stop();
walletInitialized.removeListener(walletInitializedListener);
if (displayTorNetworkSettingsHandler != null)
displayTorNetworkSettingsHandler.accept(false);
nextStep.run();
}
});
}
private void initWallet() {
log.info("Init wallet");
bisqSetupListeners.forEach(BisqSetupListener::onInitWallet);
Runnable walletPasswordHandler = () -> {
log.info("Wallet password required");
bisqSetupListeners.forEach(BisqSetupListener::onRequestWalletPassword);
if (p2pNetworkReady.get())
p2PNetworkSetup.setSplashP2PNetworkAnimationVisible(true);
if (requestWalletPasswordHandler != null) {
requestWalletPasswordHandler.accept(aesKey -> {
walletsManager.setAesKey(aesKey);
walletsManager.maybeAddSegwitKeychains(aesKey);
if (getResyncSpvSemaphore()) {
if (showFirstPopupIfResyncSPVRequestedHandler != null)
showFirstPopupIfResyncSPVRequestedHandler.run();
} else {
// TODO no guarantee here that the wallet is really fully initialized
// We would need a new walletInitializedButNotEncrypted state to track
// Usually init is fast and we have our wallet initialized at that state though.
walletInitialized.set(true);
}
});
}
};
walletAppSetup.init(chainFileLockedExceptionHandler,
spvFileCorruptedHandler,
getResyncSpvSemaphore(),
showFirstPopupIfResyncSPVRequestedHandler,
showPopupIfInvalidBtcConfigHandler,
walletPasswordHandler,
() -> {
if (allBasicServicesInitialized) {
// the following are called each time a block is received
checkForLockedUpFunds();
checkForInvalidMakerFeeTxs();
checkFreeDiskSpace();
}
},
() -> walletInitialized.set(true));
}
private void initDomainServices() {
log.info("initDomainServices");
domainInitialisation.initDomainServices(rejectedTxErrorMessageHandler,
displayPrivateNotificationHandler,
daoErrorMessageHandler,
daoWarnMessageHandler,
filterWarningHandler,
chainNotSyncedHandler,
offerDisabledHandler,
voteResultExceptionHandler,
revolutAccountsUpdateHandler,
amazonGiftCardAccountsUpdateHandler,
daoRequiresRestartHandler);
if (walletsSetup.downloadPercentageProperty().get() == 1) {
checkForLockedUpFunds();
checkForInvalidMakerFeeTxs();
}
alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) ->
displayAlertIfPresent(newValue, false));
displayAlertIfPresent(alertManager.alertMessageProperty().get(), false);
allBasicServicesInitialized = true;
appStartupState.onDomainServicesInitialized();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Utils
///////////////////////////////////////////////////////////////////////////////////////////
private void checkForLockedUpFunds() {
// We check if there are locked up funds in failed or closed trades
try {
Set<String> setOfAllTradeIds = tradeManager.getSetOfFailedOrClosedTradeIdsFromLockedInFunds();
btcWalletService.getAddressEntriesForTrade().stream()
.filter(e -> setOfAllTradeIds.contains(e.getOfferId()) &&
e.getContext() == AddressEntry.Context.MULTI_SIG)
.forEach(e -> {
Coin balance = e.getCoinLockedInMultiSigAsCoin();
if (balance.isPositive()) {
String message = Res.get("popup.warning.lockedUpFunds",
formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId());
log.warn(message);
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(message);
}
}
});
} catch (TradeTxException e) {
log.warn(e.getMessage());
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(e.getMessage());
}
}
}
private void checkForInvalidMakerFeeTxs() {
// We check if we have open offers with no confidence object at the maker fee tx. That can happen if the
// miner fee was too low and the transaction got removed from mempool and got out from our wallet after a
// resync.
openOfferManager.getObservableList().forEach(e -> {
if (e.getOffer().isBsqSwapOffer()) {
return;
}
String offerFeePaymentTxId = e.getOffer().getOfferFeePaymentTxId();
if (btcWalletService.getConfidenceForTxId(offerFeePaymentTxId) == null) {
String message = Res.get("popup.warning.openOfferWithInvalidMakerFeeTx",
e.getOffer().getShortId(), offerFeePaymentTxId);
log.warn(message);
if (lockedUpFundsHandler != null) {
lockedUpFundsHandler.accept(message);
}
}
});
}
private void checkFreeDiskSpace() {
long TWO_GIGABYTES = 2147483648L;
long usableSpace = new File(Config.appDataDir(), VERSION_FILE_NAME).getUsableSpace();
if (usableSpace < TWO_GIGABYTES) {
String message = Res.get("popup.warning.diskSpace", formatBytes(usableSpace), formatBytes(TWO_GIGABYTES));
log.warn(message);
if (diskSpaceWarningHandler != null) {
diskSpaceWarningHandler.accept(message);
}
}
}
@Nullable
public static String getLastBisqVersion() {
File versionFile = getVersionFile();
if (!versionFile.exists()) {
return null;
}
try (Scanner scanner = new Scanner(versionFile)) {
// We only expect 1 line
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Nullable
public static boolean getResyncSpvSemaphore() {
File resyncSpvSemaphore = new File(Config.appDataDir(), RESYNC_SPV_FILE_NAME);
return resyncSpvSemaphore.exists();
}
public static void setResyncSpvSemaphore(boolean isResyncSpvRequested) {
File resyncSpvSemaphore = new File(Config.appDataDir(), RESYNC_SPV_FILE_NAME);
if (isResyncSpvRequested) {
if (!resyncSpvSemaphore.exists()) {
try {
if (!resyncSpvSemaphore.createNewFile()) {
log.error("ResyncSpv file could not be created");
}
} catch (IOException e) {
e.printStackTrace();
log.error("ResyncSpv file could not be created. {}", e.toString());
}
}
} else {
resyncSpvSemaphore.delete();
}
}
private static File getVersionFile() {
return new File(Config.appDataDir(), VERSION_FILE_NAME);
}
public static boolean hasDowngraded() {
return hasDowngraded(getLastBisqVersion());
}
public static boolean hasDowngraded(String lastVersion) {
return lastVersion != null && Version.isNewVersion(lastVersion, Version.VERSION);
}
public static boolean hasDowngraded(@Nullable Consumer<String> downGradePreventionHandler) {
String lastVersion = getLastBisqVersion();
boolean hasDowngraded = hasDowngraded(lastVersion);
if (hasDowngraded) {
log.error("Downgrade from version {} to version {} is not supported", lastVersion, Version.VERSION);
if (downGradePreventionHandler != null) {
downGradePreventionHandler.accept(lastVersion);
}
}
return hasDowngraded;
}
public static void persistBisqVersion() {
File versionFile = getVersionFile();
if (!versionFile.exists()) {
try {
if (!versionFile.createNewFile()) {
log.error("Version file could not be created");
}
} catch (IOException e) {
e.printStackTrace();
log.error("Version file could not be created. {}", e.toString());
}
}
try (FileWriter fileWriter = new FileWriter(versionFile, false)) {
fileWriter.write(Version.VERSION);
} catch (IOException e) {
e.printStackTrace();
log.error("Writing Version failed. {}", e.toString());
}
}
private void checkForCorrectOSArchitecture() {
if (!Utilities.isCorrectOSArchitecture() && wrongOSArchitectureHandler != null) {
String osArchitecture = Utilities.getOSArchitecture();
// We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
// Needs at least more testing on different machines...
wrongOSArchitectureHandler.accept(Res.get("popup.warning.wrongVersion",
osArchitecture,
Utilities.getJVMArchitecture(),
osArchitecture));
}
}
/**
* If Bisq is running on an OS that is virtualized under Qubes, show info popup with
* link to the Setup Guide. The guide documents what other steps are needed, in
* addition to installing the Linux package (qube sizing, etc)
*/
private void checkIfRunningOnQubesOS() {
if (Utilities.isQubesOS() && qubesOSInfoHandler != null) {
qubesOSInfoHandler.run();
}
}
/**
* Check if we have inbound connections. If not, try to ping ourselves.
* If Bisq cannot connect to its own onion address through Tor, display
* an informative message to let the user know to configure their firewall else
* their offers will not be reachable.
* Repeat this test hourly.
*/
private void checkInboundConnections() {
NodeAddress onionAddress = p2PService.getNetworkNode().nodeAddressProperty().get();
if (onionAddress == null || !onionAddress.getFullAddress().contains("onion")) {
return;
}
if (p2PService.getNetworkNode().upTime() > TimeUnit.HOURS.toMillis(1) &&
p2PService.getNetworkNode().getInboundConnectionCount() == 0) {
// we've been online a while and did not find any inbound connections; lets try the self-ping check
log.info("no recent inbound connections found, starting the self-ping test");
privateNotificationManager.sendPing(onionAddress, stringResult -> {
log.info(stringResult);
if (stringResult.contains("failed")) {
getP2PNetworkStatusIconId().set("flashing:image-yellow_circle");
}
});
}
// schedule another inbound connection check for later
int nextCheckInMinutes = 30 + new Random().nextInt(30);
log.debug("next inbound connections check in {} minutes", nextCheckInMinutes);
UserThread.runAfter(this::checkInboundConnections, nextCheckInMinutes, TimeUnit.MINUTES);
}
private void maybeShowSecurityRecommendation() {
String key = "remindPasswordAndBackup";
user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
if (!walletsManager.areWalletsEncrypted() && !user.isPaymentAccountImport() && preferences.showAgain(key) && change.wasAdded() &&
displaySecurityRecommendationHandler != null)
displaySecurityRecommendationHandler.accept(key);
});
}
private void maybeShowLocalhostRunningInfo() {
if (Config.baseCurrencyNetwork().isMainnet()) {
maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler,
localBitcoinNode.shouldBeUsed());
}
}
private void maybeShowAccountSigningStateInfo() {
String keySignedByArbitrator = "accountSignedByArbitrator";
String keySignedByPeer = "accountSignedByPeer";
String keyPeerLimitedLifted = "accountLimitLifted";
String keyPeerSigner = "accountPeerSigner";
// check signed witness on startup
checkSigningState(AccountAgeWitnessService.SignState.ARBITRATOR, keySignedByArbitrator, displaySignedByArbitratorHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_INITIAL, keySignedByPeer, displaySignedByPeerHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_LIMIT_LIFTED, keyPeerLimitedLifted, displayPeerLimitLiftedHandler);
checkSigningState(AccountAgeWitnessService.SignState.PEER_SIGNER, keyPeerSigner, displayPeerSignerHandler);
// check signed witness during runtime
p2PService.getP2PDataStorage().addAppendOnlyDataStoreListener(
payload -> {
maybeTriggerDisplayHandler(keySignedByArbitrator, displaySignedByArbitratorHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.ARBITRATOR));
maybeTriggerDisplayHandler(keySignedByPeer, displaySignedByPeerHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_INITIAL));
maybeTriggerDisplayHandler(keyPeerLimitedLifted, displayPeerLimitLiftedHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_LIMIT_LIFTED));
maybeTriggerDisplayHandler(keyPeerSigner, displayPeerSignerHandler,
isSignedWitnessOfMineWithState(payload, AccountAgeWitnessService.SignState.PEER_SIGNER));
});
}
private void checkSigningState(AccountAgeWitnessService.SignState state,
String key, Consumer<String> displayHandler) {
boolean signingStateFound = signedWitnessStorageService.getMap().values().stream()
.anyMatch(payload -> isSignedWitnessOfMineWithState(payload, state));
maybeTriggerDisplayHandler(key, displayHandler, signingStateFound);
}
private boolean isSignedWitnessOfMineWithState(PersistableNetworkPayload payload,
AccountAgeWitnessService.SignState state) {
if (payload instanceof SignedWitness && user.getPaymentAccounts() != null) {
// We know at this point that it is already added to the signed witness list
// Check if new signed witness is for one of my own accounts
return user.getPaymentAccounts().stream()
.filter(a -> PaymentMethod.hasChargebackRisk(a.getPaymentMethod(), a.getTradeCurrencies()))
.filter(a -> Arrays.equals(((SignedWitness) payload).getAccountAgeWitnessHash(),
accountAgeWitnessService.getMyWitness(a.getPaymentAccountPayload()).getHash()))
.anyMatch(a -> accountAgeWitnessService.getSignState(accountAgeWitnessService.getMyWitness(
a.getPaymentAccountPayload())).equals(state));
}
return false;
}
private void maybeTriggerDisplayHandler(String key, Consumer<String> displayHandler, boolean signingStateFound) {
if (signingStateFound && preferences.showAgain(key) &&
displayHandler != null) {
displayHandler.accept(key);
}
}
private void maybeUpgradeBsqExplorerUrl() {
// if wiz BSQ explorer selected, replace with 1st explorer in the list of available.
if (preferences.getBsqBlockChainExplorer().name.equalsIgnoreCase("mempool.space (@wiz)") &&
preferences.getBsqBlockChainExplorers().size() > 0) {
preferences.setBsqBlockChainExplorer(preferences.getBsqBlockChainExplorers().get(0));
}
}
private void maybeShowTorAddressUpgradeInformation() {
if (Config.baseCurrencyNetwork().isRegtest() ||
Utils.isV3Address(Objects.requireNonNull(p2PService.getNetworkNode().getNodeAddress()).getHostName())) {
return;
}
maybeRunTorNodeAddressUpgradeHandler();
tradeManager.getNumPendingTrades().addListener((observable, oldValue, newValue) -> {
long numPendingTrades = (long) newValue;
if (numPendingTrades == 0) {
maybeRunTorNodeAddressUpgradeHandler();
}
});
}
private void maybeRunTorNodeAddressUpgradeHandler() {
if (mediationManager.getDisputesAsObservableList().stream().allMatch(Dispute::isClosed) &&
refundManager.getDisputesAsObservableList().stream().allMatch(Dispute::isClosed) &&
arbitrationManager.getDisputesAsObservableList().stream().allMatch(Dispute::isClosed) &&
tradeManager.getNumPendingTrades().isEqualTo(0).get()) {
Objects.requireNonNull(torAddressUpgradeHandler).run();
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////////////////////
// Wallet
public StringProperty getBtcInfo() {
return walletAppSetup.getBtcInfo();
}
public DoubleProperty getBtcSyncProgress() {
return walletAppSetup.getBtcSyncProgress();
}
public StringProperty getWalletServiceErrorMsg() {
return walletAppSetup.getWalletServiceErrorMsg();
}
public StringProperty getBtcSplashSyncIconId() {
return walletAppSetup.getBtcSplashSyncIconId();
}
public BooleanProperty getUseTorForBTC() {
return walletAppSetup.getUseTorForBTC();
}
// P2P
public StringProperty getP2PNetworkInfo() {
return p2PNetworkSetup.getP2PNetworkInfo();
}
public BooleanProperty getSplashP2PNetworkAnimationVisible() {
return p2PNetworkSetup.getSplashP2PNetworkAnimationVisible();
}
public StringProperty getP2pNetworkWarnMsg() {
return p2PNetworkSetup.getP2pNetworkWarnMsg();
}
public StringProperty getP2PNetworkIconId() {
return p2PNetworkSetup.getP2PNetworkIconId();
}
public StringProperty getP2PNetworkStatusIconId() {
return p2PNetworkSetup.getP2PNetworkStatusIconId();
}
public BooleanProperty getDataReceived() {
return p2PNetworkSetup.getDataReceived();
}
public StringProperty getP2pNetworkLabelId() {
return p2PNetworkSetup.getP2pNetworkLabelId();
}
}
| bisq-network/bisq | core/src/main/java/bisq/core/app/BisqSetup.java |
45,330 | /**
* Copyright (c) 2006-2022, JGraph Ltd
*/
package com.mxgraph.online;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@SuppressWarnings("serial")
abstract public class AbsAuth extends HttpServlet implements AbsComm
{
private static final Logger log = Logger.getLogger(AbsAuth.class.getName());
private static final boolean DEBUG = false;
protected static final String SEPARATOR = "/:::/";
public static final int X_WWW_FORM_URLENCODED = 1;
public static final int JSON = 2;
private static final String STATE_COOKIE = "auth-state";
private static final String TOKEN_COOKIE = "auth-token";
protected static final int STATE_COOKIE_AGE = 600; //10 min
protected static final int TOKEN_COOKIE_AGE = 31536000; //One year
public static boolean IS_GAE = (System.getProperty("com.google.appengine.runtime.version") == null) ? false : true;
public static boolean USE_HTTP = "1".equals(System.getenv("DRAWIO_USE_HTTP")); // Not secure, use at your own risk
public static final SecureRandom random = new SecureRandom();
protected static Cache tokenCache;
static
{
try
{
tokenCache = CacheFacade.createCache();
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected int postType = X_WWW_FORM_URLENCODED;
protected String cookiePath = "/";
protected boolean withRedirectUrl = true;
protected boolean withRedirectUrlInRefresh = true;
protected boolean withAcceptJsonHeader = false;
static public class Config
{
public String REDIRECT_PATH = null, AUTH_SERVICE_URL = null;
protected HashMap<String, String> clientSecretMap = new HashMap<>();
public Config(String clientIds, String clientSecrets)
{
try
{
String[] cIds = clientIds.split(SEPARATOR);
String[] cSecrets = clientSecrets.split(SEPARATOR);
for (int i = 0; i < cIds.length; i++)
{
clientSecretMap.put(cIds[i], cSecrets[i]);
}
}
catch (Exception e)
{
throw new RuntimeException("Invalid config. " + e.getMessage());
}
}
public String getClientSecret(String cId)
{
return clientSecretMap.get(cId);
}
public String getRedirectUrl(String domain)
{
return (USE_HTTP? "http://" : "https://") + domain + REDIRECT_PATH;
}
}
protected Config getConfig()
{
return null;
}
protected String processAuthError(String errorCode)
{
//Usually sending null is enough as it is used as a value for auth info
//If more processing is needed, override this method
return processAuthResponse("null", false);
}
protected String processAuthResponse(String authRes, boolean jsonResponse)
{
return "";
}
@SuppressWarnings("unchecked")
protected static void putCacheValue(String key, String val)
{
int trials = 0;
boolean done = false;
do
{
//Exponential? back-off
if (trials > 0)
{
try
{
Thread.sleep(200 * trials);
}
catch (InterruptedException e) { }
}
trials++;
try
{
tokenCache.put(key, val);
done = true;
}
catch(Exception e)
{
//delay in re-trial is above
done = false;
}
}
while(!done && trials < 3);
}
//To support multiple tokens in one cookie
protected String getTokenFromCookieVal(String tokenCookieVal, Object request)
{
return tokenCookieVal;
}
protected void logout(String tokenCookieName, String tokenCookieVal, Object request, Object response)
{
deleteCookie(tokenCookieName, cookiePath, response);
}
//https://stackoverflow.com/questions/4390800/determine-if-a-string-is-absolute-url-or-relative-url-in-java
public static boolean isAbsolute(String url)
{
if (url.startsWith("//")) // //www.domain.com/start
{
return true;
}
try
{
URI uri = new URI(url);
return uri.isAbsolute();
}
catch (URISyntaxException e)
{
return true; // Block malformed URLs also
}
}
protected void doGetAbst(Object request, Object response) throws IOException
{
String stateOnly = getParameter("getState", request);
if ("1".equals(stateOnly))
{
String state = new BigInteger(256, random).toString(32);
String key = new BigInteger(256, random).toString(32);
putCacheValue(key, state);
setStatus(HttpServletResponse.SC_OK, response);
//Chrome blocks this cookie when draw.io is running in an iframe. The cookie is added to parent frame. TODO FIXME
addCookie(STATE_COOKIE, key, STATE_COOKIE_AGE, cookiePath, response); //10 min to finish auth
setHeader("Content-Type", "text/plain", response);
setBody(state, response);
return;
}
String code = getParameter("code", request);
String error = getParameter("error", request);
HashMap<String, String> stateVars = new HashMap<>();
String secret = null, client = null, redirectUri = null, domain = null, stateToken = null, cookieToken = null, version = null, successRedirect = null;
try
{
String state = getParameter("state", request);
try
{
if (state != null)
{
String[] parts = state.split("&");
for (String part : parts)
{
String[] keyVal = part.split("=");
stateVars.put(keyVal[0], keyVal[1]);
}
}
domain = stateVars.get("domain");
client = stateVars.get("cId");
stateToken = stateVars.get("token");
version = stateVars.get("ver");
successRedirect = stateVars.get("redirect");
//Redirect to a page on the same domain only (relative path)
if (successRedirect != null && isAbsolute(successRedirect))
{
successRedirect = null;
}
//Get the cached state based on the cookie key
String cacheKey = getCookieValue(STATE_COOKIE, request);
if (cacheKey != null)
{
cookieToken = (String) tokenCache.get(cacheKey);
//Delete cookie & cache after being used since it is a single use
tokenCache.remove(cacheKey);
deleteCookie(STATE_COOKIE, cookiePath, response);
}
}
catch(Exception e)
{
//Ignore, incorrect arguments
e.printStackTrace();
}
Config CONFIG = getConfig();
redirectUri = CONFIG.getRedirectUrl(domain != null? domain : getServerName(request));
secret = CONFIG.getClientSecret(client);
String tokenCookie = TOKEN_COOKIE + client; //Such that we support multiple client ids
//TODO This code should be removed when new code is propagated
String refreshToken = getParameter("refresh_token", request), tokenCookieVal = null;
if (refreshToken == null)
{
tokenCookieVal = getCookieValue(tokenCookie, request);
refreshToken = getTokenFromCookieVal(tokenCookieVal, request);
}
//Logout (delete refresh token)
String logoutParam = getParameter("doLogout", request);
if ("1".equals(logoutParam))
{
logout(tokenCookie, tokenCookieVal, request, response);
}
else if (error != null)
{
setStatus(HttpServletResponse.SC_UNAUTHORIZED, response);
// Writes JavaScript code
setBody(processAuthError(error), response);
}
else if ((code == null && refreshToken == null) || client == null || redirectUri == null || secret == null)
{
setStatus(HttpServletResponse.SC_BAD_REQUEST, response);
}
//Non GAE runtimes are excluded from state check. TODO Change GAE stub to return null from CacheFactory
else if (IS_GAE && (stateToken == null || !stateToken.equals(cookieToken)))
{
setStatus(HttpServletResponse.SC_UNAUTHORIZED, response);
}
else
{
Response authResp = contactOAuthServer(CONFIG.AUTH_SERVICE_URL, code, refreshToken, secret, client, redirectUri, successRedirect != null, 1);
setStatus(authResp.status, response);
if (authResp.refreshToken != null)
{
addCookie(tokenCookie, getRefreshTokenCookie(authResp.refreshToken, tokenCookieVal, authResp.accessToken), TOKEN_COOKIE_AGE, cookiePath, response);
}
if (authResp.content != null)
{
if (successRedirect != null)
{
//successRedirect is validated above
sendRedirect(successRedirect + "#" + Utils.encodeURIComponent(authResp.content, "UTF-8"), response);
}
else
{
setBody(authResp.content, response);
}
}
}
}
catch (Exception e)
{
setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response);
log.log(Level.SEVERE, "AUTH-SERVLET: [" + getRemoteAddr(request)+ "] ERROR: " + e.getMessage());
}
}
protected String getRefreshTokenCookie(String refreshToken, String tokenCookieVal, String accessToken)
{
return refreshToken;
}
protected int getExpiresIn(JsonObject json)
{
try
{
return json.get("expires_in").getAsInt();
}
catch(Exception e)
{
return -1;
}
}
protected String getAccessToken(JsonObject json)
{
return json.get("access_token").getAsString();
}
protected String getRefreshToken(JsonObject json)
{
try
{
return json.get("refresh_token").getAsString();
}
catch(Exception e)
{
return null;
}
}
class Response
{
public int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
public String content = null;
public String refreshToken = null;
public String accessToken = null;
}
private Response contactOAuthServer(String authSrvUrl, String code, String refreshToken, String secret,
String client, String redirectUri,boolean directResp, int retryCount)
{
HttpURLConnection con = null;
Response response = new Response();
try
{
URL obj = new URL(authSrvUrl);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
boolean jsonResponse = false;
StringBuilder urlParameters = new StringBuilder();
if (postType == X_WWW_FORM_URLENCODED)
{
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (withAcceptJsonHeader)
{
con.setRequestProperty("Accept", "application/json");
}
urlParameters.append("client_id=");
urlParameters.append(Utils.encodeURIComponent(client, "UTF-8"));
urlParameters.append("&client_secret=");
urlParameters.append(Utils.encodeURIComponent(secret, "UTF-8"));
if (code != null)
{
if (withRedirectUrl)
{
urlParameters.append("&redirect_uri=");
urlParameters.append(Utils.encodeURIComponent(redirectUri, "UTF-8"));
}
urlParameters.append("&code=");
urlParameters.append(Utils.encodeURIComponent(code, "UTF-8"));
urlParameters.append("&grant_type=authorization_code");
}
else
{
if (withRedirectUrlInRefresh)
{
urlParameters.append("&redirect_uri=");
urlParameters.append(Utils.encodeURIComponent(redirectUri, "UTF-8"));
}
urlParameters.append("&refresh_token=");
urlParameters.append(Utils.encodeURIComponent(refreshToken, "UTF-8"));
urlParameters.append("&grant_type=refresh_token");
jsonResponse = true;
}
}
else if (postType == JSON)
{
con.setRequestProperty("Content-Type", "application/json");
JsonObject urlParamsObj = new JsonObject();
urlParamsObj.addProperty("client_id", client);
urlParamsObj.addProperty("redirect_uri", redirectUri);
urlParamsObj.addProperty("client_secret", secret);
if (code != null)
{
urlParamsObj.addProperty("code", code);
urlParamsObj.addProperty("grant_type", "authorization_code");
}
else
{
urlParamsObj.addProperty("refresh_token", refreshToken);
urlParamsObj.addProperty("grant_type", "refresh_token");
jsonResponse = true;
}
urlParameters.append(urlParamsObj.toString());
}
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters.toString());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer authRes = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
authRes.append(inputLine);
}
in.close();
response.status = con.getResponseCode();
Gson gson = new Gson();
JsonObject json = gson.fromJson(authRes.toString(), JsonElement.class).getAsJsonObject();
String accessToken = getAccessToken(json);
int expiresIn = getExpiresIn(json);
response.refreshToken = getRefreshToken(json);
response.accessToken = accessToken;
JsonObject respObj = new JsonObject();
respObj.addProperty("access_token", accessToken);
if (expiresIn > -1)
{
respObj.addProperty("expires_in", expiresIn);
}
if (directResp)
{
response.content = respObj.toString();
}
else
{
// Writes JavaScript code
response.content = processAuthResponse(respObj.toString(), jsonResponse);
}
}
catch(IOException e)
{
StringBuilder details = new StringBuilder("");
if (con != null)
{
try
{
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.err.println(inputLine);
details.append(inputLine);
details.append("\n");
}
in.close();
}
catch (Exception e2)
{
// Ignore
}
}
if (e.getMessage() != null && e.getMessage().contains("401"))
{
response.status = HttpServletResponse.SC_UNAUTHORIZED;
}
else if (retryCount > 0 && e.getMessage() != null && e.getMessage().contains("Connection timed out"))
{
return contactOAuthServer(authSrvUrl, code, refreshToken, secret,
client, redirectUri, directResp, --retryCount);
}
else
{
response.status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
e.printStackTrace();
log.log(Level.SEVERE, "AUTH-SERVLET: [" + authSrvUrl+ "] ERROR: " + e.getMessage() + " -> " + details.toString());
}
if (DEBUG)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.println(details.toString());
pw.flush();
response.content = sw.toString();
}
}
return response;
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/AbsAuth.java |
45,331 | /*
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.bitcoinj.core;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.Runnables;
import com.google.common.util.concurrent.Uninterruptibles;
import net.jcip.annotations.GuardedBy;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.internal.InternalUtils;
import org.bitcoinj.base.internal.PlatformUtils;
import org.bitcoinj.base.internal.Stopwatch;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.listeners.AddressEventListener;
import org.bitcoinj.core.listeners.BlockchainDownloadEventListener;
import org.bitcoinj.core.listeners.BlocksDownloadedEventListener;
import org.bitcoinj.core.listeners.ChainDownloadStartedEventListener;
import org.bitcoinj.core.listeners.DownloadProgressTracker;
import org.bitcoinj.core.listeners.GetDataEventListener;
import org.bitcoinj.core.listeners.OnTransactionBroadcastListener;
import org.bitcoinj.core.listeners.PeerConnectedEventListener;
import org.bitcoinj.core.listeners.PeerDisconnectedEventListener;
import org.bitcoinj.core.listeners.PeerDiscoveredEventListener;
import org.bitcoinj.core.listeners.PreMessageReceivedEventListener;
import org.bitcoinj.net.ClientConnectionManager;
import org.bitcoinj.net.FilterMerger;
import org.bitcoinj.net.NioClientManager;
import org.bitcoinj.net.discovery.MultiplexingDiscovery;
import org.bitcoinj.net.discovery.PeerDiscovery;
import org.bitcoinj.net.discovery.PeerDiscoveryException;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.utils.ContextPropagatingThreadFactory;
import org.bitcoinj.utils.ExponentialBackoff;
import org.bitcoinj.utils.ListenableCompletableFuture;
import org.bitcoinj.utils.ListenerRegistration;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.listeners.KeyChainEventListener;
import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener;
import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener;
import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.SocketAddress;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
import static org.bitcoinj.base.internal.Preconditions.checkState;
/**
* <p>Runs a set of connections to the P2P network, brings up connections to replace disconnected nodes and manages
* the interaction between them all. Most applications will want to use one of these.</p>
*
* <p>PeerGroup tries to maintain a constant number of connections to a set of distinct peers.
* Each peer runs a network listener in its own thread. When a connection is lost, a new peer
* will be tried after a delay as long as the number of connections less than the maximum.</p>
*
* <p>Connections are made to addresses from a provided list. When that list is exhausted,
* we start again from the head of the list.</p>
*
* <p>The PeerGroup can broadcast a transaction to the currently connected set of peers. It can
* also handle download of the blockchain from peers, restarting the process when peers die.</p>
*
* <p>A PeerGroup won't do anything until you call the {@link PeerGroup#start()} method
* which will block until peer discovery is completed and some outbound connections
* have been initiated (it will return before handshaking is done, however).
* You should call {@link PeerGroup#stop()} when finished. Note that not all methods
* of PeerGroup are safe to call from a UI thread as some may do network IO,
* but starting and stopping the service should be fine.</p>
*/
public class PeerGroup implements TransactionBroadcaster {
private static final Logger log = LoggerFactory.getLogger(PeerGroup.class);
protected final ReentrantLock lock = Threading.lock(PeerGroup.class);
// All members in this class should be marked with final, volatile, @GuardedBy or a mix as appropriate to define
// their thread safety semantics. Volatile requires a Hungarian-style v prefix.
// By default we don't require any services because any peer will do.
private long requiredServices = 0;
/**
* The default number of connections to the p2p network the library will try to build. This is set to 12 empirically.
* It used to be 4, but because we divide the connection pool in two for broadcasting transactions, that meant we
* were only sending transactions to two peers and sometimes this wasn't reliable enough: transactions wouldn't
* get through.
*/
public static final int DEFAULT_CONNECTIONS = 12;
private volatile int vMaxPeersToDiscoverCount = 100;
private static final Duration DEFAULT_PEER_DISCOVERY_TIMEOUT = Duration.ofSeconds(5);
private volatile Duration vPeerDiscoveryTimeout = DEFAULT_PEER_DISCOVERY_TIMEOUT;
protected final NetworkParameters params;
@Nullable protected final AbstractBlockChain chain;
// This executor is used to queue up jobs: it's used when we don't want to use locks for mutual exclusion,
// typically because the job might call in to user provided code that needs/wants the freedom to use the API
// however it wants, or because a job needs to be ordered relative to other jobs like that.
protected final ScheduledExecutorService executor;
// Whether the peer group is currently running. Once shut down it cannot be restarted.
private volatile boolean vRunning;
// Whether the peer group has been started or not. An unstarted PG does not try to access the network.
private volatile boolean vUsedUp;
// Addresses to try to connect to, excluding active peers.
@GuardedBy("lock") private final PriorityQueue<PeerAddress> inactives;
@GuardedBy("lock") private final Map<PeerAddress, ExponentialBackoff> backoffMap;
@GuardedBy("lock") private final Map<PeerAddress, Integer> priorityMap;
// Currently active peers. This is an ordered list rather than a set to make unit tests predictable.
private final CopyOnWriteArrayList<Peer> peers;
// Currently connecting peers.
private final CopyOnWriteArrayList<Peer> pendingPeers;
private final ClientConnectionManager channels;
// The peer that has been selected for the purposes of downloading announced data.
@GuardedBy("lock") private Peer downloadPeer;
// Callback for events related to chain download.
@Nullable @GuardedBy("lock") private BlockchainDownloadEventListener downloadListener;
private final CopyOnWriteArrayList<ListenerRegistration<BlocksDownloadedEventListener>> peersBlocksDownloadedEventListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<ChainDownloadStartedEventListener>> peersChainDownloadStartedEventListeners
= new CopyOnWriteArrayList<>();
/** Callbacks for events related to peers connecting */
protected final CopyOnWriteArrayList<ListenerRegistration<PeerConnectedEventListener>> peerConnectedEventListeners
= new CopyOnWriteArrayList<>();
/** Callbacks for events related to peer connection/disconnection */
protected final CopyOnWriteArrayList<ListenerRegistration<PeerDiscoveredEventListener>> peerDiscoveredEventListeners
= new CopyOnWriteArrayList<>();
/** Callbacks for events related to peers disconnecting */
protected final CopyOnWriteArrayList<ListenerRegistration<PeerDisconnectedEventListener>> peerDisconnectedEventListeners
= new CopyOnWriteArrayList<>();
/** Callbacks for events related to peer data being received */
private final CopyOnWriteArrayList<ListenerRegistration<GetDataEventListener>> peerGetDataEventListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<PreMessageReceivedEventListener>> peersPreMessageReceivedEventListeners
= new CopyOnWriteArrayList<>();
protected final CopyOnWriteArrayList<ListenerRegistration<OnTransactionBroadcastListener>> peersTransactionBroadastEventListeners
= new CopyOnWriteArrayList<>();
// Discover peers via addr and addrv2 messages?
private volatile boolean vDiscoverPeersViaP2P = false;
// Peer discovery sources, will be polled occasionally if there aren't enough inactives.
private final CopyOnWriteArraySet<PeerDiscovery> peerDiscoverers;
// The version message to use for new connections.
@GuardedBy("lock") private VersionMessage versionMessage;
// Maximum depth up to which pending transaction dependencies are downloaded, or 0 for disabled.
@GuardedBy("lock") private int downloadTxDependencyDepth;
// How many connections we want to have open at the current time. If we lose connections, we'll try opening more
// until we reach this count.
@GuardedBy("lock") private int maxConnections;
// Minimum protocol version we will allow ourselves to connect to: require Bloom filtering.
private volatile int vMinRequiredProtocolVersion;
/** How many milliseconds to wait after receiving a pong before sending another ping. */
public static final long DEFAULT_PING_INTERVAL_MSEC = 2000;
@GuardedBy("lock") private long pingIntervalMsec = DEFAULT_PING_INTERVAL_MSEC;
@GuardedBy("lock") private boolean useLocalhostPeerWhenPossible = true;
@GuardedBy("lock") private boolean ipv6Unreachable = false;
@GuardedBy("lock") private Instant fastCatchupTime;
private final CopyOnWriteArrayList<Wallet> wallets;
private final CopyOnWriteArrayList<PeerFilterProvider> peerFilterProviders;
// This event listener is added to every peer. It's here so when we announce transactions via an "inv", every
// peer can fetch them.
private final PeerListener peerListener = new PeerListener();
private int minBroadcastConnections = 0;
private final ScriptsChangeEventListener walletScriptsEventListener = (wallet, scripts, isAddingScripts) -> recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED);
private final KeyChainEventListener walletKeyEventListener = keys -> recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED);
private final WalletCoinsReceivedEventListener walletCoinsReceivedEventListener = (wallet, tx, prevBalance, newBalance) -> onCoinsReceivedOrSent(wallet, tx);
private final WalletCoinsSentEventListener walletCoinsSentEventListener = (wallet, tx, prevBalance, newBalance) -> onCoinsReceivedOrSent(wallet, tx);
public static final int MAX_ADDRESSES_PER_ADDR_MESSAGE = 16;
private void onCoinsReceivedOrSent(Wallet wallet, Transaction tx) {
// We received a relevant transaction. We MAY need to recalculate and resend the Bloom filter, but only
// if we have received a transaction that includes a relevant P2PK or P2WPKH output.
//
// The reason is that P2PK and P2WPKH outputs, when spent, will not repeat any data we can predict in their
// inputs. So a remote peer will update the Bloom filter for us when such an output is seen matching the
// existing filter, so that it includes the tx hash in which the P2PK/P2WPKH output was observed. Thus
// the spending transaction will always match (due to the outpoint structure).
//
// Unfortunately, whilst this is required for correct sync of the chain in blocks, there are two edge cases.
//
// (1) If a wallet receives a relevant, confirmed P2PK/P2WPKH output that was not broadcast across the network,
// for example in a coinbase transaction, then the node that's serving us the chain will update its filter
// but the rest will not. If another transaction then spends it, the other nodes won't match/relay it.
//
// (2) If we receive a P2PK/P2WPKH output broadcast across the network, all currently connected nodes will see
// it and update their filter themselves, but any newly connected nodes will receive the last filter we
// calculated, which would not include this transaction.
//
// For this reason we check if the transaction contained any relevant P2PKs or P2WPKHs and force a recalc
// and possibly retransmit if so. The recalculation process will end up including the tx hash into the
// filter. In case (1), we need to retransmit the filter to the connected peers. In case (2), we don't
// and shouldn't, we should just recalculate and cache the new filter for next time.
for (TransactionOutput output : tx.getOutputs()) {
Script scriptPubKey = output.getScriptPubKey();
if (ScriptPattern.isP2PK(scriptPubKey) || ScriptPattern.isP2WPKH(scriptPubKey)) {
if (output.isMine(wallet)) {
if (tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED);
else
recalculateFastCatchupAndFilter(FilterRecalculateMode.DONT_SEND);
return;
}
}
}
}
// Exponential backoff for peers starts at 1 second and maxes at 10 minutes.
private final ExponentialBackoff.Params peerBackoffParams = new ExponentialBackoff.Params(Duration.ofSeconds(1),
1.5f, Duration.ofMinutes(10));
// Tracks failures globally in case of a network failure.
@GuardedBy("lock") private ExponentialBackoff groupBackoff = new ExponentialBackoff(new ExponentialBackoff.Params(Duration.ofSeconds(1), 1.5f, Duration.ofSeconds(10)));
// This is a synchronized set, so it locks on itself. We use it to prevent TransactionBroadcast objects from
// being garbage collected if nothing in the apps code holds on to them transitively. See the discussion
// in broadcastTransaction.
private final Set<TransactionBroadcast> runningBroadcasts;
private class PeerListener implements GetDataEventListener, BlocksDownloadedEventListener, AddressEventListener {
public PeerListener() {
}
@Override
public List<Message> getData(Peer peer, GetDataMessage m) {
return handleGetData(m);
}
@Override
public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
if (chain == null) return;
final double rate = chain.getFalsePositiveRate();
final double target = bloomFilterMerger.getBloomFilterFPRate() * MAX_FP_RATE_INCREASE;
if (rate > target) {
// TODO: Avoid hitting this path if the remote peer didn't acknowledge applying a new filter yet.
log.info("Force update Bloom filter due to high false positive rate ({} vs {})", rate, target);
recalculateFastCatchupAndFilter(FilterRecalculateMode.FORCE_SEND_FOR_REFRESH);
}
}
/**
* Called when a peer receives an {@code addr} or {@code addrv2} message, usually in response to a
* {@code getaddr} message.
*
* @param peer the peer that received the addr or addrv2 message
* @param message the addr or addrv2 message that was received
*/
@Override
public void onAddr(Peer peer, AddressMessage message) {
if (!vDiscoverPeersViaP2P)
return;
List<PeerAddress> addresses = new LinkedList<>(message.getAddresses());
// Make sure we pick random addresses.
Collections.shuffle(addresses);
int numAdded = 0;
for (PeerAddress address : addresses) {
if (!address.getServices().has(requiredServices))
continue;
// Add to inactive pool with slightly elevated priority because services fit.
boolean added = addInactive(address, 1);
if (added)
numAdded++;
// Limit addresses picked per message.
if (numAdded >= MAX_ADDRESSES_PER_ADDR_MESSAGE)
break;
}
log.info("{} gossiped {} addresses, added {} of them to the inactive pool", peer.getAddress(),
addresses.size(), numAdded);
}
}
private class PeerStartupListener implements PeerConnectedEventListener, PeerDisconnectedEventListener {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
handleNewPeer(peer);
}
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
// The channel will be automatically removed from channels.
handlePeerDeath(peer, null);
}
}
private final PeerStartupListener startupListener = new PeerStartupListener();
/**
* The default Bloom filter false positive rate, which is selected to be extremely low such that you hardly ever
* download false positives. This provides maximum performance. Although this default can be overridden to push
* the FP rate higher, due to <a href="https://groups.google.com/forum/#!msg/bitcoinj/Ys13qkTwcNg/9qxnhwnkeoIJ">
* various complexities</a> there are still ways a remote peer can deanonymize the users wallet. This is why the
* FP rate is chosen for performance rather than privacy. If a future version of bitcoinj fixes the known
* de-anonymization attacks this FP rate may rise again (or more likely, become expressed as a bandwidth allowance).
*/
public static final double DEFAULT_BLOOM_FILTER_FP_RATE = 0.00001;
/** Maximum increase in FP rate before forced refresh of the bloom filter */
public static final double MAX_FP_RATE_INCREASE = 10.0f;
// An object that calculates bloom filters given a list of filter providers, whilst tracking some state useful
// for privacy purposes.
private final FilterMerger bloomFilterMerger;
/** The default timeout between when a connection attempt begins and version message exchange completes */
public static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(5);
private volatile Duration vConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
/** Whether bloom filter support is enabled when using a non FullPrunedBlockchain*/
private volatile boolean vBloomFilteringEnabled = true;
/**
* Creates a PeerGroup for the given network. No chain is provided so this node will report its chain height
* as zero to other peers. This constructor is useful if you just want to explore the network but aren't interested
* in downloading block data.
* @param network the P2P network to connect to
*/
public PeerGroup(Network network) {
this(network, null);
}
/**
* Creates a PeerGroup with the given network. No chain is provided so this node will report its chain height
* as zero to other peers. This constructor is useful if you just want to explore the network but aren't interested
* in downloading block data.
* @deprecated Use {@link #PeerGroup(Network)}
*/
@Deprecated
public PeerGroup(NetworkParameters params) {
this(params.network());
}
/**
* Creates a PeerGroup for the given network and chain. Blocks will be passed to the chain as they are broadcast
* and downloaded. This is probably the constructor you want to use.
* @param network the P2P network to connect to
* @param chain used to process blocks
*/
public PeerGroup(Network network, @Nullable AbstractBlockChain chain) {
this(network, chain, new NioClientManager());
}
/**
* Creates a PeerGroup for the given network and chain. Blocks will be passed to the chain as they are broadcast
* and downloaded.
* @deprecated Use {@link PeerGroup#PeerGroup(Network, AbstractBlockChain)}
*/
@Deprecated
public PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain) {
this(params.network(), chain);
}
/**
* Create a PeerGroup for the given network, chain and connection manager.
* @param network the P2P network to connect to
* @param chain used to process blocks
* @param connectionManager used to create new connections and keep track of existing ones.
*/
protected PeerGroup(Network network, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) {
this(NetworkParameters.of(Objects.requireNonNull(network)), chain, connectionManager, DEFAULT_BLOOM_FILTER_FP_RATE);
}
/**
* Create a PeerGroup for the given network, chain and connection manager.
* @param network the P2P network to connect to
* @param chain used to process blocks
* @param connectionManager used to create new connections and keep track of existing ones.
* @param bloomFilterFpRate false positive rate for bloom filters
*/
protected PeerGroup(Network network, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager, double bloomFilterFpRate) {
this(NetworkParameters.of(Objects.requireNonNull(network)), chain, connectionManager, bloomFilterFpRate);
}
/**
* Create a PeerGroup for the given network, chain and connection manager.
* @param params the P2P network to connect to
* @param chain used to process blocks
* @param connectionManager used to create new connections and keep track of existing ones.
* @param bloomFilterFpRate false positive rate for bloom filters
*/
// For testing only
protected PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager, double bloomFilterFpRate) {
Objects.requireNonNull(params);
Context.getOrCreate(); // create a context for convenience
this.params = params;
this.chain = chain;
fastCatchupTime = params.getGenesisBlock().time();
wallets = new CopyOnWriteArrayList<>();
peerFilterProviders = new CopyOnWriteArrayList<>();
executor = createPrivateExecutor();
// This default sentinel value will be overridden by one of two actions:
// - adding a peer discovery source sets it to the default
// - using connectTo() will increment it by one
maxConnections = 0;
int height = chain == null ? 0 : chain.getBestChainHeight();
versionMessage = new VersionMessage(params, height);
// We never request that the remote node wait for a bloom filter yet, as we have no wallets
versionMessage.relayTxesBeforeFilter = true;
downloadTxDependencyDepth = Integer.MAX_VALUE;
inactives = new PriorityQueue<>(1, new Comparator<PeerAddress>() {
@SuppressWarnings("FieldAccessNotGuarded") // only called when inactives is accessed, and lock is held then.
@Override
public int compare(PeerAddress a, PeerAddress b) {
checkState(lock.isHeldByCurrentThread());
int result = backoffMap.get(a).compareTo(backoffMap.get(b));
if (result != 0)
return result;
result = Integer.compare(getPriority(a), getPriority(b));
if (result != 0)
return result;
// Sort by port if otherwise equals - for testing
result = Integer.compare(a.getPort(), b.getPort());
return result;
}
});
backoffMap = new HashMap<>();
priorityMap = new ConcurrentHashMap<>();
peers = new CopyOnWriteArrayList<>();
pendingPeers = new CopyOnWriteArrayList<>();
channels = connectionManager;
peerDiscoverers = new CopyOnWriteArraySet<>();
runningBroadcasts = Collections.synchronizedSet(new HashSet<TransactionBroadcast>());
bloomFilterMerger = new FilterMerger(bloomFilterFpRate);
vMinRequiredProtocolVersion = ProtocolVersion.BLOOM_FILTER.intValue();
}
private CountDownLatch executorStartupLatch = new CountDownLatch(1);
protected ScheduledExecutorService createPrivateExecutor() {
ScheduledExecutorService result =
new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("PeerGroup Thread"));
// Hack: jam the executor so jobs just queue up until the user calls start() on us. For example, adding a wallet
// results in a bloom filter recalc being queued, but we don't want to do that until we're actually started.
result.execute(() -> Uninterruptibles.awaitUninterruptibly(executorStartupLatch));
return result;
}
/**
* This is how long we wait for peer discoveries to return their results.
*/
public void setPeerDiscoveryTimeout(Duration peerDiscoveryTimeout) {
this.vPeerDiscoveryTimeout = peerDiscoveryTimeout;
}
/**
* This is how many milliseconds we wait for peer discoveries to return their results.
* @deprecated use {@link #setPeerDiscoveryTimeout(Duration)}
*/
@Deprecated
public void setPeerDiscoveryTimeoutMillis(long peerDiscoveryTimeoutMillis) {
setPeerDiscoveryTimeout(Duration.ofMillis(peerDiscoveryTimeoutMillis));
}
/**
* Adjusts the desired number of connections that we will create to peers. Note that if there are already peers
* open and the new value is lower than the current number of peers, those connections will be terminated. Likewise
* if there aren't enough current connections to meet the new requested max size, some will be added.
*/
public void setMaxConnections(int maxConnections) {
int adjustment;
lock.lock();
try {
this.maxConnections = maxConnections;
if (!isRunning()) return;
} finally {
lock.unlock();
}
// We may now have too many or too few open connections. Add more or drop some to get to the right amount.
adjustment = maxConnections - channels.getConnectedClientCount();
if (adjustment > 0)
triggerConnections();
if (adjustment < 0)
channels.closeConnections(-adjustment);
}
/**
* Configure download of pending transaction dependencies. A change of values only takes effect for newly connected
* peers.
*/
public void setDownloadTxDependencies(int depth) {
lock.lock();
try {
this.downloadTxDependencyDepth = depth;
} finally {
lock.unlock();
}
}
private Runnable triggerConnectionsJob = new Runnable() {
private boolean firstRun = true;
private final Duration MIN_PEER_DISCOVERY_INTERVAL = Duration.ofSeconds(1);
@Override
public void run() {
try {
go();
} catch (Throwable e) {
log.error("Exception when trying to build connections", e); // The executor swallows exceptions :(
}
}
public void go() {
if (!vRunning) return;
boolean doDiscovery = false;
Instant now = TimeUtils.currentTime();
lock.lock();
try {
// First run: try and use a local node if there is one, for the additional security it can provide.
// But, not on Android as there are none for this platform: it could only be a malicious app trying
// to hijack our traffic.
if (!PlatformUtils.isAndroidRuntime() && useLocalhostPeerWhenPossible && maybeCheckForLocalhostPeer() && firstRun) {
log.info("Localhost peer detected, trying to use it instead of P2P discovery");
maxConnections = 0;
connectToLocalHost();
return;
}
boolean havePeerWeCanTry = !inactives.isEmpty() && backoffMap.get(inactives.peek()).retryTime().isBefore(now);
doDiscovery = !havePeerWeCanTry;
} finally {
firstRun = false;
lock.unlock();
}
// Don't hold the lock across discovery as this process can be very slow.
boolean discoverySuccess = false;
if (doDiscovery) {
discoverySuccess = discoverPeers() > 0;
}
lock.lock();
try {
if (doDiscovery) {
// Require that we have enough connections, to consider this
// a success, or we just constantly test for new peers
if (discoverySuccess && countConnectedAndPendingPeers() >= getMaxConnections()) {
groupBackoff.trackSuccess();
} else {
groupBackoff.trackFailure();
}
}
// Inactives is sorted by backoffMap time.
if (inactives.isEmpty()) {
if (countConnectedAndPendingPeers() < getMaxConnections()) {
Duration interval = TimeUtils.longest(Duration.between(now, groupBackoff.retryTime()), MIN_PEER_DISCOVERY_INTERVAL);
log.info("Peer discovery didn't provide us any more peers, will try again in "
+ interval.toMillis() + " ms.");
executor.schedule(this, interval.toMillis(), TimeUnit.MILLISECONDS);
} else {
// We have enough peers and discovery provided no more, so just settle down. Most likely we
// were given a fixed set of addresses in some test scenario.
}
return;
}
PeerAddress addrToTry;
do {
addrToTry = inactives.poll();
} while (ipv6Unreachable && addrToTry.getAddr() instanceof Inet6Address);
if (addrToTry == null) {
// We have exhausted the queue of reachable peers, so just settle down.
// Most likely we were given a fixed set of addresses in some test scenario.
return;
}
Instant retryTime = backoffMap.get(addrToTry).retryTime();
retryTime = TimeUtils.later(retryTime, groupBackoff.retryTime());
if (retryTime.isAfter(now)) {
Duration delay = Duration.between(now, retryTime);
log.info("Waiting {} ms before next connect attempt to {}", delay.toMillis(), addrToTry);
inactives.add(addrToTry);
executor.schedule(this, delay.toMillis(), TimeUnit.MILLISECONDS);
return;
}
connectTo(addrToTry, false, vConnectTimeout);
} finally {
lock.unlock();
}
if (countConnectedAndPendingPeers() < getMaxConnections()) {
executor.execute(this); // Try next peer immediately.
}
}
};
private void triggerConnections() {
// Run on a background thread due to the need to potentially retry and back off in the background.
if (!executor.isShutdown())
executor.execute(triggerConnectionsJob);
}
/** The maximum number of connections that we will create to peers. */
public int getMaxConnections() {
lock.lock();
try {
return maxConnections;
} finally {
lock.unlock();
}
}
private List<Message> handleGetData(GetDataMessage m) {
// Scans the wallets and memory pool for transactions in the getdata message and returns them.
// Runs on peer threads.
lock.lock();
try {
LinkedList<Message> transactions = new LinkedList<>();
LinkedList<InventoryItem> items = new LinkedList<>(m.getItems());
Iterator<InventoryItem> it = items.iterator();
while (it.hasNext()) {
InventoryItem item = it.next();
// Check the wallets.
for (Wallet w : wallets) {
Transaction tx = w.getTransaction(item.hash);
if (tx == null) continue;
transactions.add(tx);
it.remove();
break;
}
}
return transactions;
} finally {
lock.unlock();
}
}
/**
* Sets the {@link VersionMessage} that will be announced on newly created connections. A version message is
* primarily interesting because it lets you customize the "subVer" field which is used a bit like the User-Agent
* field from HTTP. It means your client tells the other side what it is, see
* <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a>.
*
* The VersionMessage you provide is copied and the best chain height/time filled in for each new connection,
* therefore you don't have to worry about setting that. The provided object is really more of a template.
*/
public void setVersionMessage(VersionMessage ver) {
lock.lock();
try {
versionMessage = ver;
} finally {
lock.unlock();
}
}
/**
* Returns the version message provided by setVersionMessage or a default if none was given.
*/
public VersionMessage getVersionMessage() {
lock.lock();
try {
return versionMessage;
} finally {
lock.unlock();
}
}
/**
* Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating
* a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it,
* and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for
* {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain.
*/
public void setUserAgent(String name, String version, @Nullable String comments) {
//TODO Check that height is needed here (it wasnt, but it should be, no?)
int height = chain == null ? 0 : chain.getBestChainHeight();
VersionMessage ver = new VersionMessage(params, height);
ver.relayTxesBeforeFilter = false;
updateVersionMessageRelayTxesBeforeFilter(ver);
ver.appendToSubVer(name, version, comments);
setVersionMessage(ver);
}
// Updates the relayTxesBeforeFilter flag of ver
private void updateVersionMessageRelayTxesBeforeFilter(VersionMessage ver) {
// We will provide the remote node with a bloom filter (ie they shouldn't relay yet)
// if chain == null || !chain.shouldVerifyTransactions() and a wallet is added and bloom filters are enabled
// Note that the default here means that no tx invs will be received if no wallet is ever added
lock.lock();
try {
boolean spvMode = chain != null && !chain.shouldVerifyTransactions();
boolean willSendFilter = spvMode && peerFilterProviders.size() > 0 && vBloomFilteringEnabled;
ver.relayTxesBeforeFilter = !willSendFilter;
} finally {
lock.unlock();
}
}
/**
* Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating
* a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it,
* and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for
* {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain.
*/
public void setUserAgent(String name, String version) {
setUserAgent(name, version, null);
}
/** See {@link Peer#addBlocksDownloadedEventListener(BlocksDownloadedEventListener)} */
public void addBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) {
addBlocksDownloadedEventListener(Threading.USER_THREAD, listener);
}
/**
* <p>Adds a listener that will be notified on the given executor when
* blocks are downloaded by the download peer.</p>
* @see Peer#addBlocksDownloadedEventListener(Executor, BlocksDownloadedEventListener)
*/
public void addBlocksDownloadedEventListener(Executor executor, BlocksDownloadedEventListener listener) {
peersBlocksDownloadedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addBlocksDownloadedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addBlocksDownloadedEventListener(executor, listener);
}
/** See {@link Peer#addBlocksDownloadedEventListener(BlocksDownloadedEventListener)} */
public void addChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) {
addChainDownloadStartedEventListener(Threading.USER_THREAD, listener);
}
/**
* <p>Adds a listener that will be notified on the given executor when
* chain download starts.</p>
*/
public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) {
peersChainDownloadStartedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addChainDownloadStartedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addChainDownloadStartedEventListener(executor, listener);
}
/** See {@link Peer#addConnectedEventListener(PeerConnectedEventListener)} */
public void addConnectedEventListener(PeerConnectedEventListener listener) {
addConnectedEventListener(Threading.USER_THREAD, listener);
}
/**
* <p>Adds a listener that will be notified on the given executor when
* new peers are connected to.</p>
*/
public void addConnectedEventListener(Executor executor, PeerConnectedEventListener listener) {
peerConnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addConnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addConnectedEventListener(executor, listener);
}
/** See {@link Peer#addDisconnectedEventListener(PeerDisconnectedEventListener)} */
public void addDisconnectedEventListener(PeerDisconnectedEventListener listener) {
addDisconnectedEventListener(Threading.USER_THREAD, listener);
}
/**
* <p>Adds a listener that will be notified on the given executor when
* peers are disconnected from.</p>
*/
public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) {
peerDisconnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addDisconnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addDisconnectedEventListener(executor, listener);
}
/** See {@link PeerGroup#addDiscoveredEventListener(Executor, PeerDiscoveredEventListener)} */
public void addDiscoveredEventListener(PeerDiscoveredEventListener listener) {
addDiscoveredEventListener(Threading.USER_THREAD, listener);
}
/**
* <p>Adds a listener that will be notified on the given executor when new
* peers are discovered.</p>
*/
public void addDiscoveredEventListener(Executor executor, PeerDiscoveredEventListener listener) {
peerDiscoveredEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
}
/** See {@link Peer#addGetDataEventListener(GetDataEventListener)} */
public void addGetDataEventListener(GetDataEventListener listener) {
addGetDataEventListener(Threading.USER_THREAD, listener);
}
/** See {@link Peer#addGetDataEventListener(Executor, GetDataEventListener)} */
public void addGetDataEventListener(final Executor executor, final GetDataEventListener listener) {
peerGetDataEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addGetDataEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addGetDataEventListener(executor, listener);
}
/** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */
public void addOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) {
addOnTransactionBroadcastListener(Threading.USER_THREAD, listener);
}
/** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */
public void addOnTransactionBroadcastListener(Executor executor, OnTransactionBroadcastListener listener) {
peersTransactionBroadastEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addOnTransactionBroadcastListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addOnTransactionBroadcastListener(executor, listener);
}
/** See {@link Peer#addPreMessageReceivedEventListener(PreMessageReceivedEventListener)} */
public void addPreMessageReceivedEventListener(PreMessageReceivedEventListener listener) {
addPreMessageReceivedEventListener(Threading.USER_THREAD, listener);
}
/** See {@link Peer#addPreMessageReceivedEventListener(Executor, PreMessageReceivedEventListener)} */
public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) {
peersPreMessageReceivedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addPreMessageReceivedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addPreMessageReceivedEventListener(executor, listener);
}
public boolean removeBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peersBlocksDownloadedEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeBlocksDownloadedEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removeBlocksDownloadedEventListener(listener);
return result;
}
public boolean removeChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peersChainDownloadStartedEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeChainDownloadStartedEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removeChainDownloadStartedEventListener(listener);
return result;
}
/** The given event listener will no longer be called with events. */
public boolean removeConnectedEventListener(PeerConnectedEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peerConnectedEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeConnectedEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removeConnectedEventListener(listener);
return result;
}
/** The given event listener will no longer be called with events. */
public boolean removeDisconnectedEventListener(PeerDisconnectedEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peerDisconnectedEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeDisconnectedEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removeDisconnectedEventListener(listener);
return result;
}
/** The given event listener will no longer be called with events. */
public boolean removeDiscoveredEventListener(PeerDiscoveredEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peerDiscoveredEventListeners);
return result;
}
/** The given event listener will no longer be called with events. */
public boolean removeGetDataEventListener(GetDataEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peerGetDataEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeGetDataEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removeGetDataEventListener(listener);
return result;
}
/** The given event listener will no longer be called with events. */
public boolean removeOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peersTransactionBroadastEventListeners);
for (Peer peer : getConnectedPeers())
peer.removeOnTransactionBroadcastListener(listener);
for (Peer peer : getPendingPeers())
peer.removeOnTransactionBroadcastListener(listener);
return result;
}
public boolean removePreMessageReceivedEventListener(PreMessageReceivedEventListener listener) {
boolean result = ListenerRegistration.removeFromList(listener, peersPreMessageReceivedEventListeners);
for (Peer peer : getConnectedPeers())
peer.removePreMessageReceivedEventListener(listener);
for (Peer peer : getPendingPeers())
peer.removePreMessageReceivedEventListener(listener);
return result;
}
/**
* Returns a newly allocated list containing the currently connected peers. If all you care about is the count,
* use numConnectedPeers().
*/
public List<Peer> getConnectedPeers() {
lock.lock();
try {
return new ArrayList<>(peers);
} finally {
lock.unlock();
}
}
/**
* Returns a list containing Peers that did not complete connection yet.
*/
public List<Peer> getPendingPeers() {
lock.lock();
try {
return new ArrayList<>(pendingPeers);
} finally {
lock.unlock();
}
}
/**
* Add an address to the list of potential peers to connect to. It won't necessarily be used unless there's a need
* to build new connections to reach the max connection count.
*
* @param peerAddress IP/port to use.
*/
public void addAddress(PeerAddress peerAddress) {
addAddress(peerAddress, 0);
}
/**
* Add an address to the list of potential peers to connect to. It won't necessarily be used unless there's a need
* to build new connections to reach the max connection count.
*
* @param peerAddress IP/port to use.
* @param priority for connecting and being picked as a download peer
*/
public void addAddress(PeerAddress peerAddress, int priority) {
int newMax;
lock.lock();
try {
if (addInactive(peerAddress, priority)) {
newMax = getMaxConnections() + 1;
setMaxConnections(newMax);
}
} finally {
lock.unlock();
}
}
// Adds peerAddress to backoffMap map and inactives queue.
// Returns true if it was added, false if it was already there.
private boolean addInactive(PeerAddress peerAddress, int priority) {
lock.lock();
try {
// Deduplicate
if (backoffMap.containsKey(peerAddress))
return false;
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams));
if (priority != 0)
priorityMap.put(peerAddress, priority);
inactives.offer(peerAddress);
return true;
} finally {
lock.unlock();
}
}
private int getPriority(PeerAddress peerAddress) {
Integer priority = priorityMap.get(peerAddress);
return priority != null ? priority : 0;
}
/**
* Convenience for connecting only to peers that can serve specific services. It will configure suitable peer
* discoveries.
* @param requiredServices Required services as a bitmask, e.g. {@link Services#NODE_NETWORK}.
*/
public void setRequiredServices(long requiredServices) {
lock.lock();
try {
this.requiredServices = requiredServices;
peerDiscoverers.clear();
addPeerDiscovery(MultiplexingDiscovery.forServices(params.network(), requiredServices));
} finally {
lock.unlock();
}
}
/** Convenience method for {@link #addAddress(PeerAddress)}. */
public void addAddress(InetAddress address) {
addAddress(PeerAddress.simple(address, params.getPort()));
}
/** Convenience method for {@link #addAddress(PeerAddress, int)}. */
public void addAddress(InetAddress address, int priority) {
addAddress(PeerAddress.simple(address, params.getPort()), priority);
}
/**
* Setting this to {@code true} will add addresses discovered via P2P {@code addr} and {@code addrv2} messages to
* the list of potential peers to connect to. This will automatically be set to true if at least one peer discovery
* is added via {@link #addPeerDiscovery(PeerDiscovery)}.
*
* @param discoverPeersViaP2P true if peers should be discovered from the P2P network
*/
public void setDiscoverPeersViaP2P(boolean discoverPeersViaP2P) {
vDiscoverPeersViaP2P = discoverPeersViaP2P;
}
/**
* Add addresses from a discovery source to the list of potential peers to connect to. If max connections has not
* been configured, or set to zero, then it's set to the default at this point.
*/
public void addPeerDiscovery(PeerDiscovery peerDiscovery) {
lock.lock();
try {
if (getMaxConnections() == 0)
setMaxConnections(DEFAULT_CONNECTIONS);
peerDiscoverers.add(peerDiscovery);
} finally {
lock.unlock();
}
setDiscoverPeersViaP2P(true);
}
/** Returns number of discovered peers. */
protected int discoverPeers() {
// Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
checkState(!lock.isHeldByCurrentThread());
int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
Duration peerDiscoveryTimeout = this.vPeerDiscoveryTimeout;
Stopwatch watch = Stopwatch.start();
final List<PeerAddress> addressList = new LinkedList<>();
for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
List<InetSocketAddress> addresses;
try {
addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeout);
} catch (PeerDiscoveryException e) {
log.warn(e.getMessage());
continue;
}
for (InetSocketAddress address : addresses) addressList.add(PeerAddress.simple(address));
if (addressList.size() >= maxPeersToDiscoverCount) break;
}
if (!addressList.isEmpty()) {
for (PeerAddress address : addressList) {
addInactive(address, 0);
}
final Set<PeerAddress> peersDiscoveredSet = Collections.unmodifiableSet(new HashSet<>(addressList));
for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
registration.executor.execute(() -> registration.listener.onPeersDiscovered(peersDiscoveredSet));
}
}
log.info("Peer discovery took {} and returned {} items from {} discoverers",
watch, addressList.size(), peerDiscoverers.size());
return addressList.size();
}
// For testing only
void waitForJobQueue() {
Futures.getUnchecked(executor.submit(Runnables.doNothing()));
}
private int countConnectedAndPendingPeers() {
lock.lock();
try {
return peers.size() + pendingPeers.size();
} finally {
lock.unlock();
}
}
private enum LocalhostCheckState {
NOT_TRIED,
FOUND,
FOUND_AND_CONNECTED,
NOT_THERE
}
private LocalhostCheckState localhostCheckState = LocalhostCheckState.NOT_TRIED;
private boolean maybeCheckForLocalhostPeer() {
checkState(lock.isHeldByCurrentThread());
if (localhostCheckState == LocalhostCheckState.NOT_TRIED) {
// Do a fast blocking connect to see if anything is listening.
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), params.getPort()),
Math.toIntExact(vConnectTimeout.toMillis()));
localhostCheckState = LocalhostCheckState.FOUND;
return true;
} catch (IOException e) {
log.info("Localhost peer not detected.");
localhostCheckState = LocalhostCheckState.NOT_THERE;
}
}
return false;
}
/**
* Starts the PeerGroup and begins network activity.
* @return A future that completes when first connection activity has been triggered (note: not first connection made).
*/
public ListenableCompletableFuture<Void> startAsync() {
// This is run in a background thread by the Service implementation.
if (chain == null) {
// Just try to help catch what might be a programming error.
log.warn("Starting up with no attached block chain. Did you forget to pass one to the constructor?");
}
checkState(!vUsedUp, () ->
"cannot start a peer group twice");
vRunning = true;
vUsedUp = true;
executorStartupLatch.countDown();
// We do blocking waits during startup, so run on the executor thread.
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
log.info("Starting ...");
channels.startAsync();
channels.awaitRunning();
triggerConnections();
setupPinging();
} catch (Throwable e) {
log.error("Exception when starting up", e); // The executor swallows exceptions :(
}
}, executor);
return ListenableCompletableFuture.of(future);
}
/** Does a blocking startup. */
public void start() {
startAsync().join();
}
public ListenableCompletableFuture<Void> stopAsync() {
checkState(vRunning);
vRunning = false;
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
log.info("Stopping ...");
Stopwatch watch = Stopwatch.start();
// The log output this creates can be useful.
setDownloadPeer(null);
// Blocking close of all sockets.
channels.stopAsync();
channels.awaitTerminated();
for (PeerDiscovery peerDiscovery : peerDiscoverers) {
peerDiscovery.shutdown();
}
vRunning = false;
log.info("Stopped, took {}.", watch);
} catch (Throwable e) {
log.error("Exception when shutting down", e); // The executor swallows exceptions :(
}
}, executor);
executor.shutdown();
return ListenableCompletableFuture.of(future);
}
/** Does a blocking stop */
public void stop() {
try {
Stopwatch watch = Stopwatch.start();
stopAsync();
log.info("Awaiting PeerGroup shutdown ...");
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
log.info("... took {}", watch);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Gracefully drops all connected peers.
*/
public void dropAllPeers() {
lock.lock();
try {
for (Peer peer : peers)
peer.close();
} finally {
lock.unlock();
}
}
/**
* <p>Link the given wallet to this PeerGroup. This is used for three purposes:</p>
*
* <ol>
* <li>So the wallet receives broadcast transactions.</li>
* <li>Announcing pending transactions that didn't get into the chain yet to our peers.</li>
* <li>Set the fast catchup time using {@link PeerGroup#setFastCatchupTimeSecs(long)}, to optimize chain
* download.</li>
* </ol>
*
* <p>Note that this should be done before chain download commences because if you add a wallet with keys earlier
* than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p>
*
* <p>The Wallet will have an event listener registered on it, so to avoid leaks remember to use
* {@link PeerGroup#removeWallet(Wallet)} on it if you wish to keep the Wallet but lose the PeerGroup.</p>
*/
public void addWallet(Wallet wallet) {
lock.lock();
try {
Objects.requireNonNull(wallet);
checkState(!wallets.contains(wallet));
wallets.add(wallet);
wallet.setTransactionBroadcaster(this);
wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, walletCoinsReceivedEventListener);
wallet.addCoinsSentEventListener(Threading.SAME_THREAD, walletCoinsSentEventListener);
wallet.addKeyChainEventListener(Threading.SAME_THREAD, walletKeyEventListener);
wallet.addScriptsChangeEventListener(Threading.SAME_THREAD, walletScriptsEventListener);
addPeerFilterProvider(wallet);
for (Peer peer : peers) {
peer.addWallet(wallet);
}
} finally {
lock.unlock();
}
}
/**
* <p>Link the given PeerFilterProvider to this PeerGroup. DO NOT use this for Wallets, use
* {@link PeerGroup#addWallet(Wallet)} instead.</p>
*
* <p>Note that this should be done before chain download commences because if you add a listener with keys earlier
* than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p>
*
* <p>This method invokes {@link PeerGroup#recalculateFastCatchupAndFilter(FilterRecalculateMode)}.
* The return value of this method is the {@code ListenableCompletableFuture} returned by that invocation.</p>
*
* @return a future that completes once each {@code Peer} in this group has had its
* {@code BloomFilter} (re)set.
*/
public ListenableCompletableFuture<BloomFilter> addPeerFilterProvider(PeerFilterProvider provider) {
lock.lock();
try {
Objects.requireNonNull(provider);
checkState(!peerFilterProviders.contains(provider));
// Insert provider at the start. This avoids various concurrency problems that could occur because we need
// all providers to be in a consistent, unchanging state whilst the filter is built. Providers can give
// this guarantee by taking a lock in their begin method, but if we add to the end of the list here, it
// means we establish a lock ordering a > b > c if that's the order the providers were added in. Given that
// the main wallet will usually be first, this establishes an ordering wallet > other-provider, which means
// other-provider can then not call into the wallet itself. Other providers installed by the API user should
// come first so the expected ordering is preserved. This can also manifest itself in providers that use
// synchronous RPCs into an actor instead of locking, but the same issue applies.
peerFilterProviders.add(0, provider);
// Don't bother downloading block bodies before the oldest keys in all our wallets. Make sure we recalculate
// if a key is added. Of course, by then we may have downloaded the chain already. Ideally adding keys would
// automatically rewind the block chain and redownload the blocks to find transactions relevant to those keys,
// all transparently and in the background. But we are a long way from that yet.
ListenableCompletableFuture<BloomFilter> future = recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED);
updateVersionMessageRelayTxesBeforeFilter(getVersionMessage());
return future;
} finally {
lock.unlock();
}
}
/**
* Opposite of {@link #addPeerFilterProvider(PeerFilterProvider)}. Again, don't use this for wallets. Does not
* trigger recalculation of the filter.
*/
public void removePeerFilterProvider(PeerFilterProvider provider) {
lock.lock();
try {
Objects.requireNonNull(provider);
checkArgument(peerFilterProviders.remove(provider));
} finally {
lock.unlock();
}
}
/**
* Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced.
*/
public void removeWallet(Wallet wallet) {
wallets.remove(Objects.requireNonNull(wallet));
peerFilterProviders.remove(wallet);
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
wallet.removeCoinsSentEventListener(walletCoinsSentEventListener);
wallet.removeKeyChainEventListener(walletKeyEventListener);
wallet.removeScriptsChangeEventListener(walletScriptsEventListener);
wallet.setTransactionBroadcaster(null);
for (Peer peer : peers) {
peer.removeWallet(wallet);
}
}
public enum FilterRecalculateMode {
SEND_IF_CHANGED,
FORCE_SEND_FOR_REFRESH,
DONT_SEND,
}
private final Map<FilterRecalculateMode, ListenableCompletableFuture<BloomFilter>> inFlightRecalculations = Maps.newHashMap();
/**
* Recalculates the bloom filter given to peers as well as the timestamp after which full blocks are downloaded
* (instead of only headers). Note that calls made one after another may return the same future, if the request
* wasn't processed yet (i.e. calls are deduplicated).
*
* @param mode In what situations to send the filter to connected peers.
* @return a future that completes once the filter has been calculated (note: this does not mean acknowledged by remote peers).
*/
public ListenableCompletableFuture<BloomFilter> recalculateFastCatchupAndFilter(final FilterRecalculateMode mode) {
final ListenableCompletableFuture<BloomFilter> future = new ListenableCompletableFuture<>();
synchronized (inFlightRecalculations) {
if (inFlightRecalculations.get(mode) != null)
return inFlightRecalculations.get(mode);
inFlightRecalculations.put(mode, future);
}
Runnable command = new Runnable() {
@Override
public void run() {
try {
go();
} catch (Throwable e) {
log.error("Exception when trying to recalculate Bloom filter", e); // The executor swallows exceptions :(
}
}
public void go() {
checkState(!lock.isHeldByCurrentThread());
// Fully verifying mode doesn't use this optimization (it can't as it needs to see all transactions).
if ((chain != null && chain.shouldVerifyTransactions()) || !vBloomFilteringEnabled)
return;
// We only ever call bloomFilterMerger.calculate on jobQueue, so we cannot be calculating two filters at once.
FilterMerger.Result result = bloomFilterMerger.calculate(Collections.unmodifiableList(peerFilterProviders /* COW */));
boolean send;
switch (mode) {
case SEND_IF_CHANGED:
send = result.changed;
break;
case DONT_SEND:
send = false;
break;
case FORCE_SEND_FOR_REFRESH:
send = true;
break;
default:
throw new UnsupportedOperationException();
}
if (send) {
for (Peer peer : peers /* COW */) {
// Only query the mempool if this recalculation request is not in order to lower the observed FP
// rate. There's no point querying the mempool when doing this because the FP rate can only go
// down, and we will have seen all the relevant txns before: it's pointless to ask for them again.
peer.setBloomFilter(result.filter, mode != FilterRecalculateMode.FORCE_SEND_FOR_REFRESH);
}
// Reset the false positive estimate so that we don't send a flood of filter updates
// if the estimate temporarily overshoots our threshold.
if (chain != null)
chain.resetFalsePositiveEstimate();
}
// Do this last so that bloomFilter is already set when it gets called.
setFastCatchupTime(result.earliestKeyTime);
synchronized (inFlightRecalculations) {
inFlightRecalculations.put(mode, null);
}
future.complete(result.filter);
}
};
try {
executor.execute(command);
} catch (RejectedExecutionException e) {
// Can happen during shutdown.
}
return future;
}
/**
* <p>Sets the false positive rate of bloom filters given to peers. The default is {@link #DEFAULT_BLOOM_FILTER_FP_RATE}.</p>
*
* <p>Be careful regenerating the bloom filter too often, as it decreases anonymity because remote nodes can
* compare transactions against both the new and old filters to significantly decrease the false positive rate.</p>
*
* <p>See the docs for {@link BloomFilter#BloomFilter(int, double, int, BloomFilter.BloomUpdate)} for a brief
* explanation of anonymity when using bloom filters.</p>
*/
@Deprecated
public void setBloomFilterFalsePositiveRate(double bloomFilterFPRate) {
lock.lock();
try {
bloomFilterMerger.setBloomFilterFPRate(bloomFilterFPRate);
recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED);
} finally {
lock.unlock();
}
}
/**
* Returns the number of currently connected peers. To be informed when this count changes, use
* {@link PeerConnectedEventListener#onPeerConnected} and {@link PeerDisconnectedEventListener#onPeerDisconnected}.
*/
public int numConnectedPeers() {
return peers.size();
}
/**
* Connect to a peer by creating a channel to the destination address. This should not be
* used normally - let the PeerGroup manage connections through {@link #start()}
*
* @param address destination IP and port.
* @return The newly created Peer object or null if the peer could not be connected.
* Use {@link Peer#getConnectionOpenFuture()} if you
* want a future which completes when the connection is open.
*/
@Nullable
public Peer connectTo(InetSocketAddress address) {
lock.lock();
try {
PeerAddress peerAddress = PeerAddress.simple(address);
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams));
return connectTo(peerAddress, true, vConnectTimeout);
} finally {
lock.unlock();
}
}
/**
* Helper for forcing a connection to localhost. Useful when using regtest mode. Returns the peer object.
*/
@Nullable
public Peer connectToLocalHost() {
lock.lock();
try {
final PeerAddress localhost = PeerAddress.localhost(params);
backoffMap.put(localhost, new ExponentialBackoff(peerBackoffParams));
return connectTo(localhost, true, vConnectTimeout);
} finally {
lock.unlock();
}
}
/**
* Creates a version message to send, constructs a Peer object and attempts to connect it. Returns the peer on
* success or null on failure.
* @param address Remote network address
* @param incrementMaxConnections Whether to consider this connection an attempt to fill our quota, or something
* explicitly requested.
* @param connectTimeout timeout for establishing the connection to peers
* @return Peer or null.
*/
@Nullable @GuardedBy("lock")
protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, Duration connectTimeout) {
checkState(lock.isHeldByCurrentThread());
VersionMessage ver = getVersionMessage().duplicate();
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
ver.receivingAddr = new InetSocketAddress(address.getAddr(), address.getPort());
Peer peer = createPeer(address, ver);
peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
try {
log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address,
peers.size(), pendingPeers.size(), maxConnections);
CompletableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer);
if (future.isDone())
InternalUtils.getUninterruptibly(future);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
log.warn("Failed to connect to " + address + ": " + cause.getMessage());
handlePeerDeath(peer, cause);
return null;
}
peer.setSocketTimeout(connectTimeout);
// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on
// a worker thread.
if (incrementMaxConnections) {
// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new
// outbound connection.
maxConnections++;
}
return peer;
}
/** You can override this to customise the creation of {@link Peer} objects. */
@GuardedBy("lock")
protected Peer createPeer(PeerAddress address, VersionMessage ver) {
return new Peer(params, ver, address, chain, requiredServices, downloadTxDependencyDepth);
}
/**
* Sets the timeout between when a connection attempt to a peer begins and when the version message exchange
* completes. This does not apply to currently pending peers.
* @param connectTimeout timeout for estiablishing the connection to peers
*/
public void setConnectTimeout(Duration connectTimeout) {
this.vConnectTimeout = connectTimeout;
}
/** @deprecated use {@link #setConnectTimeout(Duration)} */
@Deprecated
public void setConnectTimeoutMillis(int connectTimeoutMillis) {
setConnectTimeout(Duration.ofMillis(connectTimeoutMillis));
}
/**
* <p>Start downloading the blockchain.</p>
*
* <p>If no peers are currently connected, the download will be started once a peer starts. If the peer dies,
* the download will resume with another peer.</p>
*
* @param listener a listener for chain download events, may not be null
*/
public void startBlockChainDownload(BlockchainDownloadEventListener listener) {
lock.lock();
try {
if (downloadPeer != null) {
if (this.downloadListener != null) {
removeDataEventListenerFromPeer(downloadPeer, this.downloadListener);
}
if (listener != null) {
addDataEventListenerToPeer(Threading.USER_THREAD, downloadPeer, listener);
}
}
this.downloadListener = listener;
} finally {
lock.unlock();
}
}
/**
* Register a data event listener against a single peer (i.e. for blockchain
* download). Handling registration/deregistration on peer death/add is
* outside the scope of these methods.
*/
private static void addDataEventListenerToPeer(Executor executor, Peer peer, BlockchainDownloadEventListener downloadListener) {
peer.addBlocksDownloadedEventListener(executor, downloadListener);
peer.addChainDownloadStartedEventListener(executor, downloadListener);
}
/**
* Remove a registered data event listener against a single peer (i.e. for
* blockchain download). Handling registration/deregistration on peer death/add is
* outside the scope of these methods.
*/
private static void removeDataEventListenerFromPeer(Peer peer, BlockchainDownloadEventListener listener) {
peer.removeBlocksDownloadedEventListener(listener);
peer.removeChainDownloadStartedEventListener(listener);
}
/**
* Download the blockchain from peers. Convenience that uses a {@link DownloadProgressTracker} for you.<p>
*
* This method waits until the download is complete. "Complete" is defined as downloading
* from at least one peer all the blocks that are in that peer's inventory.
*/
public void downloadBlockChain() {
DownloadProgressTracker listener = new DownloadProgressTracker();
startBlockChainDownload(listener);
try {
listener.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
protected void handleNewPeer(final Peer peer) {
int newSize = -1;
lock.lock();
try {
groupBackoff.trackSuccess();
backoffMap.get(peer.getAddress()).trackSuccess();
// Sets up the newly connected peer so it can do everything it needs to.
pendingPeers.remove(peer);
peers.add(peer);
newSize = peers.size();
log.info("{}: New peer ({} connected, {} pending, {} max)", peer, newSize, pendingPeers.size(), maxConnections);
// Give the peer a filter that can be used to probabilistically drop transactions that
// aren't relevant to our wallet. We may still receive some false positives, which is
// OK because it helps improve wallet privacy. Old nodes will just ignore the message.
if (bloomFilterMerger.getLastFilter() != null) peer.setBloomFilter(bloomFilterMerger.getLastFilter());
peer.setDownloadData(false);
// TODO: The peer should calculate the fast catchup time from the added wallets here.
for (Wallet wallet : wallets)
peer.addWallet(wallet);
if (downloadPeer == null && newSize > maxConnections / 2) {
Peer newDownloadPeer = selectDownloadPeer(peers);
if (newDownloadPeer != null) {
setDownloadPeer(newDownloadPeer);
// Kick off chain download if we aren't already doing it.
boolean shouldDownloadChain = downloadListener != null && chain != null;
if (shouldDownloadChain) {
startBlockChainDownloadFromPeer(downloadPeer);
}
} else {
log.info("Not yet setting download peer because there is no clear candidate.");
}
}
// Make sure the peer knows how to upload transactions that are requested from us.
peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, peerListener);
peer.addGetDataEventListener(Threading.SAME_THREAD, peerListener);
// Discover other peers.
peer.addAddressEventListener(Threading.SAME_THREAD, peerListener);
// And set up event listeners for clients. This will allow them to find out about new transactions and blocks.
for (ListenerRegistration<BlocksDownloadedEventListener> registration : peersBlocksDownloadedEventListeners)
peer.addBlocksDownloadedEventListener(registration.executor, registration.listener);
for (ListenerRegistration<ChainDownloadStartedEventListener> registration : peersChainDownloadStartedEventListeners)
peer.addChainDownloadStartedEventListener(registration.executor, registration.listener);
for (ListenerRegistration<PeerConnectedEventListener> registration : peerConnectedEventListeners)
peer.addConnectedEventListener(registration.executor, registration.listener);
// We intentionally do not add disconnect listeners to peers
for (ListenerRegistration<GetDataEventListener> registration : peerGetDataEventListeners)
peer.addGetDataEventListener(registration.executor, registration.listener);
for (ListenerRegistration<OnTransactionBroadcastListener> registration : peersTransactionBroadastEventListeners)
peer.addOnTransactionBroadcastListener(registration.executor, registration.listener);
for (ListenerRegistration<PreMessageReceivedEventListener> registration : peersPreMessageReceivedEventListeners)
peer.addPreMessageReceivedEventListener(registration.executor, registration.listener);
} finally {
lock.unlock();
}
final int fNewSize = newSize;
for (final ListenerRegistration<PeerConnectedEventListener> registration : peerConnectedEventListeners) {
registration.executor.execute(() -> registration.listener.onPeerConnected(peer, fNewSize));
}
// Discovery more peers.
if (vDiscoverPeersViaP2P)
peer.sendMessage(new GetAddrMessage());
}
@Nullable private volatile ScheduledFuture<?> vPingTask;
@SuppressWarnings("NonAtomicOperationOnVolatileField")
private void setupPinging() {
if (getPingIntervalMsec() <= 0)
return; // Disabled.
vPingTask = executor.scheduleAtFixedRate(() -> {
try {
if (getPingIntervalMsec() <= 0) {
ScheduledFuture<?> task = vPingTask;
if (task != null) {
task.cancel(false);
vPingTask = null;
}
return; // Disabled.
}
for (Peer peer : getConnectedPeers()) {
peer.sendPing();
}
} catch (Throwable e) {
log.error("Exception in ping loop", e); // The executor swallows exceptions :(
}
}, getPingIntervalMsec(), getPingIntervalMsec(), TimeUnit.MILLISECONDS);
}
private void setDownloadPeer(@Nullable Peer peer) {
lock.lock();
try {
if (downloadPeer == peer)
return;
if (downloadPeer != null) {
log.info("Unsetting download peer: {}", downloadPeer);
if (downloadListener != null) {
removeDataEventListenerFromPeer(downloadPeer, downloadListener);
}
downloadPeer.setDownloadData(false);
}
downloadPeer = peer;
if (downloadPeer != null) {
log.info("Setting download peer: {}", downloadPeer);
if (downloadListener != null) {
addDataEventListenerToPeer(Threading.SAME_THREAD, peer, downloadListener);
}
downloadPeer.setDownloadData(true);
if (chain != null)
downloadPeer.setFastDownloadParameters(bloomFilterMerger.getLastFilter() != null, fastCatchupTime);
}
} finally {
lock.unlock();
}
}
/** Use "Context.get().getConfidenceTable()" instead */
@Deprecated @Nullable
public TxConfidenceTable getMemoryPool() {
return Context.get().getConfidenceTable();
}
/**
* Tells the {@link PeerGroup} to download only block headers before a certain time and bodies after that. Call this
* before starting block chain download.
* Do not use a {@code time > NOW - 1} block, as it will break some block download logic.
*/
public void setFastCatchupTime(Instant fastCatchupTime) {
lock.lock();
try {
checkState(chain == null || !chain.shouldVerifyTransactions(), () ->
"fast catchup is incompatible with fully verifying");
this.fastCatchupTime = fastCatchupTime;
if (downloadPeer != null) {
downloadPeer.setFastDownloadParameters(bloomFilterMerger.getLastFilter() != null, fastCatchupTime);
}
} finally {
lock.unlock();
}
}
/** @deprecated use {@link #setFastCatchupTime(Instant)} */
@Deprecated
public void setFastCatchupTimeSecs(long fastCatchupTimeSecs) {
setFastCatchupTime(Instant.ofEpochSecond(fastCatchupTimeSecs));
}
/**
* Returns the current fast catchup time. The contents of blocks before this time won't be downloaded as they
* cannot contain any interesting transactions. If you use {@link PeerGroup#addWallet(Wallet)} this just returns
* the min of the wallets earliest key times.
* @return a time in seconds since the epoch
*/
public Instant fastCatchupTime() {
lock.lock();
try {
return fastCatchupTime;
} finally {
lock.unlock();
}
}
/** @deprecated use {@link #fastCatchupTime()} */
@Deprecated
public long getFastCatchupTimeSecs() {
return fastCatchupTime().getEpochSecond();
}
protected void handlePeerDeath(final Peer peer, @Nullable Throwable exception) {
// Peer deaths can occur during startup if a connect attempt after peer discovery aborts immediately.
if (!isRunning()) return;
int numPeers;
int numConnectedPeers = 0;
lock.lock();
try {
pendingPeers.remove(peer);
peers.remove(peer);
PeerAddress address = peer.getAddress();
log.info("{}: Peer died ({} connected, {} pending, {} max)", address, peers.size(), pendingPeers.size(), maxConnections);
if (peer == downloadPeer) {
log.info("Download peer died. Picking a new one.");
setDownloadPeer(null);
// Pick a new one and possibly tell it to download the chain.
final Peer newDownloadPeer = selectDownloadPeer(peers);
if (newDownloadPeer != null) {
setDownloadPeer(newDownloadPeer);
if (downloadListener != null) {
startBlockChainDownloadFromPeer(newDownloadPeer);
}
}
}
numPeers = peers.size() + pendingPeers.size();
numConnectedPeers = peers.size();
groupBackoff.trackFailure();
if (exception instanceof NoRouteToHostException) {
if (address.getAddr() instanceof Inet6Address && !ipv6Unreachable) {
ipv6Unreachable = true;
log.warn("IPv6 peer connect failed due to routing failure, ignoring IPv6 addresses from now on");
}
} else {
backoffMap.get(address).trackFailure();
// Put back on inactive list
inactives.offer(address);
}
if (numPeers < getMaxConnections()) {
triggerConnections();
}
} finally {
lock.unlock();
}
peer.removeAddressEventListener(peerListener);
peer.removeBlocksDownloadedEventListener(peerListener);
peer.removeGetDataEventListener(peerListener);
for (Wallet wallet : wallets) {
peer.removeWallet(wallet);
}
final int fNumConnectedPeers = numConnectedPeers;
for (ListenerRegistration<BlocksDownloadedEventListener> registration: peersBlocksDownloadedEventListeners)
peer.removeBlocksDownloadedEventListener(registration.listener);
for (ListenerRegistration<ChainDownloadStartedEventListener> registration: peersChainDownloadStartedEventListeners)
peer.removeChainDownloadStartedEventListener(registration.listener);
for (ListenerRegistration<GetDataEventListener> registration: peerGetDataEventListeners)
peer.removeGetDataEventListener(registration.listener);
for (ListenerRegistration<PreMessageReceivedEventListener> registration: peersPreMessageReceivedEventListeners)
peer.removePreMessageReceivedEventListener(registration.listener);
for (ListenerRegistration<OnTransactionBroadcastListener> registration : peersTransactionBroadastEventListeners)
peer.removeOnTransactionBroadcastListener(registration.listener);
for (final ListenerRegistration<PeerDisconnectedEventListener> registration : peerDisconnectedEventListeners) {
registration.executor.execute(() -> registration.listener.onPeerDisconnected(peer, fNumConnectedPeers));
peer.removeDisconnectedEventListener(registration.listener);
}
}
@GuardedBy("lock") private int stallPeriodSeconds = 10;
@GuardedBy("lock") private int stallMinSpeedBytesSec = Block.HEADER_SIZE * 10;
/**
* Configures the stall speed: the speed at which a peer is considered to be serving us the block chain
* unacceptably slowly. Once a peer has served us data slower than the given data rate for the given
* number of seconds, it is considered stalled and will be disconnected, forcing the chain download to continue
* from a different peer. The defaults are chosen conservatively, but if you are running on a platform that is
* CPU constrained or on a very slow network e.g. EDGE, the default settings may need adjustment to
* avoid false stalls.
*
* @param periodSecs How many seconds the download speed must be below blocksPerSec, defaults to 10.
* @param bytesPerSecond Download speed (only blocks/txns count) must be consistently below this for a stall, defaults to the bandwidth required for 10 block headers per second.
*/
public void setStallThreshold(int periodSecs, int bytesPerSecond) {
lock.lock();
try {
stallPeriodSeconds = periodSecs;
stallMinSpeedBytesSec = bytesPerSecond;
} finally {
lock.unlock();
}
}
private class ChainDownloadSpeedCalculator implements BlocksDownloadedEventListener, Runnable {
private int blocksInLastSecond, txnsInLastSecond, origTxnsInLastSecond;
private long bytesInLastSecond;
// If we take more stalls than this, we assume we're on some kind of terminally slow network and the
// stall threshold just isn't set properly. We give up on stall disconnects after that.
private int maxStalls = 3;
// How many seconds the peer has until we start measuring its speed.
private int warmupSeconds = -1;
// Used to calculate a moving average.
private long[] samples;
private int cursor;
private boolean syncDone;
private final Logger log = LoggerFactory.getLogger(ChainDownloadSpeedCalculator.class);
@Override
public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
blocksInLastSecond++;
bytesInLastSecond += Block.HEADER_SIZE;
List<Transaction> blockTransactions = block.getTransactions();
// This whole area of the type hierarchy is a mess.
int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) +
(filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0);
txnsInLastSecond = txnsInLastSecond + txCount;
if (filteredBlock != null)
origTxnsInLastSecond += filteredBlock.getTransactionCount();
}
private int countAndMeasureSize(Collection<Transaction> transactions) {
for (Transaction transaction : transactions)
bytesInLastSecond += transaction.messageSize();
return transactions.size();
}
@Override
public void run() {
try {
calculate();
} catch (Throwable e) {
log.error("Error in speed calculator", e);
}
}
private void calculate() {
int minSpeedBytesPerSec;
int period;
lock.lock();
try {
minSpeedBytesPerSec = stallMinSpeedBytesSec;
period = stallPeriodSeconds;
} finally {
lock.unlock();
}
synchronized (this) {
if (samples == null || samples.length != period) {
samples = new long[period];
// *2 because otherwise a single low sample could cause an immediate disconnect which is too harsh.
Arrays.fill(samples, minSpeedBytesPerSec * 2);
warmupSeconds = 15;
}
int chainHeight = chain != null ? chain.getBestChainHeight() : -1;
int mostCommonChainHeight = getMostCommonChainHeight();
if (!syncDone && mostCommonChainHeight > 0 && chainHeight >= mostCommonChainHeight) {
log.info("End of sync detected at height {}.", chainHeight);
syncDone = true;
}
if (!syncDone) {
// Calculate the moving average.
samples[cursor++] = bytesInLastSecond;
if (cursor == samples.length) cursor = 0;
long sampleSum = 0;
for (long sample : samples) sampleSum += sample;
final float average = (float) sampleSum / samples.length;
String statsString = String.format(Locale.US,
"%d blocks/sec, %d tx/sec, %d pre-filtered tx/sec, avg/last %.2f/%.2f kilobytes per sec, chain/common height %d/%d",
blocksInLastSecond, txnsInLastSecond, origTxnsInLastSecond, average / 1024.0,
bytesInLastSecond / 1024.0, chainHeight, mostCommonChainHeight);
String thresholdString = String.format(Locale.US, "(threshold <%.2f KB/sec for %d seconds)",
minSpeedBytesPerSec / 1024.0, samples.length);
if (maxStalls <= 0) {
log.info(statsString + ", stall disabled " + thresholdString);
} else if (warmupSeconds > 0) {
warmupSeconds--;
if (bytesInLastSecond > 0)
log.info(statsString
+ String.format(Locale.US, " (warming up %d more seconds)", warmupSeconds));
} else if (average < minSpeedBytesPerSec) {
log.info(statsString + ", STALLED " + thresholdString);
maxStalls--;
if (maxStalls == 0) {
// We could consider starting to drop the Bloom filtering FP rate at this point, because
// we tried a bunch of peers and no matter what we don't seem to be able to go any faster.
// This implies we're bandwidth bottlenecked and might want to start using bandwidth
// more effectively. Of course if there's a MITM that is deliberately throttling us,
// this is a good way to make us take away all the FPs from our Bloom filters ... but
// as they don't give us a whole lot of privacy either way that's not inherently a big
// deal.
log.warn("This network seems to be slower than the requested stall threshold - won't do stall disconnects any more.");
} else {
Peer peer = getDownloadPeer();
log.warn(String.format(Locale.US,
"Chain download stalled: received %.2f KB/sec for %d seconds, require average of %.2f KB/sec, disconnecting %s, %d stalls left",
average / 1024.0, samples.length, minSpeedBytesPerSec / 1024.0, peer, maxStalls));
peer.close();
// Reset the sample buffer and give the next peer time to get going.
samples = null;
warmupSeconds = period;
}
} else {
log.info(statsString + ", not stalled " + thresholdString);
}
}
blocksInLastSecond = 0;
txnsInLastSecond = 0;
origTxnsInLastSecond = 0;
bytesInLastSecond = 0;
}
}
}
@Nullable private ChainDownloadSpeedCalculator chainDownloadSpeedCalculator;
// For testing only
void startBlockChainDownloadFromPeer(Peer peer) {
lock.lock();
try {
setDownloadPeer(peer);
if (chainDownloadSpeedCalculator == null) {
// Every second, run the calculator which will log how fast we are downloading the chain.
chainDownloadSpeedCalculator = new ChainDownloadSpeedCalculator();
executor.scheduleAtFixedRate(chainDownloadSpeedCalculator, 1, 1, TimeUnit.SECONDS);
}
peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, chainDownloadSpeedCalculator);
// startBlockChainDownload will setDownloadData(true) on itself automatically.
peer.startBlockChainDownload();
} finally {
lock.unlock();
}
}
/**
* Returns a future that is triggered when the number of connected peers is equal to the given number of
* peers. By using this with {@link PeerGroup#getMaxConnections()} you can wait until the
* network is fully online. To block immediately, just call get() on the result. Just calls
* {@link #waitForPeersOfVersion(int, long)} with zero as the protocol version.
*
* @param numPeers How many peers to wait for.
* @return a future that will be triggered when the number of connected peers is greater than or equals numPeers
*/
public ListenableCompletableFuture<List<Peer>> waitForPeers(final int numPeers) {
return waitForPeersOfVersion(numPeers, 0);
}
/**
* Returns a future that is triggered when there are at least the requested number of connected peers that support
* the given protocol version or higher. To block immediately, just call get() on the result.
*
* @param numPeers How many peers to wait for.
* @param protocolVersion The protocol version the awaited peers must implement (or better).
* @return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers
*/
public ListenableCompletableFuture<List<Peer>> waitForPeersOfVersion(final int numPeers, final long protocolVersion) {
List<Peer> foundPeers = findPeersOfAtLeastVersion(protocolVersion);
if (foundPeers.size() >= numPeers) {
ListenableCompletableFuture<List<Peer>> f = new ListenableCompletableFuture<>();
f.complete(foundPeers);
return f;
}
final ListenableCompletableFuture<List<Peer>> future = new ListenableCompletableFuture<List<Peer>>();
addConnectedEventListener(new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
final List<Peer> peers = findPeersOfAtLeastVersion(protocolVersion);
if (peers.size() >= numPeers) {
future.complete(peers);
removeConnectedEventListener(this);
}
}
});
return future;
}
/**
* Returns an array list of peers that implement the given protocol version or better.
*/
public List<Peer> findPeersOfAtLeastVersion(long protocolVersion) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if (peer.getPeerVersionMessage().clientVersion >= protocolVersion)
results.add(peer);
return results;
} finally {
lock.unlock();
}
}
/**
* Returns a future that is triggered when there are at least the requested number of connected peers that support
* the given protocol version or higher. To block immediately, just call get() on the result.
*
* @param numPeers How many peers to wait for.
* @param mask An integer representing a bit mask that will be ANDed with the peers advertised service masks.
* @return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers
*/
public ListenableCompletableFuture<List<Peer>> waitForPeersWithServiceMask(final int numPeers, final int mask) {
lock.lock();
try {
List<Peer> foundPeers = findPeersWithServiceMask(mask);
if (foundPeers.size() >= numPeers) {
ListenableCompletableFuture<List<Peer>> f = new ListenableCompletableFuture<>();
f.complete(foundPeers);
return f;
}
final ListenableCompletableFuture<List<Peer>> future = new ListenableCompletableFuture<>();
addConnectedEventListener(new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
final List<Peer> peers = findPeersWithServiceMask(mask);
if (peers.size() >= numPeers) {
future.complete(peers);
removeConnectedEventListener(this);
}
}
});
return future;
} finally {
lock.unlock();
}
}
/**
* Returns an array list of peers that match the requested service bit mask.
*/
public List<Peer> findPeersWithServiceMask(int mask) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if (peer.getPeerVersionMessage().localServices.has(mask))
results.add(peer);
return results;
} finally {
lock.unlock();
}
}
/**
* Returns the number of connections that are required before transactions will be broadcast. If there aren't
* enough, {@link PeerGroup#broadcastTransaction(Transaction)} will wait until the minimum number is reached so
* propagation across the network can be observed. If no value has been set using
* {@link PeerGroup#setMinBroadcastConnections(int)} a default of 80% of whatever
* {@link PeerGroup#getMaxConnections()} returns is used.
*/
public int getMinBroadcastConnections() {
lock.lock();
try {
if (minBroadcastConnections == 0) {
int max = getMaxConnections();
if (max <= 1)
return max;
else
return (int) Math.round(getMaxConnections() * 0.8);
}
return minBroadcastConnections;
} finally {
lock.unlock();
}
}
/**
* See {@link PeerGroup#getMinBroadcastConnections()}.
*/
public void setMinBroadcastConnections(int value) {
lock.lock();
try {
minBroadcastConnections = value;
} finally {
lock.unlock();
}
}
/**
* Calls {@link PeerGroup#broadcastTransaction(Transaction, int, boolean)} with getMinBroadcastConnections() as
* the number of connections to wait for before commencing broadcast. Also, if the transaction has no broadcast
* confirmations yet the peers will be dropped after the transaction has been sent.
*/
@Override
public TransactionBroadcast broadcastTransaction(final Transaction tx) {
return broadcastTransaction(tx, Math.max(1, getMinBroadcastConnections()), true);
}
/**
* <p>Given a transaction, sends it un-announced to one peer and then waits for it to be received back from other
* peers. Once all connected peers have announced the transaction, the future available via the
* {@link TransactionBroadcast#awaitRelayed()} ()} method will be completed. If anything goes
* wrong the exception will be thrown when get() is called, or you can receive it via a callback on the
* {@link ListenableCompletableFuture}. This method returns immediately, so if you want it to block just call get() on the
* result.</p>
*
* <p>Optionally, peers will be dropped after they have been used for broadcasting the transaction and they have
* no broadcast confirmations yet.</p>
*
* <p>Note that if the PeerGroup is limited to only one connection (discovery is not activated) then the future
* will complete as soon as the transaction was successfully written to that peer.</p>
*
* <p>The transaction won't be sent until there are at least minConnections active connections available.
* A good choice for proportion would be between 0.5 and 0.8 but if you want faster transmission during initial
* bringup of the peer group you can lower it.</p>
*
* <p>The returned {@link TransactionBroadcast} object can be used to get progress feedback,
* which is calculated by watching the transaction propagate across the network and be announced by peers.</p>
*/
public TransactionBroadcast broadcastTransaction(final Transaction tx, final int minConnections,
final boolean dropPeersAfterBroadcast) {
// If we don't have a record of where this tx came from already, set it to be ourselves so Peer doesn't end up
// redownloading it from the network redundantly.
if (tx.getConfidence().getSource().equals(TransactionConfidence.Source.UNKNOWN)) {
log.info("Transaction source unknown, setting to SELF: {}", tx.getTxId());
tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
}
final TransactionBroadcast broadcast = new TransactionBroadcast(this, tx);
broadcast.setMinConnections(minConnections);
broadcast.setDropPeersAfterBroadcast(dropPeersAfterBroadcast && tx.getConfidence().numBroadcastPeers() == 0);
// Send the TX to the wallet once we have a successful broadcast.
broadcast.awaitRelayed().whenComplete((bcast, throwable) -> {
if (bcast != null) {
runningBroadcasts.remove(bcast);
// OK, now tell the wallet about the transaction. If the wallet created the transaction then
// it already knows and will ignore this. If it's a transaction we received from
// somebody else via a side channel and are now broadcasting, this will put it into the
// wallet now we know it's valid.
for (Wallet wallet : wallets) {
// Assumption here is there are no dependencies of the created transaction.
//
// We may end up with two threads trying to do this in parallel - the wallet will
// ignore whichever one loses the race.
try {
wallet.receivePending(bcast.transaction(), null);
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot fail to verify a tx we created ourselves.
}
}
} else {
// This can happen if we get a reject message from a peer.
runningBroadcasts.remove(bcast);
}
});
// Keep a reference to the TransactionBroadcast object. This is important because otherwise, the entire tree
// of objects we just created would become garbage if the user doesn't hold on to the returned future, and
// eventually be collected. This in turn could result in the transaction not being committed to the wallet
// at all.
runningBroadcasts.add(broadcast);
broadcast.broadcastOnly();
return broadcast;
}
/**
* Returns the period between pings for an individual peer. Setting this lower means more accurate and timely ping
* times are available via {@link Peer#lastPingInterval()} but it increases load on the
* remote node. It defaults to {@link PeerGroup#DEFAULT_PING_INTERVAL_MSEC}.
*/
public long getPingIntervalMsec() {
lock.lock();
try {
return pingIntervalMsec;
} finally {
lock.unlock();
}
}
/**
* Sets the period between pings for an individual peer. Setting this lower means more accurate and timely ping
* times are available via {@link Peer#lastPingInterval()} but it increases load on the
* remote node. It defaults to {@link PeerGroup#DEFAULT_PING_INTERVAL_MSEC}.
* Setting the value to be smaller or equals 0 disables pinging entirely, although you can still request one yourself
* using {@link Peer#sendPing()}.
*/
public void setPingIntervalMsec(long pingIntervalMsec) {
lock.lock();
try {
this.pingIntervalMsec = pingIntervalMsec;
ScheduledFuture<?> task = vPingTask;
if (task != null)
task.cancel(false);
setupPinging();
} finally {
lock.unlock();
}
}
/**
* If a peer is connected to that claims to speak a protocol version lower than the given version, it will
* be disconnected and another one will be tried instead.
*/
public void setMinRequiredProtocolVersion(int minRequiredProtocolVersion) {
this.vMinRequiredProtocolVersion = minRequiredProtocolVersion;
}
/** The minimum protocol version required: defaults to the version required for Bloom filtering. */
public int getMinRequiredProtocolVersion() {
return vMinRequiredProtocolVersion;
}
/**
* Returns our peers most commonly reported chain height.
* If the most common heights are tied, or no peers are connected, returns {@code 0}.
*/
public int getMostCommonChainHeight() {
lock.lock();
try {
return getMostCommonChainHeight(this.peers);
} finally {
lock.unlock();
}
}
/**
* Returns most commonly reported chain height from the given list of {@link Peer}s.
* If the most common heights are tied, or no peers are connected, returns {@code 0}.
*/
public static int getMostCommonChainHeight(final List<Peer> peers) {
if (peers.isEmpty())
return 0;
List<Integer> heights = new ArrayList<>(peers.size());
for (Peer peer : peers) heights.add((int) peer.getBestHeight());
return maxOfMostFreq(heights);
}
private static class Pair implements Comparable<Pair> {
final int item;
int count = 0;
public Pair(int item) { this.item = item; }
// note that in this implementation compareTo() is not consistent with equals()
@Override public int compareTo(Pair o) { return -Integer.compare(count, o.count); }
}
static int maxOfMostFreq(List<Integer> items) {
if (items.isEmpty())
return 0;
// This would be much easier in a functional language (or in Java 8).
items = Ordering.natural().reverse().sortedCopy(items);
LinkedList<Pair> pairs = new LinkedList<>();
pairs.add(new Pair(items.get(0)));
for (int item : items) {
Pair pair = pairs.getLast();
if (pair.item != item)
pairs.add((pair = new Pair(item)));
pair.count++;
}
// pairs now contains a uniquified list of the sorted inputs, with counts for how often that item appeared.
// Now sort by how frequently they occur, and pick the most frequent. If the first place is tied between two,
// don't pick any.
Collections.sort(pairs);
final Pair firstPair = pairs.get(0);
if (pairs.size() == 1)
return firstPair.item;
final Pair secondPair = pairs.get(1);
if (firstPair.count > secondPair.count)
return firstPair.item;
checkState(firstPair.count == secondPair.count);
return 0;
}
/**
* Given a list of Peers, return a Peer to be used as the download peer. If you don't want PeerGroup to manage
* download peer statuses for you, just override this and always return null.
*/
@Nullable
protected Peer selectDownloadPeer(List<Peer> peers) {
// Characteristics to select for in order of importance:
// - Chain height is reasonable (majority of nodes)
// - High enough protocol version for the features we want (but we'll settle for less)
// - Randomly, to try and spread the load.
if (peers.isEmpty())
return null;
int mostCommonChainHeight = getMostCommonChainHeight(peers);
// Make sure we don't select a peer if there is no consensus about block height.
if (mostCommonChainHeight == 0)
return null;
// Only select peers that announce the minimum protocol and services and that we think is fully synchronized.
List<Peer> candidates = new LinkedList<>();
int highestPriority = Integer.MIN_VALUE;
final int MINIMUM_VERSION = ProtocolVersion.WITNESS_VERSION.intValue();
for (Peer peer : peers) {
final VersionMessage versionMessage = peer.getPeerVersionMessage();
if (versionMessage.clientVersion < MINIMUM_VERSION)
continue;
if (!versionMessage.services().has(Services.NODE_NETWORK))
continue;
if (!versionMessage.services().has(Services.NODE_WITNESS))
continue;
final long peerHeight = peer.getBestHeight();
if (peerHeight < mostCommonChainHeight || peerHeight > mostCommonChainHeight + 1)
continue;
candidates.add(peer);
highestPriority = Math.max(highestPriority, getPriority(peer.peerAddress));
}
if (candidates.isEmpty())
return null;
// If there is a difference in priority, consider only the highest.
for (Iterator<Peer> i = candidates.iterator(); i.hasNext(); ) {
Peer peer = i.next();
if (getPriority(peer.peerAddress) < highestPriority)
i.remove();
}
// Random poll.
int index = (int) (Math.random() * candidates.size());
return candidates.get(index);
}
/**
* Returns the currently selected download peer. Bear in mind that it may have changed as soon as this method
* returns. Can return null if no peer was selected.
*/
public Peer getDownloadPeer() {
lock.lock();
try {
return downloadPeer;
} finally {
lock.unlock();
}
}
/**
* Returns the maximum number of {@link Peer}s to discover. This maximum is checked after
* each {@link PeerDiscovery} so this max number can be surpassed.
* @return the maximum number of peers to discover
*/
public int getMaxPeersToDiscoverCount() {
return vMaxPeersToDiscoverCount;
}
/**
* Sets the maximum number of {@link Peer}s to discover. This maximum is checked after
* each {@link PeerDiscovery} so this max number can be surpassed.
* @param maxPeersToDiscoverCount the maximum number of peers to discover
*/
public void setMaxPeersToDiscoverCount(int maxPeersToDiscoverCount) {
this.vMaxPeersToDiscoverCount = maxPeersToDiscoverCount;
}
/** See {@link #setUseLocalhostPeerWhenPossible(boolean)} */
public boolean getUseLocalhostPeerWhenPossible() {
lock.lock();
try {
return useLocalhostPeerWhenPossible;
} finally {
lock.unlock();
}
}
/**
* When true (the default), PeerGroup will attempt to connect to a Bitcoin node running on localhost before
* attempting to use the P2P network. If successful, only localhost will be used. This makes for a simple
* and easy way for a user to upgrade a bitcoinj based app running in SPV mode to fully validating security.
*/
public void setUseLocalhostPeerWhenPossible(boolean useLocalhostPeerWhenPossible) {
lock.lock();
try {
this.useLocalhostPeerWhenPossible = useLocalhostPeerWhenPossible;
} finally {
lock.unlock();
}
}
public boolean isRunning() {
return vRunning;
}
/**
* Can be used to disable Bloom filtering entirely, even in SPV mode. You are very unlikely to need this, it is
* an optimisation for rare cases when full validation is not required but it's still more efficient to download
* full blocks than filtered blocks.
*/
public void setBloomFilteringEnabled(boolean bloomFilteringEnabled) {
this.vBloomFilteringEnabled = bloomFilteringEnabled;
}
/** Returns whether the Bloom filtering protocol optimisation is in use: defaults to true. */
public boolean isBloomFilteringEnabled() {
return vBloomFilteringEnabled;
}
}
| bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java |
45,332 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, 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.yb.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yb.ColumnSchema;
import org.yb.CommonNet;
import org.yb.CommonTypes;
import org.yb.CommonTypes.TableType;
import org.yb.CommonTypes.YQLDatabase;
import org.yb.Schema;
import org.yb.Type;
import org.yb.annotations.InterfaceAudience;
import org.yb.annotations.InterfaceStability;
import org.yb.cdc.CdcConsumer.XClusterRole;
import org.yb.master.CatalogEntityInfo;
import org.yb.master.MasterReplicationOuterClass;
import org.yb.master.CatalogEntityInfo.ReplicationInfoPB;
import org.yb.tserver.TserverTypes;
import org.yb.util.Pair;
import com.google.common.net.HostAndPort;
import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
/**
* A synchronous and thread-safe client for YB.
* <p>
* This class acts as a wrapper around {@link AsyncYBClient}. The {@link Deferred} objects are
* joined against using the default admin operation timeout
* (see {@link org.yb.client.YBClient.YBClientBuilder#defaultAdminOperationTimeoutMs(long)}(long)}).
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class YBClient implements AutoCloseable {
public static final Logger LOG = LoggerFactory.getLogger(YBClient.class);
private final AsyncYBClient asyncClient;
// Number of retries on retriable errors, could make it time based as needed.
private static final int MAX_NUM_RETRIES = 25;
// Redis default table name.
public static final String REDIS_DEFAULT_TABLE_NAME = "redis";
// Redis keyspace name.
public static final String REDIS_KEYSPACE_NAME = "system_redis";
// Redis key column name.
public static final String REDIS_KEY_COLUMN_NAME = "key";
// Log errors every so many errors.
private static final int LOG_ERRORS_EVERY_NUM_ITERS = 100;
// Log info after these many iterations.
private static final int LOG_EVERY_NUM_ITERS = 200;
// Simple way to inject an error on Wait based APIs. If enabled, after first inject,
// it will be turned off. We can enhance it to use more options like every-N etc.
private boolean injectWaitError = false;
public YBClient(AsyncYBClient asyncClient) {
this.asyncClient = asyncClient;
}
/**
* Create redis table options object.
* @param numTablets number of pre-split tablets.
* @return an options object to be used during table creation.
*/
public static CreateTableOptions getRedisTableOptions(int numTablets) {
CreateTableOptions cto = new CreateTableOptions();
if (numTablets <= 0) {
String msg = "Number of tablets " + numTablets + " cannot be less than one.";
LOG.error(msg);
throw new RuntimeException(msg);
}
cto.setTableType(TableType.REDIS_TABLE_TYPE)
.setNumTablets(numTablets);
return cto;
}
/**
* Creates the redis namespace "system_redis".
*
* @throws Exception if the namespace already exists or creation fails.
*/
public void createRedisNamespace() throws Exception {
createRedisNamespace(false);
}
/**
* Creates the redis namespace "system_redis".
*
* @param ifNotExist if true, error is ignored if the namespace already exists.
* @return true if created, false if already exists.
* @throws Exception throws exception on creation failure.
*/
public boolean createRedisNamespace(boolean ifNotExist) throws Exception {
Exception exception = null;
try {
// TODO As there is no way to get an existing namespace or create if it does not exist,
// the RPC call is made first that may fail.
// Change this when we have better support for namespace.
CreateKeyspaceResponse resp = this.createKeyspace(REDIS_KEYSPACE_NAME,
YQLDatabase.YQL_DATABASE_REDIS);
if (resp.hasError()) {
exception = new RuntimeException("Could not create keyspace " + REDIS_KEYSPACE_NAME +
". Error: " + resp.errorMessage());
}
} catch (YBServerException e) {
// The RPC call also throws exception on conflict.
exception = e;
}
if (exception != null) {
String errMsg = exception.getMessage();
if (ifNotExist && errMsg != null && errMsg.contains("ALREADY_PRESENT")) {
LOG.info("Redis namespace {} already exists.", REDIS_KEYSPACE_NAME);
return false;
}
throw exception;
}
return true;
}
/**
* Create a redis table on the cluster with the specified name and tablet count.
* It also creates the redis namespace 'system_redis'.
*
* @param name the table name
* @param numTablets number of pre-split tablets
* @return an object to communicate with the created table.
*/
public YBTable createRedisTable(String name, int numTablets) throws Exception {
createRedisNamespace();
return createTable(REDIS_KEYSPACE_NAME, name, getRedisSchema(),
getRedisTableOptions(numTablets));
}
/**
* Create a redis table on the cluster with the specified name.
* It also creates the redis namespace 'system_redis'.
*
* @param name the table name
* @return an object to communicate with the created table.
*/
public YBTable createRedisTable(String name) throws Exception {
return createRedisTable(name, false);
}
/**
* Create a redis table on the cluster with the specified name.
* It also creates the redis namespace 'system_redis'.
*
* @param name the table name.
* @param ifNotExist if true, table is not created if it already exists.
* @return an object to communicate with the created table if it is created.
* @throws Exception throws exception on creation failure.
*/
public YBTable createRedisTable(String name, boolean ifNotExist) throws Exception {
if (createRedisNamespace(ifNotExist)) {
// Namespace is just created, so there is no redis table.
return createRedisTableOnly(name, false);
}
return createRedisTableOnly(name, ifNotExist);
}
/**
* Create a redis table on the cluster with the specified name.
* The redis namespace 'system_redis' must already be existing.
*
* @param name the table name.
* @return an object to communicate with the created table if it is created.
* @throws Exception throws exception on creation failure.
*/
public YBTable createRedisTableOnly(String name) throws Exception {
return createRedisTableOnly(name, false);
}
/**
* Create a redis table on the cluster with the specified name.
* The redis namespace 'system_redis' must already be existing.
*
* @param name the table name.
* @param ifNotExist if true, table is not created if it already exists.
* @return an object to communicate with the created table if it is created.
* @throws Exception throws exception on creation failure.
*/
public YBTable createRedisTableOnly(String name, boolean ifNotExist) throws Exception {
if (ifNotExist) {
ListTablesResponse response = getTablesList(name);
if (response.getTablesList().stream().anyMatch(n -> n.equals(name))) {
return openTable(REDIS_KEYSPACE_NAME, name);
}
}
return createTable(REDIS_KEYSPACE_NAME, name, getRedisSchema(),
new CreateTableOptions().setTableType(TableType.REDIS_TABLE_TYPE));
}
/**
* Create a table on the cluster with the specified name and schema. Default table
* configurations are used, mainly the table will have one tablet.
* @param keyspace CQL keyspace to which this table belongs
* @param name Table's name
* @param schema Table's schema
* @return an object to communicate with the created table
*/
public YBTable createTable(String keyspace, String name, Schema schema) throws Exception {
return createTable(keyspace, name, schema, new CreateTableOptions());
}
/**
* Create a table on the cluster with the specified name, schema, and table configurations.
* @param keyspace CQL keyspace to which this table belongs
* @param name the table's name
* @param schema the table's schema
* @param builder a builder containing the table's configurations
* @return an object to communicate with the created table
*/
public YBTable createTable(String keyspace, String name, Schema schema,
CreateTableOptions builder)
throws Exception {
Deferred<YBTable> d = asyncClient.createTable(keyspace, name, schema, builder);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/*
* Create a CQL keyspace.
* @param non-null name of the keyspace.
*/
public CreateKeyspaceResponse createKeyspace(String keyspace)
throws Exception {
Deferred<CreateKeyspaceResponse> d = asyncClient.createKeyspace(keyspace);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/*
* Create a keyspace (namespace) for the specified database type.
* @param non-null name of the keyspace.
*/
public CreateKeyspaceResponse createKeyspace(String keyspace, YQLDatabase databaseType)
throws Exception {
Deferred<CreateKeyspaceResponse> d = asyncClient.createKeyspace(keyspace, databaseType);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Delete a keyspace(or namespace) on the cluster with the specified name.
* @param keyspaceName CQL keyspace to delete
* @return an rpc response object
*/
public DeleteNamespaceResponse deleteNamespace(String keyspaceName)
throws Exception {
Deferred<DeleteNamespaceResponse> d = asyncClient.deleteNamespace(keyspaceName);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Delete a table on the cluster with the specified name.
* @param keyspace CQL keyspace to which this table belongs
* @param name the table's name
* @return an rpc response object
*/
public DeleteTableResponse deleteTable(final String keyspace, final String name)
throws Exception {
Deferred<DeleteTableResponse> d = asyncClient.deleteTable(keyspace, name);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Alter a table on the cluster as specified by the builder.
*
* When the method returns it only indicates that the master accepted the alter
* command, use {@link YBClient#isAlterTableDone(String)} to know when the alter finishes.
* @param keyspace CQL keyspace to which this table belongs
* @param name the table's name, if this is a table rename then the old table name must be passed
* @param ato the alter table builder
* @return an rpc response object
*/
public AlterTableResponse alterTable(String keyspace, String name, AlterTableOptions ato)
throws Exception {
Deferred<AlterTableResponse> d = asyncClient.alterTable(keyspace, name, ato);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get information about master heartbeat delays as seen by the master leader.
*
* @return rpc response object containing the master heartbeat delays and rpc error if any
* @throws Exception when the rpc fails
*/
public GetMasterHeartbeatDelaysResponse getMasterHeartbeatDelays() throws Exception {
Deferred<GetMasterHeartbeatDelaysResponse> d = asyncClient.getMasterHeartbeatDelays();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Helper method that checks and waits until the completion of an alter command.
* It will block until the alter command is done or the timeout is reached.
* @param keyspace CQL keyspace to which this table belongs
* @param name Table's name, if the table was renamed then that name must be checked against
* @return a boolean indicating if the table is done being altered
*/
public boolean isAlterTableDone(String keyspace, String name) throws Exception {
long totalSleepTime = 0;
while (totalSleepTime < getDefaultAdminOperationTimeoutMs()) {
long start = System.currentTimeMillis();
Deferred<IsAlterTableDoneResponse> d = asyncClient.isAlterTableDone(keyspace, name);
IsAlterTableDoneResponse response;
try {
response = d.join(AsyncYBClient.sleepTime);
} catch (Exception ex) {
throw ex;
}
if (response.isDone()) {
return true;
}
// Count time that was slept and see if we need to wait a little more.
long elapsed = System.currentTimeMillis() - start;
// Don't oversleep the deadline.
if (totalSleepTime + AsyncYBClient.sleepTime > getDefaultAdminOperationTimeoutMs()) {
return false;
}
// elapsed can be bigger if we slept about 500ms
if (elapsed <= AsyncYBClient.sleepTime) {
LOG.debug("Alter not done, sleep " + (AsyncYBClient.sleepTime - elapsed) +
" and slept " + totalSleepTime);
Thread.sleep(AsyncYBClient.sleepTime - elapsed);
totalSleepTime += AsyncYBClient.sleepTime;
} else {
totalSleepTime += elapsed;
}
}
return false;
}
/**
* Get the list of running tablet servers.
* @return a list of tablet servers
*/
public ListTabletServersResponse listTabletServers() throws Exception {
Deferred<ListTabletServersResponse> d = asyncClient.listTabletServers();
return d.join(getDefaultAdminOperationTimeoutMs());
}
public ListLiveTabletServersResponse listLiveTabletServers() throws Exception {
Deferred<ListLiveTabletServersResponse> d = asyncClient.listLiveTabletServers();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of all the masters.
* @return a list of masters
*/
public ListMastersResponse listMasters() throws Exception {
Deferred<ListMastersResponse> d = asyncClient.listMasters();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the current cluster configuration.
* @return the configuration
*/
public GetMasterClusterConfigResponse getMasterClusterConfig() throws Exception {
Deferred<GetMasterClusterConfigResponse> d = asyncClient.getMasterClusterConfig();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Change the current cluster configuration.
* @param config the new config to set on the cluster.
* @return the configuration
*/
public ChangeMasterClusterConfigResponse changeMasterClusterConfig(
CatalogEntityInfo.SysClusterConfigEntryPB config) throws Exception {
Deferred<ChangeMasterClusterConfigResponse> d = asyncClient.changeMasterClusterConfig(config);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Change the load balancer state.
* @param isEnable if true, load balancer is enabled on master, else is disabled.
* @return the response of the operation.
*/
public ChangeLoadBalancerStateResponse changeLoadBalancerState(
boolean isEnable) throws Exception {
Deferred<ChangeLoadBalancerStateResponse> d = asyncClient.changeLoadBalancerState(isEnable);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the tablet load move completion percentage for blacklisted nodes, if any.
* @return the response with percent load completed.
*/
public GetLoadMovePercentResponse getLoadMoveCompletion()
throws Exception {
Deferred<GetLoadMovePercentResponse> d;
GetLoadMovePercentResponse resp;
int numTries = 0;
do {
d = asyncClient.getLoadMoveCompletion();
resp = d.join(getDefaultAdminOperationTimeoutMs());
} while (resp.hasRetriableError() && numTries++ < MAX_NUM_RETRIES);
return resp;
}
public AreNodesSafeToTakeDownResponse areNodesSafeToTakeDown(Set<String> masterIps,
Set<String> tserverIps,
long followerLagBoundMs)
throws Exception {
ListTabletServersResponse tabletServers = listTabletServers();
Collection<String> tserverUUIDs = tabletServers.getTabletServersList().stream()
.filter(ts -> tserverIps.contains(ts.getHost()))
.map(ts -> ts.getUuid())
.collect(Collectors.toSet());
ListMastersResponse masters = listMasters();
Collection<String> masterUUIDs = masters.getMasters().stream()
.filter(m -> masterIps.contains(m.getHost()))
.map(m -> m.getUuid())
.collect(Collectors.toSet());
Deferred<AreNodesSafeToTakeDownResponse> d = asyncClient.areNodesSafeToTakeDown(
masterUUIDs, tserverUUIDs, followerLagBoundMs
);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the tablet load move completion percentage for blacklisted nodes, if any.
* @return the response with percent load completed.
*/
public GetLoadMovePercentResponse getLeaderBlacklistCompletion()
throws Exception {
Deferred<GetLoadMovePercentResponse> d;
GetLoadMovePercentResponse resp;
int numTries = 0;
do {
d = asyncClient.getLeaderBlacklistCompletion();
resp = d.join(getDefaultAdminOperationTimeoutMs());
} while (resp.hasRetriableError() && numTries++ < MAX_NUM_RETRIES);
return resp;
}
/**
* Check if the tablet load is balanced as per the master leader.
* @param numServers expected number of servers across which the load needs to balanced.
* Zero implies load distribution can be checked across all servers
* which the master leader knows about.
* @return a deferred object that yields if the load is balanced.
*/
public IsLoadBalancedResponse getIsLoadBalanced(int numServers) throws Exception {
Deferred<IsLoadBalancedResponse> d = asyncClient.getIsLoadBalanced(numServers);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Check if the load balancer is idle as per the master leader.
* @return a deferred object that yields if the load is balanced.
*/
public IsLoadBalancerIdleResponse getIsLoadBalancerIdle() throws Exception {
Deferred<IsLoadBalancerIdleResponse> d = asyncClient.getIsLoadBalancerIdle();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Check if the tablet leader load is balanced as per the master leader.
* @return a deferred object that yields if the load is balanced.
*/
public AreLeadersOnPreferredOnlyResponse getAreLeadersOnPreferredOnly() throws Exception {
Deferred<AreLeadersOnPreferredOnlyResponse> d = asyncClient.getAreLeadersOnPreferredOnly();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Check if initdb executed by the master is done running.
*/
public IsInitDbDoneResponse getIsInitDbDone() throws Exception {
Deferred<IsInitDbDoneResponse> d = asyncClient.getIsInitDbDone();
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Wait for the master server to be running and initialized.
* @param hp the host and port for the master.
* @param timeoutMS timeout in milliseconds to wait for.
* @return returns true if the master is properly initialized, false otherwise.
*/
public boolean waitForMaster(HostAndPort hp, long timeoutMS) throws Exception {
if (!waitForServer(hp, timeoutMS)) {
return false;
}
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < timeoutMS &&
getMasterUUID(hp.getHost(), hp.getPort()) == null) {
Thread.sleep(AsyncYBClient.sleepTime);
}
return getMasterUUID(hp.getHost(), hp.getPort()) != null;
}
/**
* Find the uuid of a master using the given host/port.
* @param host Master host that is being queried.
* @param port RPC port of the host being queried.
* @return The uuid of the master, or null if not found.
*/
String getMasterUUID(String host, int port) {
HostAndPort hostAndPort = HostAndPort.fromParts(host, port);
return getMasterRegistrationResponse(hostAndPort).map(
resp -> resp.getInstanceId().getPermanentUuid().toStringUtf8()
).orElse(null);
}
/**
* Find the uuid of the leader master.
* @return The uuid of the leader master, or null if no leader found.
*/
public String getLeaderMasterUUID() {
for (HostAndPort hostAndPort : asyncClient.getMasterAddresses()) {
Optional<GetMasterRegistrationResponse> resp = getMasterRegistrationResponse(hostAndPort);
if (resp.isPresent() && resp.get().getRole() == CommonTypes.PeerRole.LEADER) {
return resp.get().getInstanceId().getPermanentUuid().toStringUtf8();
}
}
return null;
}
public List<GetMasterRegistrationResponse> getMasterRegistrationResponseList() {
List<GetMasterRegistrationResponse> result = new ArrayList<>();
for (HostAndPort hostAndPort : asyncClient.getMasterAddresses()) {
Optional<GetMasterRegistrationResponse> resp = getMasterRegistrationResponse(hostAndPort);
if (resp.isPresent()) {
result.add(resp.get());
}
}
return result;
}
private Optional<GetMasterRegistrationResponse> getMasterRegistrationResponse(
HostAndPort hostAndPort) {
Deferred<GetMasterRegistrationResponse> d;
TabletClient clientForHostAndPort = asyncClient.newMasterClient(hostAndPort);
if (clientForHostAndPort == null) {
String message = "Couldn't resolve this master's address " + hostAndPort.toString();
LOG.warn(message);
} else {
d = asyncClient.getMasterRegistration(clientForHostAndPort);
try {
return Optional.of(d.join(getDefaultAdminOperationTimeoutMs()));
} catch (Exception e) {
LOG.warn("Couldn't get registration info for master {} due to error '{}'.",
hostAndPort.toString(), e.getMessage());
}
}
return Optional.empty();
}
/**
* Find the host/port of the leader master.
* @return The host and port of the leader master, or null if no leader found.
*/
public HostAndPort getLeaderMasterHostAndPort() {
List<HostAndPort> masterAddresses = asyncClient.getMasterAddresses();
Map<HostAndPort, TabletClient> clients = new HashMap<>();
for (HostAndPort hostAndPort : masterAddresses) {
TabletClient clientForHostAndPort = asyncClient.newMasterClient(hostAndPort);
if (clientForHostAndPort == null) {
String message = "Couldn't resolve this master's host/port " + hostAndPort.toString();
LOG.warn(message);
}
clients.put(hostAndPort, clientForHostAndPort);
}
CountDownLatch finished = new CountDownLatch(1);
AtomicInteger workersLeft = new AtomicInteger(clients.entrySet().size());
AtomicReference<HostAndPort> result = new AtomicReference<>(null);
for (Entry<HostAndPort, TabletClient> entry : clients.entrySet()) {
asyncClient.getMasterRegistration(entry.getValue())
.addCallback(new Callback<Object, GetMasterRegistrationResponse>() {
@Override
public Object call(GetMasterRegistrationResponse response) throws Exception {
if (response.getRole() == CommonTypes.PeerRole.LEADER) {
boolean wasNullResult = result.compareAndSet(null, entry.getKey());
if (!wasNullResult) {
LOG.warn(
"More than one node reported they are master-leaders ({} and {})",
result.get().toString(), entry.getKey().toString());
}
finished.countDown();
} else if (workersLeft.decrementAndGet() == 0) {
finished.countDown();
}
return null;
}
}).addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(final Exception e) {
// If finished == 0 then we are here because of closeClient() and the master is
// already found.
if (finished.getCount() != 0) {
LOG.warn("Couldn't get registration info for master " + entry.getKey().toString());
if (workersLeft.decrementAndGet() == 0) {
finished.countDown();
}
}
return null;
}
});
}
try {
finished.await(getDefaultAdminOperationTimeoutMs(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
return result.get();
}
/**
* Helper API to wait and get current leader's UUID. This takes care of waiting for any election
* in progress.
*
* @param timeoutMs Amount of time to try getting the leader uuid.
* @return Master leader uuid on success, null otherwise.
*/
private String waitAndGetLeaderMasterUUID(long timeoutMs) throws Exception {
LOG.info("Waiting for master leader (timeout: " + timeoutMs + " ms)");
long start = System.currentTimeMillis();
// Retry till we get a valid UUID (or timeout) for the new leader.
do {
String leaderUuid = getLeaderMasterUUID();
long elapsedTimeMs = System.currentTimeMillis() - start;
// Done if we got a valid one.
if (leaderUuid != null) {
LOG.info("Fininshed waiting for master leader in " + elapsedTimeMs + " ms. Leader UUID: " +
leaderUuid);
return leaderUuid;
}
Thread.sleep(asyncClient.sleepTime);
} while (System.currentTimeMillis() - start < timeoutMs);
LOG.error("Timed out getting leader uuid.");
return null;
}
/**
* Step down the current master leader and wait for a new leader to be elected.
*
* @param leaderUuid Current master leader's uuid.
* @exception if the new leader is the same as the old leader after certain number of tries.
*/
private void stepDownMasterLeaderAndWaitForNewLeader(String leaderUuid) throws Exception {
String tabletId = getMasterTabletId();
String newLeader = leaderUuid;
int numIters = 0;
int maxNumIters = 25;
String errorMsg = null;
try {
// TODO: This while loop will not be needed once JIRA ENG-49 is fixed.
do {
Deferred<LeaderStepDownResponse> d = asyncClient.masterLeaderStepDown(leaderUuid,
tabletId);
LeaderStepDownResponse resp = d.join(getDefaultAdminOperationTimeoutMs());
if (resp.hasError()) {
errorMsg = "Master leader step down hit error " + resp.errorMessage();
break;
}
newLeader = waitAndGetLeaderMasterUUID(getDefaultAdminOperationTimeoutMs());
if (newLeader == null) {
errorMsg = "Timed out as we could not find a valid new leader. Old leader is " +
leaderUuid;
break;
}
LOG.info("Tried step down of {}, new leader {}, iter {}.",
leaderUuid, newLeader, numIters);
// Done if we found a new leader.
if (!newLeader.equals(leaderUuid)) {
break;
}
numIters++;
if (numIters >= maxNumIters) {
errorMsg = "Maximum iterations reached trying to step down the " +
"leader master with uuid " + leaderUuid;
break;
}
Thread.sleep(asyncClient.sleepTime);
} while (true);
} catch (Exception e) {
// TODO: Ideally we need an error code here, but this is come another layer which
// eats up the NOT_THE_LEADER code.
if (e.getMessage().contains("Wrong destination UUID requested")) {
LOG.info("Got wrong destination for {} stepdown with error '{}'.",
leaderUuid, e.getMessage());
newLeader = waitAndGetLeaderMasterUUID(getDefaultAdminOperationTimeoutMs());
LOG.info("After wait for leader uuid. Old leader was {}, new leader is {}.",
leaderUuid, newLeader);
} else {
LOG.error("Error trying to step down {}. Error: .", leaderUuid, e);
throw new RuntimeException("Could not step down leader master " + leaderUuid, e);
}
}
if (errorMsg != null) {
LOG.error(errorMsg);
throw new RuntimeException(errorMsg);
}
LOG.info("Step down of {} done, new master uuid={}.", leaderUuid, newLeader);
}
/**
* Change master configuration.
*
* @param host Master host that is being added or removed.
* @param port RPC port of the host being added or removed.
* @param isAdd true if we are adding a server to the master configuration, false if removing.
* @param useHost if caller wants to use host/port instead of uuid of server being removed.
* @param hostAddrToAdd if caller wants to use a different address for the master
* for the config update
*
* @return The change config response object.
*/
public ChangeConfigResponse changeMasterConfig(
String host, int port, boolean isAdd) throws Exception {
return changeMasterConfig(host, port, isAdd, false /* useHost */);
}
public ChangeConfigResponse changeMasterConfig(
String host, int port, boolean isAdd, boolean useHost) throws Exception {
return changeMasterConfig(host, port, isAdd, useHost, null /* hostAddrToAdd */);
}
public ChangeConfigResponse changeMasterConfig(String host, int port,
boolean isAdd, boolean useHost,
String hostAddrToAdd) throws Exception {
String masterUuid = null;
int tries = 0;
if (isAdd || !useHost) {
// In case the master UUID is returned as null, retry a few times
do {
masterUuid = getMasterUUID(host, port);
Thread.sleep(AsyncYBClient.sleepTime);
tries++;
} while (tries < MAX_NUM_RETRIES && masterUuid == null);
if (masterUuid == null) {
throw new IllegalArgumentException("Invalid master host/port of " + host + "/" +
port + " - could not get it's uuid.");
}
}
LOG.info("Sending changeConfig : Target host:port={}:{} at uuid={}, add={}, useHost={}.",
host, port, masterUuid, isAdd, useHost);
long timeout = getDefaultAdminOperationTimeoutMs();
ChangeConfigResponse resp = null;
boolean changeConfigDone;
// It is possible that we might need different addresses for reaching from the client
// than the one the DB nodes use to communicate. If the client provides an address
// to add to the config explicitly, use that.
String hostAddr = hostAddrToAdd == null ? host : hostAddrToAdd;
do {
changeConfigDone = true;
try {
Deferred<ChangeConfigResponse> d =
asyncClient.changeMasterConfig(hostAddr, port, masterUuid, isAdd, useHost);
resp = d.join(timeout);
if (!resp.hasError()) {
asyncClient.updateMasterAdresses(host, port, isAdd);
}
} catch (TabletServerErrorException tsee) {
String leaderUuid = waitAndGetLeaderMasterUUID(timeout);
LOG.info("Hit tserver error {}, leader is {}.",
tsee.getTServerError().toString(), leaderUuid);
if (tsee.getTServerError().getCode() ==
TserverTypes.TabletServerErrorPB.Code.LEADER_NEEDS_STEP_DOWN) {
stepDownMasterLeaderAndWaitForNewLeader(leaderUuid);
changeConfigDone = false;
LOG.info("Retrying changeConfig because it received LEADER_NEEDS_STEP_DOWN error code.");
} else {
throw tsee;
}
}
} while (!changeConfigDone);
return resp;
}
/**
* Get the basic redis schema.
* @return redis schema
*/
public static Schema getRedisSchema() {
ArrayList<ColumnSchema> columns = new ArrayList<ColumnSchema>(1);
columns.add(new ColumnSchema.ColumnSchemaBuilder(REDIS_KEY_COLUMN_NAME, Type.BINARY)
.hashKey(true)
.nullable(false)
.build());
return new Schema(columns);
}
/**
* Get the master's tablet id.
* @return master tablet id.
*/
public static String getMasterTabletId() {
return AsyncYBClient.getMasterTabletId();
}
/**
* Wait for the cluster to have successfully elected a Master Leader.
* @param timeoutMs the amount of time, in MS, to wait until a Leader is present
*/
public void waitForMasterLeader(long timeoutMs) throws Exception {
String leaderUuid = waitAndGetLeaderMasterUUID(timeoutMs);
if (leaderUuid == null) {
throw new RuntimeException(
"Timed out waiting for Master Leader after " + timeoutMs + " ms");
}
}
/**
* Enable encryption at rest using the key file specified
*/
public boolean enableEncryptionAtRestInMemory(final String versionId) throws Exception {
Deferred<ChangeEncryptionInfoInMemoryResponse> d;
d = asyncClient.enableEncryptionAtRestInMemory(versionId);
d.join(getDefaultAdminOperationTimeoutMs());
return d.join(getDefaultAdminOperationTimeoutMs()).hasError();
}
/**
* Disable encryption at rest
*/
public boolean disableEncryptionAtRestInMemory() throws Exception {
Deferred<ChangeEncryptionInfoInMemoryResponse> d;
d = asyncClient.disableEncryptionAtRestInMemory();
return !d.join(getDefaultAdminOperationTimeoutMs()).hasError();
}
/**
* Enable encryption at rest using the key file specified
*/
public boolean enableEncryptionAtRest(final String file) throws Exception {
Deferred<ChangeEncryptionInfoResponse> d;
d = asyncClient.enableEncryptionAtRest(file);
return !d.join(getDefaultAdminOperationTimeoutMs()).hasError();
}
/**
* Disable encryption at rest
*/
public boolean disableEncryptionAtRest() throws Exception {
Deferred<ChangeEncryptionInfoResponse> d;
d = asyncClient.disableEncryptionAtRest();
return !d.join(getDefaultAdminOperationTimeoutMs()).hasError();
}
public Pair<Boolean, String> isEncryptionEnabled() throws Exception {
Deferred<IsEncryptionEnabledResponse> d = asyncClient.isEncryptionEnabled();
IsEncryptionEnabledResponse resp = d.join(getDefaultAdminOperationTimeoutMs());
if (resp.getServerError() != null) {
throw new RuntimeException("Could not check isEnabledEncryption with error: " +
resp.getServerError().getStatus().getMessage());
}
return new Pair(resp.getIsEnabled(), resp.getUniverseKeyId());
}
/**
* Add universe keys in memory to a master at hp, with universe keys in format <id -> key>
*/
public void addUniverseKeys(Map<String, byte[]> universeKeys, HostAndPort hp) throws Exception {
Deferred<AddUniverseKeysResponse> d = asyncClient.addUniverseKeys(universeKeys, hp);
AddUniverseKeysResponse resp = d.join();
if (resp.getServerError() != null) {
throw new RuntimeException("Could not add universe keys to " + hp.toString() +
" with error: " + resp.getServerError().getStatus().getMessage());
}
}
/**
* Check if a master at hp has universe key universeKeyId. Returns true if it does.
*/
public boolean hasUniverseKeyInMemory(String universeKeyId, HostAndPort hp) throws Exception {
Deferred<HasUniverseKeyInMemoryResponse> d =
asyncClient.hasUniverseKeyInMemory(universeKeyId, hp);
HasUniverseKeyInMemoryResponse resp = d.join();
if (resp.getServerError() != null) {
throw new RuntimeException("Could not add universe keys to " + hp.toString() +
" with error: " + resp.getServerError().getStatus().getMessage());
}
return resp.hasKey();
}
/**
* Ping a certain server to see if it is responding to RPC requests.
* @param host the hostname or IP of the server
* @param port the port number of the server
* @return true if the server responded to ping
*/
public boolean ping(final String host, int port) throws Exception {
Deferred<PingResponse> d = asyncClient.ping(HostAndPort.fromParts(host, port));
d.join(getDefaultAdminOperationTimeoutMs());
return true;
}
/**
* Set a gflag of a given server.
* @param hp the host and port of the server
* @param flag the flag to be set.
* @param value the value to set the flag to
* @return true if the server successfully set the flag
*/
public boolean setFlag(HostAndPort hp, String flag, String value) throws Exception {
return setFlag(hp, flag, value, false);
}
/**
* Set a gflag of a given server.
* @param hp the host and port of the server
* @param flag the flag to be set.
* @param value the value to set the flag to
* @param force if the flag needs to be set even if it is not marked runtime safe
* @return true if the server successfully set the flag
*/
public boolean setFlag(HostAndPort hp, String flag, String value,
boolean force) throws Exception {
if (flag == null || flag.isEmpty() || value == null || value.isEmpty() || hp == null) {
LOG.warn("Invalid arguments for hp: {}, flag {}, or value: {}", hp.toString(), flag, value);
return false;
}
Deferred<SetFlagResponse> d = asyncClient.setFlag(hp, flag, value, force);
return !d.join(getDefaultAdminOperationTimeoutMs()).hasError();
}
/**
* Get a gflag's value from a given server.
* @param hp the host and port of the server
* @param flag the flag to get.
* @return string value of flag if valid, else empty string
*/
public String getFlag(HostAndPort hp, String flag) throws Exception {
if (flag == null || hp == null) {
LOG.warn("Invalid arguments for hp: {}, flag {}", hp.toString(), flag);
return "";
}
Deferred<GetFlagResponse> d = asyncClient.getFlag(hp, flag);
GetFlagResponse result = d.join(getDefaultAdminOperationTimeoutMs());
if (result.getValid()) {
LOG.warn("Invalid flag {}", flag);
return result.getValue();
}
return "";
}
/**
* Get the list of master addresses from a given tserver.
* @param hp the host and port of the server
* @return a comma separated string containing the list of master addresses
*/
public String getMasterAddresses(HostAndPort hp) throws Exception {
Deferred<GetMasterAddressesResponse> d = asyncClient.getMasterAddresses(hp);
return d.join(getDefaultAdminOperationTimeoutMs()).getMasterAddresses();
}
/**
* @see AsyncYBClient#upgradeYsql(HostAndPort, boolean)
*/
public UpgradeYsqlResponse upgradeYsql(HostAndPort hp, boolean useSingleConnection)
throws Exception {
Deferred<UpgradeYsqlResponse> d = asyncClient.upgradeYsql(hp, useSingleConnection);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Check if the server is ready to serve requests.
* @param hp the host and port of the server.
* @param isTserver true if host/port is for tserver, else its master.
* @return server readiness response.
*/
public IsServerReadyResponse isServerReady(HostAndPort hp, boolean isTserver)
throws Exception {
Deferred<IsServerReadyResponse> d = asyncClient.isServerReady(hp, isTserver);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Gets the list of tablets for a TServer.
* @param hp host and port of the TServer.
* @return response containing the list of tablet ids that exist on a TServer.
*/
public ListTabletsForTabletServerResponse listTabletsForTabletServer(HostAndPort hp)
throws Exception {
Deferred<ListTabletsForTabletServerResponse> d = asyncClient.listTabletsForTabletServer(hp);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
*
* @param servers string array of node addresses (master and/or tservers) in the
* format host:port
* @return 'true' when all certificates are reloaded
* @throws RuntimeException when the operation fails
* @throws IllegalStateException when the input 'servers' array is empty or null
*/
public boolean reloadCertificates(HostAndPort server)
throws RuntimeException, IllegalStateException {
if (server == null || server.getHost() == null || "".equals(server.getHost().trim()))
throw new IllegalStateException("No servers to act upon");
LOG.debug("attempting to reload certificates for {}", (Object) server);
Deferred<ReloadCertificateResponse> deferred = asyncClient.reloadCertificates(server);
try {
ReloadCertificateResponse response = deferred.join(getDefaultAdminOperationTimeoutMs());
LOG.debug("received certificate reload response from {}", response.getNodeAddress());
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public interface Condition {
boolean get() throws Exception;
}
private class ReplicaCountCondition implements Condition {
private int numReplicas;
private YBTable table;
public ReplicaCountCondition(YBTable table, int numReplicas) {
this.numReplicas = numReplicas;
this.table = table;
}
@Override
public boolean get() throws Exception {
for (LocatedTablet tablet : table.getTabletsLocations(getDefaultAdminOperationTimeoutMs())) {
if (tablet.getReplicas().size() != numReplicas) {
return false;
}
}
return true;
}
}
private class TableDoesNotExistCondition implements Condition {
private String nameFilter;
public TableDoesNotExistCondition(String nameFilter) {
this.nameFilter = nameFilter;
}
@Override
public boolean get() throws Exception {
ListTablesResponse tl = getTablesList(nameFilter);
return tl.getTablesList().isEmpty();
}
}
/**
* Checks the ping of the given ip and port.
*/
private class ServerCondition implements Condition {
private HostAndPort hp;
public ServerCondition(HostAndPort hp) {
this.hp = hp;
}
@Override
public boolean get() throws Exception {
return ping(hp.getHost(), hp.getPort());
}
}
/**
* Checks whether the IsLoadBalancedResponse has no error.
*/
private class LoadBalanceCondition implements Condition {
private int numServers;
public LoadBalanceCondition(int numServers) {
this.numServers = numServers;
}
@Override
public boolean get() throws Exception {
IsLoadBalancedResponse resp = getIsLoadBalanced(numServers);
return !resp.hasError();
}
}
/**
* Checks whether the IsLoadBalancerIdleResponse has no error.
*/
private class LoadBalancerIdleCondition implements Condition {
public LoadBalancerIdleCondition() {
}
@Override
public boolean get() throws Exception {
IsLoadBalancerIdleResponse resp = getIsLoadBalancerIdle();
return !resp.hasError();
}
}
/**
* Checks whether the LoadBalancer is currently running.
*/
private class LoadBalancerActiveCondition implements Condition {
public LoadBalancerActiveCondition() {
}
@Override
public boolean get() throws Exception {
try {
IsLoadBalancerIdleResponse resp = getIsLoadBalancerIdle();
} catch (MasterErrorException e) {
// TODO (deepthi.srinivasan) Instead of writing if-else
// with Exceptions, find a way to receive the error code
// neatly.
return e.toString().contains("LOAD_BALANCER_RECENTLY_ACTIVE");
}
return false;
}
}
private class AreLeadersOnPreferredOnlyCondition implements Condition {
@Override
public boolean get() throws Exception {
AreLeadersOnPreferredOnlyResponse resp = getAreLeadersOnPreferredOnly();
return !resp.hasError();
}
}
private class ReplicaMapCondition implements Condition {
private YBTable table;
Map<String, List<List<Integer>>> replicaMapExpected;
private long deadline;
public ReplicaMapCondition(YBTable table,
Map<String, List<List<Integer>>> replicaMapExpected,
long deadline) {
this.table = table;
this.replicaMapExpected = replicaMapExpected;
this.deadline = deadline;
}
@Override
public boolean get() throws Exception {
Map<String, List<List<Integer>>> replicaMap =
table.getMemberTypeCountsForEachTSType(deadline);
return replicaMap.equals(replicaMapExpected);
}
}
private class MasterHasUniverseKeyInMemoryCondition implements Condition {
private String universeKeyId;
private HostAndPort hp;
public MasterHasUniverseKeyInMemoryCondition(String universeKeyId, HostAndPort hp) {
this.universeKeyId = universeKeyId;
this.hp = hp;
}
@Override
public boolean get() throws Exception {
return hasUniverseKeyInMemory(universeKeyId, hp);
}
}
/**
* Quick and dirty error injection on Wait based API's.
* After every use, for now, will get automatically disabled.
*/
public void injectWaitError() {
injectWaitError = true;
}
/**
* Helper method that loops on a condition every 500ms until it returns true or the
* operation times out.
* @param condition the Condition which implements a boolean get() method.
* @param timeoutMs the amount of time, in MS, to wait.
* @return true if the condition is true within the time frame, false otherwise.
*/
private boolean waitForCondition(Condition condition, final long timeoutMs) {
int numErrors = 0;
int numIters = 0;
Exception exception = null;
long start = System.currentTimeMillis();
do {
exception = null;
try {
if (injectWaitError) {
Thread.sleep(AsyncYBClient.sleepTime);
injectWaitError = false;
String msg = "Simulated expection due to injected error.";
LOG.info(msg);
throw new RuntimeException(msg);
}
if (condition.get()) {
return true;
}
} catch (Exception e) {
numErrors++;
if (numErrors % LOG_ERRORS_EVERY_NUM_ITERS == 0) {
LOG.warn("Hit {} errors so far. Latest is : {}.", numErrors, e.getMessage());
}
exception = e;
}
numIters++;
if (numIters % LOG_EVERY_NUM_ITERS == 0) {
LOG.info("Tried operation {} times so far.", numIters);
}
// Sleep before next retry.
try {
Thread.sleep(AsyncYBClient.sleepTime);
} catch (Exception e) {}
} while(System.currentTimeMillis() - start < timeoutMs);
if (exception == null) {
LOG.error("Timed out waiting for condition");
} else {
LOG.error("Hit too many errors, final exception is {}.", exception.getMessage());
}
LOG.error("Returning failure after {} iterations, num errors = {}.", numIters, numErrors);
return false;
}
/**
* Wait for the table to have a specific number of replicas.
* @param table the table to check the condition on
* @param numReplicas the number of replicas we expect the table to have
* @param timeoutMs the amount of time, in MS, to wait
* @return true if the table the expected number of replicas, false otherwise
*/
public boolean waitForReplicaCount(final YBTable table, final int numReplicas,
final long timeoutMs) {
Condition replicaCountCondition = new ReplicaCountCondition(table, numReplicas);
return waitForCondition(replicaCountCondition, timeoutMs);
}
/**
* Wait for the specific server to come online.
* @param hp the HostAndPort of the server
* @param timeoutMs the amount of time, in MS, to wait
* @return true if the server responded to pings in the given time, false otherwise
*/
public boolean waitForServer(final HostAndPort hp, final long timeoutMs) {
Condition serverCondition = new ServerCondition(hp);
return waitForCondition(serverCondition, timeoutMs);
}
/**
* Wait for the tablet load to be balanced by master leader.
* @param timeoutMs the amount of time, in MS, to wait
* @param numServers expected number of servers which need to balanced.
* @return true if the master leader does not return any error balance check.
*/
public boolean waitForLoadBalance(final long timeoutMs, int numServers) {
Condition loadBalanceCondition = new LoadBalanceCondition(numServers);
return waitForCondition(loadBalanceCondition, timeoutMs);
}
/**
* Wait for the Load Balancer to become active.
* @param timeoutMs the amount of time, in MS, to wait
* @return true if the load balancer is currently running.
*/
public boolean waitForLoadBalancerActive(final long timeoutMs) {
Condition loadBalancerActiveCondition = new LoadBalancerActiveCondition();
return waitForCondition(loadBalancerActiveCondition, timeoutMs);
}
/**
* Wait for the tablet load to be balanced by master leader.
* @param timeoutMs the amount of time, in MS, to wait
* @return true if the master leader does not return any error balance check.
*/
public boolean waitForLoadBalancerIdle(final long timeoutMs) {
Condition loadBalancerIdleCondition = new LoadBalancerIdleCondition();
return waitForCondition(loadBalancerIdleCondition, timeoutMs);
}
/**
* Wait for the leader load to be balanced by master leader.
* @param timeoutMs the amount of time, in MS, to wait.
* @return true iff the leader count is balanced within timeoutMs.
*/
public boolean waitForAreLeadersOnPreferredOnlyCondition(final long timeoutMs) {
Condition areLeadersOnPreferredOnlyCondition =
new AreLeadersOnPreferredOnlyCondition();
return waitForCondition(areLeadersOnPreferredOnlyCondition, timeoutMs);
}
/**
* Check if the replica count per ts matches the expected, returns true if it does within
* timeoutMs, false otherwise.
* TODO(Rahul): follow similar style for this type of function will do with affinitized
* leaders tests.
* @param timeoutMs number of milliseconds before timing out.
* @param table the table to wait for load balancing.
* @param replicaMapExpected the expected map between cluster uuid and live, read replica count.
* @return true if the read only replica count for the table matches the expected within the
* expected time frame, false otherwise.
*/
public boolean waitForExpectedReplicaMap(final long timeoutMs, YBTable table,
Map<String, List<List<Integer>>> replicaMapExpected) {
Condition replicaMapCondition = new ReplicaMapCondition(table, replicaMapExpected, timeoutMs);
return waitForCondition(replicaMapCondition, timeoutMs);
}
public boolean waitForMasterHasUniverseKeyInMemory(
final long timeoutMs, String universeKeyId, HostAndPort hp) {
Condition universeKeyCondition = new MasterHasUniverseKeyInMemoryCondition(universeKeyId, hp);
return waitForCondition(universeKeyCondition, timeoutMs);
}
/**
* Change master server configuration.
* @return status of the step down via a response.
*/
public LeaderStepDownResponse masterLeaderStepDown() throws Exception {
String leader_uuid = getLeaderMasterUUID();
String tablet_id = getMasterTabletId();
Deferred<LeaderStepDownResponse> d = asyncClient.masterLeaderStepDown(leader_uuid, tablet_id);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of all YSQL, YCQL, and YEDIS non-system tables.
* @return a list of all the non-system tables
*/
public ListTablesResponse getTablesList() throws Exception {
// YEDIS tables are stored as system tables, so they have to be separated.
ListTablesResponse nonSystemTables = getTablesList(null, true, null);
ListTablesResponse yedisTables;
// If YEDIS is not enabled, getTablesList will error out on this call.
try {
yedisTables = getTablesList(null, false, REDIS_KEYSPACE_NAME);
} catch (MasterErrorException e) {
yedisTables = null;
}
return nonSystemTables.mergeWith(yedisTables);
}
/**
* Get a list of table names. Passing a null filter returns all the tables. When a filter is
* specified, it only returns tables that satisfy a substring match.
* @param nameFilter an optional table name filter
* @return a deferred that contains the list of table names
*/
public ListTablesResponse getTablesList(String nameFilter) throws Exception {
return getTablesList(nameFilter, false, null);
}
/**
* Get a list of table names. Passing a null filter returns all the tables. When a filter is
* specified, it only returns tables that satisfy a substring match. Passing excludeSysfilters
* will return only non-system tables (index and user tables).
* @param nameFilter an optional table name filter
* @param excludeSystemTables an optional filter to search only non-system tables
* @param namespace an optional filter to search tables in specific namespace
* @return a deferred that contains the list of table names
*/
public ListTablesResponse getTablesList(
String nameFilter, boolean excludeSystemTables, String namespace)
throws Exception {
Deferred<ListTablesResponse> d = asyncClient.getTablesList(
nameFilter, excludeSystemTables, namespace);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of all YSQL, YCQL, and YEDIS namespaces.
* @return a list of all the namespaces
*/
public ListNamespacesResponse getNamespacesList() throws Exception {
// Fetch the namespaces of YSQL
ListNamespacesResponse namespacesList = null;
try {
Deferred<ListNamespacesResponse> d =
asyncClient.getNamespacesList(YQLDatabase.YQL_DATABASE_PGSQL);
namespacesList = d.join(getDefaultAdminOperationTimeoutMs());
} catch (MasterErrorException e) {
}
// Fetch the namespaces of YCQL
try {
Deferred<ListNamespacesResponse> d =
asyncClient.getNamespacesList(YQLDatabase.YQL_DATABASE_CQL);
ListNamespacesResponse response = d.join(getDefaultAdminOperationTimeoutMs());
namespacesList = namespacesList == null ? response : namespacesList.mergeWith(response);
} catch (MasterErrorException e) {
}
// Fetch the namespaces of YEDIS
try {
Deferred<ListNamespacesResponse> d =
asyncClient.getNamespacesList(YQLDatabase.YQL_DATABASE_REDIS);
ListNamespacesResponse response = d.join(getDefaultAdminOperationTimeoutMs());
namespacesList = namespacesList == null ? response : namespacesList.mergeWith(response);
} catch (MasterErrorException e) {
}
return namespacesList;
}
/**
* Create for a given tablet and stream.
* @param hp host port of the server.
* @param tableId the table id to subscribe to.
* @return a deferred object for the response from server.
*/
public CreateCDCStreamResponse createCDCStream(
final HostAndPort hp, String tableId,
String nameSpaceName, String format,
String checkpointType) throws Exception{
Deferred<CreateCDCStreamResponse> d = asyncClient.createCDCStream(hp,
tableId,
nameSpaceName,
format,
checkpointType);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public CreateCDCStreamResponse createCDCStream(YBTable table,
String nameSpaceName,
String format,
String checkpointType) throws Exception {
return createCDCStream(table, nameSpaceName, format, checkpointType, "");
}
public CreateCDCStreamResponse createCDCStream(YBTable table,
String nameSpaceName,
String format,
String checkpointType,
String recordType) throws Exception {
Deferred<CreateCDCStreamResponse> d = asyncClient.createCDCStream(table,
nameSpaceName, format, checkpointType, recordType, null);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public CreateCDCStreamResponse createCDCStream(YBTable table,
String nameSpaceName,
String format,
String checkpointType,
String recordType,
boolean dbtype,
boolean consistentSnapshot,
boolean useSnapshot) throws Exception {
Deferred<CreateCDCStreamResponse> d;
if (dbtype) {
d = asyncClient.createCDCStream(table,
nameSpaceName, format, checkpointType, recordType,
CommonTypes.YQLDatabase.YQL_DATABASE_CQL,
consistentSnapshot
? (useSnapshot ? CommonTypes.CDCSDKSnapshotOption.USE_SNAPSHOT
: CommonTypes.CDCSDKSnapshotOption.NOEXPORT_SNAPSHOT)
: null);
} else {
d = asyncClient.createCDCStream(table,
nameSpaceName, format, checkpointType, recordType,
consistentSnapshot
? (useSnapshot ? CommonTypes.CDCSDKSnapshotOption.USE_SNAPSHOT
: CommonTypes.CDCSDKSnapshotOption.NOEXPORT_SNAPSHOT)
: null);
}
return d.join(getDefaultAdminOperationTimeoutMs());
}
public boolean waitForTableRemoval(final long timeoutMs, String name) {
Condition TableDoesNotExistCondition = new TableDoesNotExistCondition(name);
return waitForCondition(TableDoesNotExistCondition, timeoutMs);
}
/**
* Test if a table exists.
* @param keyspace the keyspace name to which this table belongs.
* @param name a non-null table name
* @return true if the table exists, else false
*/
public boolean tableExists(String keyspace, String name) throws Exception {
Deferred<Boolean> d = asyncClient.tableExists(keyspace, name);
try {
return d.join(getDefaultAdminOperationTimeoutMs());
} catch (MasterErrorException e) {
return false;
}
}
/**
* Test if a table exists based on its UUID.
* @param tableUUID a non-null table UUID
* @return true if the table exists, else false
*/
public boolean tableExistsByUUID(String tableUUID) throws Exception {
Deferred<Boolean> d = asyncClient.tableExistsByUUID(tableUUID);
try {
return d.join(getDefaultAdminOperationTimeoutMs());
} catch (MasterErrorException e) {
return false;
}
}
/**
* Get the schema for a table based on the table's name.
* @param keyspace the keyspace name to which this table belongs.
* @param name a non-null table name
* @return a deferred that contains the schema for the specified table
*/
public GetTableSchemaResponse getTableSchema(final String keyspace, final String name)
throws Exception {
Deferred<GetTableSchemaResponse> d = asyncClient.getTableSchema(keyspace, name);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the schema for a table based on the table's UUID.
* @param tableUUID a non-null table uuid
* @return a deferred that contains the schema for the specified table
*/
public GetTableSchemaResponse getTableSchemaByUUID(final String tableUUID)
throws Exception {
Deferred<GetTableSchemaResponse> d = asyncClient.getTableSchemaByUUID(tableUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Open the table with the given name. If the table was just created, this method will block until
* all its tablets have also been created.
* @param keyspace the keyspace name to which the table belongs.
* @param name table to open
* @return a YBTable if the table exists, else a MasterErrorException
*/
public YBTable openTable(final String keyspace, final String name) throws Exception {
Deferred<YBTable> d = asyncClient.openTable(keyspace, name);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of tablet UUIDs of a table with the given name.
* @param table table info.
* @return the set of tablet UUIDs of the table.
*/
public Set<String> getTabletUUIDs(final YBTable table) throws Exception {
Set<String> ids = new HashSet<>();
for (LocatedTablet tablet : table.getTabletsLocations(getDefaultAdminOperationTimeoutMs())) {
ids.add(new String(tablet.getTabletId()));
}
return ids;
}
/**
* Get the list of tablet UUIDs of a table with the given name.
* @param keyspace the keyspace name to which the table belongs.
* @param name the table name
* @return the set of tablet UUIDs of the table.
*/
public Set<String> getTabletUUIDs(final String keyspace, final String name) throws Exception {
return getTabletUUIDs(openTable(keyspace, name));
}
/**
* Open the table with the given UUID. If the table was just created, this method will block until
* all its tablets have also been created.
* @param tableUUID table to open
* @return a YBTable if the table exists, else a MasterErrorException
*/
public YBTable openTableByUUID(final String tableUUID) throws Exception {
Deferred<YBTable> d = asyncClient.openTableByUUID(tableUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* It is the same as {@link AsyncYBClient#setupUniverseReplication(String, Map, Set, Boolean)}
* except that it is synchronous.
*
* @see AsyncYBClient#setupUniverseReplication(String, Map, Set, Boolean)
*/
public SetupUniverseReplicationResponse setupUniverseReplication(
String replicationGroupName,
Map<String, String> sourceTableIdsBootstrapIdMap,
Set<CommonNet.HostPortPB> sourceMasterAddresses,
@Nullable Boolean isTransactional) throws Exception {
Deferred<SetupUniverseReplicationResponse> d =
asyncClient.setupUniverseReplication(
replicationGroupName,
sourceTableIdsBootstrapIdMap,
sourceMasterAddresses,
isTransactional);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public SetupUniverseReplicationResponse setupUniverseReplication(
String replicationGroupName,
Map<String, String> sourceTableIdsBootstrapIdMap,
Set<CommonNet.HostPortPB> sourceMasterAddresses) throws Exception {
return setupUniverseReplication(
replicationGroupName,
sourceTableIdsBootstrapIdMap,
sourceMasterAddresses,
null /* isTransactional */);
}
public IsSetupUniverseReplicationDoneResponse isSetupUniverseReplicationDone(
String replicationGroupName) throws Exception {
Deferred<IsSetupUniverseReplicationDoneResponse> d =
asyncClient.isSetupUniverseReplicationDone(replicationGroupName);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public SetUniverseReplicationEnabledResponse setUniverseReplicationEnabled(
String replicationGroupName, boolean active) throws Exception {
Deferred<SetUniverseReplicationEnabledResponse> d =
asyncClient.setUniverseReplicationEnabled(replicationGroupName, active);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public AlterUniverseReplicationResponse alterUniverseReplicationAddTables(
String replicationGroupName,
Map<String, String> sourceTableIdsToAddBootstrapIdMap) throws Exception {
Deferred<AlterUniverseReplicationResponse> d =
asyncClient.alterUniverseReplicationAddTables(
replicationGroupName, sourceTableIdsToAddBootstrapIdMap);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public AlterUniverseReplicationResponse alterUniverseReplicationRemoveTables(
String replicationGroupName,
Set<String> sourceTableIdsToRemove) throws Exception {
Deferred<AlterUniverseReplicationResponse> d =
asyncClient.alterUniverseReplicationRemoveTables(
replicationGroupName, sourceTableIdsToRemove);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public AlterUniverseReplicationResponse alterUniverseReplicationRemoveTables(
String replicationGroupName,
Set<String> sourceTableIdsToRemove,
boolean removeTableIgnoreErrors) throws Exception {
Deferred<AlterUniverseReplicationResponse> d =
asyncClient.alterUniverseReplicationRemoveTables(
replicationGroupName, sourceTableIdsToRemove, removeTableIgnoreErrors);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public AlterUniverseReplicationResponse alterUniverseReplicationSourceMasterAddresses(
String replicationGroupName,
Set<CommonNet.HostPortPB> sourceMasterAddresses) throws Exception {
Deferred<AlterUniverseReplicationResponse> d =
asyncClient.alterUniverseReplicationSourceMasterAddresses(
replicationGroupName, sourceMasterAddresses);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public AlterUniverseReplicationResponse alterUniverseReplicationName(
String replicationGroupName,
String newReplicationGroupName) throws Exception {
Deferred<AlterUniverseReplicationResponse> d =
asyncClient.alterUniverseReplicationName(
replicationGroupName, newReplicationGroupName);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public IsSetupUniverseReplicationDoneResponse isAlterUniverseReplicationDone(
String replicationGroupName) throws Exception {
Deferred<IsSetupUniverseReplicationDoneResponse> d =
asyncClient.isSetupUniverseReplicationDone(replicationGroupName + ".ALTER");
return d.join(getDefaultAdminOperationTimeoutMs());
}
public GetChangesResponse getChangesCDCSDK(YBTable table, String streamId,
String tabletId, long term,
long index, byte[] key,
int write_id, long time,
boolean needSchemaInfo) throws Exception {
Deferred<GetChangesResponse> d = asyncClient.getChangesCDCSDK(
table, streamId, tabletId, term, index, key, write_id, time, needSchemaInfo);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
public GetChangesResponse getChangesCDCSDK(YBTable table, String streamId,
String tabletId, long term,
long index, byte[] key,
int write_id, long time,
boolean needSchemaInfo,
CdcSdkCheckpoint explicitCheckpoint) throws Exception {
Deferred<GetChangesResponse> d = asyncClient.getChangesCDCSDK(
table, streamId, tabletId, term, index, key, write_id, time, needSchemaInfo,
explicitCheckpoint);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
public GetChangesResponse getChangesCDCSDK(YBTable table, String streamId,
String tabletId, long term,
long index, byte[] key,
int write_id, long time,
boolean needSchemaInfo,
CdcSdkCheckpoint explicitCheckpoint,
long safeHybridTime) throws Exception {
Deferred<GetChangesResponse> d = asyncClient.getChangesCDCSDK(
table, streamId, tabletId, term, index, key, write_id, time, needSchemaInfo,
explicitCheckpoint, safeHybridTime);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
public GetChangesResponse getChangesCDCSDK(YBTable table, String streamId, String tabletId,
long term, long index, byte[] key, int write_id, long time, boolean needSchemaInfo,
CdcSdkCheckpoint explicitCheckpoint, long safeHybridTime, int walSegmentIndex)
throws Exception {
Deferred<GetChangesResponse> d =
asyncClient.getChangesCDCSDK(table, streamId, tabletId, term, index, key, write_id, time,
needSchemaInfo, explicitCheckpoint, safeHybridTime, walSegmentIndex);
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
public GetCheckpointResponse getCheckpoint(YBTable table, String streamId,
String tabletId) throws Exception {
Deferred<GetCheckpointResponse> d = asyncClient
.getCheckpoint(table, streamId, tabletId);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
public GetDBStreamInfoResponse getDBStreamInfo(String streamId) throws Exception {
Deferred<GetDBStreamInfoResponse> d = asyncClient
.getDBStreamInfo(streamId);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of child tablets for a given parent tablet.
*
* @param table the {@link YBTable} instance of the table
* @param streamId the DB stream ID to read from in the cdc_state table
* @param tableId the UUID of the table to which the parent tablet belongs
* @param tabletId the UUID of the parent tablet
* @return an RPC response containing the list of child tablets
* @throws Exception
*/
public GetTabletListToPollForCDCResponse getTabletListToPollForCdc(
YBTable table, String streamId, String tableId, String tabletId) throws Exception {
Deferred<GetTabletListToPollForCDCResponse> d = asyncClient
.getTabletListToPollForCdc(table, streamId, tableId, tabletId);
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
/**
* Get the list of tablets by reading the entries in the cdc_state table for a given table and
* DB stream ID.
* @param table the {@link YBTable} instance of the table
* @param streamId the DB stream ID to read from in the cdc_state table
* @param tableId the UUID of the table for which we need the tablets to poll for
* @return an RPC response containing the list of tablets to poll for
* @throws Exception
*/
public GetTabletListToPollForCDCResponse getTabletListToPollForCdc(
YBTable table, String streamId, String tableId) throws Exception {
return getTabletListToPollForCdc(table, streamId, tableId, "");
}
/**
* [Test purposes only] Split the provided tablet.
* @param tabletId the UUID of the tablet to split
* @return {@link SplitTabletResponse}
* @throws Exception
*/
public SplitTabletResponse splitTablet(String tabletId) throws Exception {
Deferred<SplitTabletResponse> d = asyncClient.splitTablet(tabletId);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
/**
* [Test purposes only] Flush and compact the provided table. Note that you will need to wait
* accordingly for the table to get flushed and the SST files to get created.
* @param tableId the UUID of the table to compact
* @return an RPC response of type {@link FlushTableResponse} containing the flush request ID
* @throws Exception
*/
public FlushTableResponse flushTable(String tableId) throws Exception {
Deferred<FlushTableResponse> d = asyncClient.flushTable(tableId);
return d.join(2*getDefaultAdminOperationTimeoutMs());
}
public SetCheckpointResponse commitCheckpoint(YBTable table, String streamId,
String tabletId,
long term,
long index,
boolean initialCheckpoint) throws Exception {
return commitCheckpoint(table, streamId, tabletId, term, index, initialCheckpoint,
false /* bootstrap */ , null /* cdcsdkSafeTime */);
}
public SetCheckpointResponse commitCheckpoint(YBTable table, String streamId,
String tabletId,
long term,
long index,
boolean initialCheckpoint,
boolean bootstrap,
Long cdcsdkSafeTime) throws Exception {
Deferred<SetCheckpointResponse> d = asyncClient.setCheckpoint(table, streamId, tabletId, term,
index, initialCheckpoint, bootstrap, cdcsdkSafeTime);
d.addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(Exception o) throws Exception {
o.printStackTrace();
throw o;
}
});
d.addCallback(setCheckpointResponse -> {
return setCheckpointResponse;
});
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
/**
* Get the status of current server.
* @param host the address to bind to.
* @param port the port to bind to (0 means any free port).
* @return an object containing the status details of the server.
* @throws Exception
*/
public GetStatusResponse getStatus(final String host, int port) throws Exception {
Deferred<GetStatusResponse> d = asyncClient.getStatus(HostAndPort.fromParts(host, port));
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
/**
* Get the auto flag config for servers.
* @return auto flag config for each server if exists, else a MasterErrorException.
*/
public GetAutoFlagsConfigResponse autoFlagsConfig() throws Exception {
Deferred<GetAutoFlagsConfigResponse> d = asyncClient.autoFlagsConfig();
d.addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(Exception o) throws Exception {
LOG.error("Error: ", o);
throw o;
}
});
d.addCallback(getAutoFlagsConfigResponse -> {
return getAutoFlagsConfigResponse;
});
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
/**
* Promotes the auto flag config for each servers.
* @param maxFlagClass class category up to which auto flag should be promoted.
* @param promoteNonRuntimeFlags promotes auto flag non-runtime flags if true.
* @param force promotes auto flag forcefully if true.
* @return response from the server for promoting auto flag config, else a MasterErrorException.
*/
public PromoteAutoFlagsResponse promoteAutoFlags(String maxFlagClass,
boolean promoteNonRuntimeFlags,
boolean force) throws Exception {
Deferred<PromoteAutoFlagsResponse> d = asyncClient.getPromoteAutoFlagsResponse(
maxFlagClass,
promoteNonRuntimeFlags,
force);
d.addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(Exception o) throws Exception {
LOG.error("Error: ", o);
throw o;
}
});
d.addCallback(promoteAutoFlagsResponse -> {
return promoteAutoFlagsResponse;
});
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
/**
* Rollbacks the auto flag config for each servers.
* @param rollbackVersion auto flags version to which rollback is desired.
* @return response from the server for rolling back auto flag config,
* else a MasterErrorException.
*/
public RollbackAutoFlagsResponse rollbackAutoFlags(int rollbackVersion) throws Exception {
Deferred<RollbackAutoFlagsResponse> d = asyncClient.getRollbackAutoFlagsResponse(
rollbackVersion);
d.addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(Exception o) throws Exception {
LOG.error("Error: ", o);
throw o;
}
});
d.addCallback(rollbackAutoFlagsResponse -> {
return rollbackAutoFlagsResponse;
});
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
public SetCheckpointResponse bootstrapTablet(YBTable table, String streamId,
String tabletId,
long term,
long index,
boolean initialCheckpoint,
boolean bootstrap) throws Exception {
Deferred<SetCheckpointResponse> d = asyncClient.setCheckpointWithBootstrap(table, streamId,
tabletId, term, index, initialCheckpoint, bootstrap);
d.addErrback(new Callback<Exception, Exception>() {
@Override
public Exception call(Exception o) throws Exception {
o.printStackTrace();
throw o;
}
});
d.addCallback(setCheckpointResponse -> {
return setCheckpointResponse;
});
return d.join(2 * getDefaultAdminOperationTimeoutMs());
}
public DeleteUniverseReplicationResponse deleteUniverseReplication(
String replicationGroupName, boolean ignoreErrors) throws Exception {
Deferred<DeleteUniverseReplicationResponse> d =
asyncClient.deleteUniverseReplication(replicationGroupName, ignoreErrors);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public DeleteUniverseReplicationResponse deleteUniverseReplication(
String replicationGroupName) throws Exception {
return deleteUniverseReplication(replicationGroupName, false /* ignoreErrors */);
}
public GetUniverseReplicationResponse getUniverseReplication(
String replicationGrouopName) throws Exception {
Deferred<GetUniverseReplicationResponse> d =
asyncClient.getUniverseReplication(replicationGrouopName);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public BootstrapUniverseResponse bootstrapUniverse(
final HostAndPort hostAndPort, List<String> tableIds) throws Exception {
Deferred<BootstrapUniverseResponse> d =
asyncClient.bootstrapUniverse(hostAndPort, tableIds);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/** See {@link AsyncYBClient#changeXClusterRole(org.yb.cdc.CdcConsumer.XClusterRole)} */
public ChangeXClusterRoleResponse changeXClusterRole(XClusterRole role) throws Exception {
Deferred<ChangeXClusterRoleResponse> d = asyncClient.changeXClusterRole(role);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* It checks whether a bootstrap flow is required to set up replication or in case an existing
* stream has fallen far behind.
*
* @param tableIdsStreamIdMap A map of table ids to their corresponding stream id if any
* @return A deferred object that yields a {@link IsBootstrapRequiredResponse} which contains
* a map of each table id to a boolean showing whether bootstrap is required for that
* table
*/
public IsBootstrapRequiredResponse isBootstrapRequired(
Map<String, String> tableIdsStreamIdMap) throws Exception {
Deferred<IsBootstrapRequiredResponse> d =
asyncClient.isBootstrapRequired(tableIdsStreamIdMap);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* It makes parallel calls to {@link AsyncYBClient#isBootstrapRequired(java.util.Map)} method with
* batches of {@code partitionSize} tables.
*
* @see YBClient#isBootstrapRequired(java.util.Map)
*/
public List<IsBootstrapRequiredResponse> isBootstrapRequiredParallel(
Map<String, String> tableIdStreamIdMap, int partitionSize) throws Exception {
// Partition the tableIdStreamIdMap.
List<Map<String, String>> tableIdStreamIdMapList = new ArrayList<>();
Iterator<Entry<String, String>> iter = tableIdStreamIdMap.entrySet().iterator();
while (iter.hasNext()) {
Map<String, String> partition = new HashMap<>();
tableIdStreamIdMapList.add(partition);
while (partition.size() < partitionSize && iter.hasNext()) {
Entry<String, String> entry = iter.next();
partition.put(entry.getKey(), entry.getValue());
}
}
// Make the requests asynchronously.
List<Deferred<IsBootstrapRequiredResponse>> ds = new ArrayList<>();
for (Map<String, String> tableIdStreamId : tableIdStreamIdMapList) {
ds.add(asyncClient.isBootstrapRequired(tableIdStreamId));
}
// Wait for all the request to join.
List<IsBootstrapRequiredResponse> isBootstrapRequiredList = new ArrayList<>();
for (Deferred<IsBootstrapRequiredResponse> d : ds) {
isBootstrapRequiredList.add(d.join(getDefaultAdminOperationTimeoutMs()));
}
return isBootstrapRequiredList;
}
public GetReplicationStatusResponse getReplicationStatus(
@Nullable String replicationGroupName) throws Exception {
Deferred<GetReplicationStatusResponse> d =
asyncClient.getReplicationStatus(replicationGroupName);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public GetXClusterSafeTimeResponse getXClusterSafeTime() throws Exception {
Deferred<GetXClusterSafeTimeResponse> d = asyncClient.getXClusterSafeTime();
return d.join(getDefaultAdminOperationTimeoutMs());
}
public WaitForReplicationDrainResponse waitForReplicationDrain(
List<String> streamIds,
@Nullable Long targetTime) throws Exception {
Deferred<WaitForReplicationDrainResponse> d =
asyncClient.waitForReplicationDrain(streamIds, targetTime);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public WaitForReplicationDrainResponse waitForReplicationDrain(
List<String> streamIds) throws Exception {
return waitForReplicationDrain(streamIds, null /* targetTime */);
}
/**
* Get information about the namespace/database.
* @param keyspaceName namespace name to get details about.
* @param databaseType database type the database belongs to.
* @return details for the namespace.
* @throws Exception
*/
public GetNamespaceInfoResponse getNamespaceInfo(String keyspaceName,
YQLDatabase databaseType) throws Exception {
Deferred<GetNamespaceInfoResponse> d = asyncClient.getNamespaceInfo(keyspaceName, databaseType);
return d.join(getDefaultOperationTimeoutMs());
}
/**
* @see AsyncYBClient#listCDCStreams(String, String, MasterReplicationOuterClass.IdTypePB)
*/
public ListCDCStreamsResponse listCDCStreams(
String tableId,
String namespaceId,
MasterReplicationOuterClass.IdTypePB idType) throws Exception {
Deferred<ListCDCStreamsResponse> d =
asyncClient.listCDCStreams(tableId, namespaceId, idType);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* @see AsyncYBClient#deleteCDCStream(Set, boolean, boolean)
*/
public DeleteCDCStreamResponse deleteCDCStream(Set<String> streamIds,
boolean ignoreErrors,
boolean forceDelete) throws Exception {
Deferred<DeleteCDCStreamResponse> d =
asyncClient.deleteCDCStream(streamIds, ignoreErrors, forceDelete);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* @see AsyncYBClient#getTabletLocations(List<String>, String, boolean, boolean)
*/
public GetTabletLocationsResponse getTabletLocations(List<String> tabletIds,
String tableId,
boolean includeInactive,
boolean includeDeleted)
throws Exception {
Deferred<GetTabletLocationsResponse> d =
asyncClient.getTabletLocations(tabletIds, tableId, includeInactive, includeDeleted);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public CreateSnapshotScheduleResponse createSnapshotSchedule(
YQLDatabase databaseType,
String keyspaceName,
long retentionInSecs,
long timeIntervalInSecs) throws Exception {
Deferred<CreateSnapshotScheduleResponse> d =
asyncClient.createSnapshotSchedule(databaseType, keyspaceName,
retentionInSecs, timeIntervalInSecs);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public CreateSnapshotScheduleResponse createSnapshotSchedule(
YQLDatabase databaseType,
String keyspaceName,
String keyspaceId,
long retentionInSecs,
long timeIntervalInSecs) throws Exception {
Deferred<CreateSnapshotScheduleResponse> d =
asyncClient.createSnapshotSchedule(
databaseType,
keyspaceName,
keyspaceId,
retentionInSecs,
timeIntervalInSecs);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public DeleteSnapshotScheduleResponse deleteSnapshotSchedule(
UUID snapshotScheduleUUID) throws Exception {
Deferred<DeleteSnapshotScheduleResponse> d =
asyncClient.deleteSnapshotSchedule(snapshotScheduleUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public ListSnapshotSchedulesResponse listSnapshotSchedules(
UUID snapshotScheduleUUID) throws Exception {
Deferred<ListSnapshotSchedulesResponse> d =
asyncClient.listSnapshotSchedules(snapshotScheduleUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public RestoreSnapshotScheduleResponse restoreSnapshotSchedule(UUID snapshotScheduleUUID,
long restoreTimeInMillis) throws Exception {
Deferred<RestoreSnapshotScheduleResponse> d =
asyncClient.restoreSnapshotSchedule(snapshotScheduleUUID, restoreTimeInMillis);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public ListSnapshotRestorationsResponse listSnapshotRestorations(
UUID restorationUUID) throws Exception {
Deferred<ListSnapshotRestorationsResponse> d =
asyncClient.listSnapshotRestorations(restorationUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public ListSnapshotsResponse listSnapshots(UUID snapshotUUID,
boolean listDeletedSnapshots) throws Exception {
Deferred<ListSnapshotsResponse> d =
asyncClient.listSnapshots(snapshotUUID, listDeletedSnapshots);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public DeleteSnapshotResponse deleteSnapshot(
UUID snapshotUUID) throws Exception {
Deferred<DeleteSnapshotResponse> d =
asyncClient.deleteSnapshot(snapshotUUID);
return d.join(getDefaultAdminOperationTimeoutMs());
}
public ValidateReplicationInfoResponse validateReplicationInfo(
ReplicationInfoPB replicationInfoPB) throws Exception {
Deferred<ValidateReplicationInfoResponse> d =
asyncClient.validateReplicationInfo(replicationInfoPB);
return d.join(getDefaultAdminOperationTimeoutMs());
}
/**
* Analogous to {@link #shutdown()}.
* @throws Exception if an error happens while closing the connections
*/
@Override
public void close() throws Exception {
asyncClient.close();
}
/**
* Performs a graceful shutdown of this instance.
* @throws Exception
*/
public void shutdown() throws Exception {
asyncClient.shutdown();
}
/**
* Get the timeout used for operations on sessions and scanners.
* @return a timeout in milliseconds
*/
public long getDefaultOperationTimeoutMs() {
return asyncClient.getDefaultOperationTimeoutMs();
}
/**
* Get the timeout used for admin operations.
* @return a timeout in milliseconds
*/
public long getDefaultAdminOperationTimeoutMs() {
return asyncClient.getDefaultAdminOperationTimeoutMs();
}
/**
* Builder class to use in order to connect to YB.
* All the parameters beyond those in the constructors are optional.
*/
public final static class YBClientBuilder {
private AsyncYBClient.AsyncYBClientBuilder clientBuilder;
/**
* Creates a new builder for a client that will connect to the specified masters.
* @param masterAddresses comma-separated list of "host:port" pairs of the masters
*/
public YBClientBuilder(String masterAddresses) {
clientBuilder = new AsyncYBClient.AsyncYBClientBuilder(masterAddresses);
}
/**
* Creates a new builder for a client that will connect to the specified masters.
*
* <p>Here are some examples of recognized formats:
* <ul>
* <li>example.com
* <li>example.com:80
* <li>192.0.2.1
* <li>192.0.2.1:80
* <li>[2001:db8::1]
* <li>[2001:db8::1]:80
* <li>2001:db8::1
* </ul>
*
* @param masterAddresses list of master addresses
*/
public YBClientBuilder(List<String> masterAddresses) {
clientBuilder = new AsyncYBClient.AsyncYBClientBuilder(masterAddresses);
}
/**
* Sets the default timeout used for administrative operations (e.g. createTable, deleteTable,
* etc).
* Optional.
* If not provided, defaults to 10s.
* A value of 0 disables the timeout.
* @param timeoutMs a timeout in milliseconds
* @return this builder
*/
public YBClientBuilder defaultAdminOperationTimeoutMs(long timeoutMs) {
clientBuilder.defaultAdminOperationTimeoutMs(timeoutMs);
return this;
}
/**
* Sets the default timeout used for user operations (using sessions and scanners).
* Optional.
* If not provided, defaults to 10s.
* A value of 0 disables the timeout.
* @param timeoutMs a timeout in milliseconds
* @return this builder
*/
public YBClientBuilder defaultOperationTimeoutMs(long timeoutMs) {
clientBuilder.defaultOperationTimeoutMs(timeoutMs);
return this;
}
/**
* Sets the default timeout to use when waiting on data from a socket.
* Optional.
* If not provided, defaults to 5s.
* A value of 0 disables the timeout.
* @param timeoutMs a timeout in milliseconds
* @return this builder
*/
public YBClientBuilder defaultSocketReadTimeoutMs(long timeoutMs) {
clientBuilder.defaultSocketReadTimeoutMs(timeoutMs);
return this;
}
/**
* Sets the certificate file in case SSL is enabled.
* Optional.
* If not provided, defaults to null.
* A value of null disables an SSL connection.
* @param certFile the path to the certificate.
* @return this builder
*/
public YBClientBuilder sslCertFile(String certFile) {
clientBuilder.sslCertFile(certFile);
return this;
}
/**
* Sets the client cert and key files if mutual auth is enabled.
* Optional.
* If not provided, defaults to null.
* A value of null disables an mTLS connection.
* @param certFile the path to the client certificate.
* @param keyFile the path to the client private key file.
* @return this builder
*/
public YBClientBuilder sslClientCertFiles(String certFile, String keyFile) {
clientBuilder.sslClientCertFiles(certFile, keyFile);
return this;
}
/**
* Sets the outbound client host:port on which the socket binds.
* Optional.
* If not provided, defaults to null.
* @param host the address to bind to.
* @param port the port to bind to (0 means any free port).
* @return this builder
*/
public YBClientBuilder bindHostAddress(String host, int port) {
clientBuilder.bindHostAddress(host, port);
return this;
}
/**
* Single thread pool is used in netty4 to handle client IO
*/
@Deprecated
@SuppressWarnings("unused")
public YBClientBuilder nioExecutors(Executor bossExecutor, Executor workerExecutor) {
return executor(workerExecutor);
}
/**
* Set the executors which will be used for the embedded Netty workers.
* Optional.
* If not provided, uses a simple cached threadpool. If either argument is null,
* then such a thread pool will be used in place of that argument.
* Note: executor's max thread number must be greater or equal to corresponding
* thread count, or netty cannot start enough threads, and client will get stuck.
* If not sure, please just use CachedThreadPool.
*/
public YBClientBuilder executor(Executor executor) {
clientBuilder.executor(executor);
return this;
}
/**
* Single thread pool is used in netty4 to handle client IO
*/
@Deprecated
@SuppressWarnings("unused")
public YBClientBuilder bossCount(int workerCount) {
return this;
}
/**
* Set the maximum number of worker threads.
* Optional.
* If not provided, (2 * the number of available processors) is used.
*/
public YBClientBuilder workerCount(int workerCount) {
clientBuilder.workerCount(workerCount);
return this;
}
/**
* Creates a new client that connects to the masters.
* Doesn't block and won't throw an exception if the masters don't exist.
* @return a new asynchronous YB client
*/
public YBClient build() {
AsyncYBClient client = clientBuilder.build();
return new YBClient(client);
}
}
}
| yugabyte/yugabyte-db | java/yb-client/src/main/java/org/yb/client/YBClient.java |
45,333 | /*
* Copyright 2004-2024 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (https://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import org.h2.compress.CompressDeflate;
import org.h2.compress.CompressLZF;
import org.h2.compress.Compressor;
import org.h2.mvstore.type.StringDataType;
import org.h2.store.fs.FileUtils;
import org.h2.util.Utils;
/*
TODO:
Documentation
- rolling docs review: at "Metadata Map"
- better document that writes are in background thread
- better document how to do non-unique indexes
- document pluggable store and OffHeapStore
TransactionStore:
- ability to disable the transaction log,
if there is only one connection
MVStore:
- better and clearer memory usage accounting rules
(heap memory versus disk memory), so that even there is
never an out of memory
even for a small heap, and so that chunks
are still relatively big on average
- make sure serialization / deserialization errors don't corrupt the file
- test and possibly improve compact operation (for large dbs)
- automated 'kill process' and 'power failure' test
- defragment (re-creating maps, specially those with small pages)
- store number of write operations per page (maybe defragment
if much different than count)
- r-tree: nearest neighbor search
- use a small object value cache (StringCache), test on Android
for default serialization
- MVStoreTool.dump should dump the data if possible;
possibly using a callback for serialization
- implement a sharded map (in one store, multiple stores)
to support concurrent updates and writes, and very large maps
- to save space when persisting very small transactions,
use a transaction log where only the deltas are stored
- serialization for lists, sets, sets, sorted sets, maps, sorted maps
- maybe rename 'rollback' to 'revert' to distinguish from transactions
- support other compression algorithms (deflate, LZ4,...)
- remove features that are not really needed; simplify the code
possibly using a separate layer or tools
(retainVersion?)
- optional pluggable checksum mechanism (per page), which
requires that everything is a page (including headers)
- rename "store" to "save", as "store" is used in "storeVersion"
- rename setStoreVersion to setDataVersion, setSchemaVersion or similar
- temporary file storage
- simple rollback method (rollback to last committed version)
- MVMap to implement SortedMap, then NavigableMap
- storage that splits database into multiple files,
to speed up compact and allow using trim
(by truncating / deleting empty files)
- add new feature to the file system API to avoid copying data
(reads that returns a ByteBuffer instead of writing into one)
for memory mapped files and off-heap storage
- support log structured merge style operations (blind writes)
using one map per level plus bloom filter
- have a strict call order MVStore -> MVMap -> Page -> FileStore
- autocommit commits, stores, and compacts from time to time;
the background thread should wait at least 90% of the
configured write delay to store changes
- compact* should also store uncommitted changes (if there are any)
- write a LSM-tree (log structured merge tree) utility on top of the MVStore
with blind writes and/or a bloom filter that
internally uses regular maps and merge sort
- chunk metadata: maybe split into static and variable,
or use a small page size for metadata
- data type "string": maybe use prefix compression for keys
- test chunk id rollover
- feature to auto-compact from time to time and on close
- compact very small chunks
- Page: to save memory, combine keys & values into one array
(also children & counts). Maybe remove some other
fields (childrenCount for example)
- Support SortedMap for MVMap
- compact: copy whole pages (without having to open all maps)
- maybe change the length code to have lower gaps
- test with very low limits (such as: short chunks, small pages)
- maybe allow to read beyond the retention time:
when compacting, move live pages in old chunks
to a map (possibly the metadata map) -
this requires a change in the compaction code, plus
a map lookup when reading old data; also, this
old data map needs to be cleaned up somehow;
maybe using an additional timeout
*/
/**
* A persistent storage for maps.
*/
public final class MVStore implements AutoCloseable {
/**
* Store is open.
*/
private static final int STATE_OPEN = 0;
/**
* Store is about to close now, but is still operational.
* Outstanding store operation by background writer or other thread may be in progress.
* New updates must not be initiated, unless they are part of a closing procedure itself.
*/
private static final int STATE_STOPPING = 1;
/**
* Store is closed.
*/
private static final int STATE_CLOSED = 2;
/**
* This designates the "last stored" version for a store which was
* just open for the first time.
*/
static final long INITIAL_VERSION = -1;
/**
* Lock which governs access to major store operations: store(), close(), ...
* It serves as a replacement for synchronized(this), except it allows for
* non-blocking lock attempts.
*/
private final ReentrantLock storeLock = new ReentrantLock(true);
/**
* Flag to refine the state under storeLock.
* It indicates that store() operation is running, and we have to prevent possible re-entrance.
*/
private final AtomicBoolean storeOperationInProgress = new AtomicBoolean();
private volatile int state;
private final FileStore<?> fileStore;
private final boolean fileStoreShallBeClosed;
private final int keysPerPage;
private long updateCounter = 0;
private long updateAttemptCounter = 0;
/**
* The metadata map. Holds name -> id and id -> name and id -> metadata
* mapping for all maps. This is relatively slow changing part of metadata
*/
private final MVMap<String, String> meta;
private final ConcurrentHashMap<Integer, MVMap<?, ?>> maps = new ConcurrentHashMap<>();
private final AtomicInteger lastMapId = new AtomicInteger();
private int versionsToKeep = 5;
/**
* The compression level for new pages (0 for disabled, 1 for fast, 2 for
* high). Even if disabled, the store may contain (old) compressed pages.
*/
private final int compressionLevel;
private Compressor compressorFast;
private Compressor compressorHigh;
public final UncaughtExceptionHandler backgroundExceptionHandler;
private volatile long currentVersion;
/**
* Oldest store version in use. All version beyond this can be safely dropped
*/
private final AtomicLong oldestVersionToKeep = new AtomicLong();
/**
* Ordered collection of all version usage counters for all versions starting
* from oldestVersionToKeep and up to current.
*/
private final Deque<TxCounter> versions = new LinkedList<>();
/**
* Counter of open transactions for the latest (current) store version
*/
private volatile TxCounter currentTxCounter = new TxCounter(currentVersion);
/**
* The estimated memory used by unsaved pages. This number is not accurate,
* also because it may be changed concurrently, and because temporary pages
* are counted.
*/
private int unsavedMemory;
private final int autoCommitMemory;
private volatile boolean saveNeeded;
private volatile boolean metaChanged;
private volatile MVStoreException panicException;
private long lastTimeAbsolute;
private long leafCount;
private long nonLeafCount;
/**
* Callback for maintenance after some unused store versions were dropped
*/
private volatile LongConsumer oldestVersionTracker;
/**
* Create and open the store.
*
* @param config the configuration to use
* @throws MVStoreException if the file is corrupt, or an exception
* occurred while opening
* @throws IllegalArgumentException if the directory does not exist
*/
MVStore(Map<String, Object> config) {
compressionLevel = DataUtils.getConfigParam(config, "compress", 0);
String fileName = (String) config.get("fileName");
FileStore<?> fileStore = (FileStore<?>) config.get("fileStore");
boolean fileStoreShallBeOpen = false;
if (fileStore == null) {
if (fileName != null) {
fileStore = new SingleFileStore(config);
fileStoreShallBeOpen = true;
}
fileStoreShallBeClosed = true;
} else {
if (fileName != null) {
throw new IllegalArgumentException("fileName && fileStore");
}
Boolean fileStoreIsAdopted = (Boolean) config.get("fileStoreIsAdopted");
fileStoreShallBeClosed = fileStoreIsAdopted != null && fileStoreIsAdopted;
}
this.fileStore = fileStore;
keysPerPage = DataUtils.getConfigParam(config, "keysPerPage", 48);
backgroundExceptionHandler =
(UncaughtExceptionHandler)config.get("backgroundExceptionHandler");
if (fileStore != null) {
// 19 KB memory is about 1 KB storage
int kb = Math.max(1, Math.min(19, Utils.scaleForAvailableMemory(64))) * 1024;
kb = DataUtils.getConfigParam(config, "autoCommitBufferSize", kb);
autoCommitMemory = kb * 1024;
char[] encryptionKey = (char[]) config.remove("encryptionKey");
MVMap<String, String> metaMap = null;
// there is no need to lock store here, since it is not opened (or even created) yet,
// just to make some assertions happy, when they ensure single-threaded access
storeLock.lock();
try {
if (fileStoreShallBeOpen) {
boolean readOnly = config.containsKey("readOnly");
fileStore.open(fileName, readOnly, encryptionKey);
}
fileStore.bind(this);
metaMap = fileStore.start();
} catch (MVStoreException e) {
panic(e);
} finally {
if (encryptionKey != null) {
Arrays.fill(encryptionKey, (char) 0);
}
unlockAndCheckPanicCondition();
}
meta = metaMap;
scrubMetaMap();
// setAutoCommitDelay starts the thread, but only if
// the parameter is different from the old value
int delay = DataUtils.getConfigParam(config, "autoCommitDelay", 1000);
setAutoCommitDelay(delay);
} else {
autoCommitMemory = 0;
meta = openMetaMap();
}
onVersionChange(currentVersion);
}
public MVMap<String,String> openMetaMap() {
int metaId = fileStore != null ? fileStore.getMetaMapId(this::getNextMapId) : 1;
MVMap<String,String> map = new MVMap<>(this, metaId, StringDataType.INSTANCE, StringDataType.INSTANCE);
map.setRootPos(getRootPos(map.getId()), currentVersion);
return map;
}
private void scrubMetaMap() {
Set<String> keysToRemove = new HashSet<>();
// ensure that there is only one name mapped to each id
// this could be a leftover of an unfinished map rename
for (Iterator<String> it = meta.keyIterator(DataUtils.META_NAME); it.hasNext();) {
String key = it.next();
if (!key.startsWith(DataUtils.META_NAME)) {
break;
}
String mapName = key.substring(DataUtils.META_NAME.length());
int mapId = DataUtils.parseHexInt(meta.get(key));
String realMapName = getMapName(mapId);
if(!mapName.equals(realMapName)) {
keysToRemove.add(key);
}
}
for (String key : keysToRemove) {
meta.remove(key);
markMetaChanged();
}
for (Iterator<String> it = meta.keyIterator(DataUtils.META_MAP); it.hasNext();) {
String key = it.next();
if (!key.startsWith(DataUtils.META_MAP)) {
break;
}
String mapName = DataUtils.getMapName(meta.get(key));
String mapIdStr = key.substring(DataUtils.META_MAP.length());
// ensure that last map id is not smaller than max of any existing map ids
adjustLastMapId(DataUtils.parseHexInt(mapIdStr));
// each map should have a proper name
if(!mapIdStr.equals(meta.get(DataUtils.META_NAME + mapName))) {
meta.put(DataUtils.META_NAME + mapName, mapIdStr);
markMetaChanged();
}
}
}
private void unlockAndCheckPanicCondition() {
storeLock.unlock();
MVStoreException exception = getPanicException();
if (exception != null) {
closeImmediately();
throw exception;
}
}
public void panic(MVStoreException e) {
if (isOpen()) {
handleException(e);
panicException = e;
}
throw e;
}
public MVStoreException getPanicException() {
return panicException;
}
/**
* Open a store in exclusive mode. For a file-based store, the parent
* directory must already exist.
*
* @param fileName the file name (null for in-memory)
* @return the store
*/
public static MVStore open(String fileName) {
HashMap<String, Object> config = new HashMap<>();
config.put("fileName", fileName);
return new MVStore(config);
}
/**
* Open a map with the default settings. The map is automatically create if
* it does not yet exist. If a map with this name is already open, this map
* is returned.
*
* @param <K> the key type
* @param <V> the value type
* @param name the name of the map
* @return the map
*/
public <K, V> MVMap<K, V> openMap(String name) {
return openMap(name, new MVMap.Builder<>());
}
/**
* Open a map with the given builder. The map is automatically create if it
* does not yet exist. If a map with this name is already open, this map is
* returned.
*
* @param <M> the map type
* @param <K> the key type
* @param <V> the value type
* @param name the name of the map
* @param builder the map builder
* @return the map
*/
public <M extends MVMap<K, V>, K, V> M openMap(String name, MVMap.MapBuilder<M, K, V> builder) {
int id = getMapId(name);
if (id >= 0) {
@SuppressWarnings("unchecked")
M map = (M) getMap(id);
if(map == null) {
map = openMap(id, builder);
}
assert builder.getKeyType() == null || map.getKeyType().getClass().equals(builder.getKeyType().getClass());
assert builder.getValueType() == null
|| map.getValueType().getClass().equals(builder.getValueType().getClass());
return map;
} else {
HashMap<String, Object> c = new HashMap<>();
id = getNextMapId();
assert getMap(id) == null;
c.put("id", id);
long curVersion = currentVersion;
c.put("createVersion", curVersion);
M map = builder.create(this, c);
String x = Integer.toHexString(id);
meta.put(MVMap.getMapKey(id), map.asString(name));
String existing = meta.putIfAbsent(DataUtils.META_NAME + name, x);
if (existing != null) {
// looks like map was created concurrently, cleanup and re-start
meta.remove(MVMap.getMapKey(id));
return openMap(name, builder);
}
map.setRootPos(0, curVersion);
markMetaChanged();
@SuppressWarnings("unchecked")
M existingMap = (M) maps.putIfAbsent(id, map);
if (existingMap != null) {
map = existingMap;
}
return map;
}
}
/**
* Open an existing map with the given builder.
*
* @param <M> the map type
* @param <K> the key type
* @param <V> the value type
* @param id the map id
* @param builder the map builder
* @return the map
*/
@SuppressWarnings("unchecked")
public <M extends MVMap<K, V>, K, V> M openMap(int id, MVMap.MapBuilder<M, K, V> builder) {
M map;
while ((map = (M)getMap(id)) == null) {
String configAsString = meta.get(MVMap.getMapKey(id));
DataUtils.checkArgument(configAsString != null, "Missing map with id {0}", id);
HashMap<String, Object> config = new HashMap<>(DataUtils.parseMap(configAsString));
config.put("id", id);
map = builder.create(this, config);
long root = getRootPos(id);
map.setRootPos(root, currentVersion);
if (maps.putIfAbsent(id, map) == null) {
break;
}
// looks like map has been concurrently created already, re-start
}
return map;
}
/**
* Get map by id.
*
* @param <K> the key type
* @param <V> the value type
* @param id map id
* @return Map
*/
public <K, V> MVMap<K,V> getMap(int id) {
checkNotClosed();
@SuppressWarnings("unchecked")
MVMap<K, V> map = (MVMap<K, V>) maps.get(id);
return map;
}
/**
* Get the set of all map names.
*
* @return the set of names
*/
public Set<String> getMapNames() {
HashSet<String> set = new HashSet<>();
checkNotClosed();
for (Iterator<String> it = meta.keyIterator(DataUtils.META_NAME); it.hasNext();) {
String x = it.next();
if (!x.startsWith(DataUtils.META_NAME)) {
break;
}
String mapName = x.substring(DataUtils.META_NAME.length());
set.add(mapName);
}
return set;
}
/**
* Get this store's layout map. This data is for informational purposes only. The
* data is subject to change in future versions.
* <p>
* The data in this map should not be modified (changing system data may corrupt the store).
* <p>
* The layout map contains the following entries:
* <pre>
* chunk.{chunkId} = {chunk metadata}
* root.{mapId} = {root position}
* </pre>
*
* @return the metadata map
*/
public Map<String, String> getLayoutMap() {
return fileStore == null ? null : fileStore.getLayoutMap();
}
@SuppressWarnings("ReferenceEquality")
private boolean isRegularMap(MVMap<?,?> map) {
return map != meta && (fileStore == null || fileStore.isRegularMap(map));
}
/**
* Get the metadata map. This data is for informational purposes only. The
* data is subject to change in future versions.
* <p>
* The data in this map should not be modified (changing system data may corrupt the store).
* <p>
* The metadata map contains the following entries:
* <pre>
* name.{name} = {mapId}
* map.{mapId} = {map metadata}
* setting.storeVersion = {version}
* </pre>
*
* @return the metadata map
*/
public MVMap<String, String> getMetaMap() {
checkNotClosed();
return meta;
}
/**
* Check whether a given map exists.
*
* @param name the map name
* @return true if it exists
*/
public boolean hasMap(String name) {
return meta.containsKey(DataUtils.META_NAME + name);
}
/**
* Check whether a given map exists and has data.
*
* @param name the map name
* @return true if it exists and has data.
*/
public boolean hasData(String name) {
return hasMap(name) && getRootPos(getMapId(name)) != 0;
}
void markMetaChanged() {
// changes in the metadata alone are usually not detected, as the meta
// map is changed after storing
metaChanged = true;
}
int getLastMapId() {
return lastMapId.get();
}
private int getNextMapId() {
return lastMapId.incrementAndGet();
}
void adjustLastMapId(int mapId) {
if (mapId > lastMapId.get()) {
lastMapId.set(mapId);
}
}
void resetLastMapId(int mapId) {
lastMapId.set(mapId);
}
/**
* Close the file and the store. Unsaved changes are written to disk first.
*/
@Override
public void close() {
closeStore(true, 0);
}
/**
* Close the store. Pending changes are persisted.
* If time is allocated for housekeeping, chunks with a low
* fill rate are compacted, and some chunks are put next to each other.
* If time is unlimited then full compaction is performed, which uses
* different algorithm - opens alternative temp store and writes all live
* data there, then replaces this store with a new one.
*
* @param allowedCompactionTime time (in milliseconds) allotted for file
* compaction activity, 0 means no compaction,
* -1 means unlimited time (full compaction)
*/
public void close(int allowedCompactionTime) {
if (!isClosed()) {
if (fileStore != null) {
boolean compactFully = allowedCompactionTime == -1;
if (fileStore.isReadOnly()) {
compactFully = false;
} else {
commit();
}
if (compactFully) {
allowedCompactionTime = 0;
}
closeStore(true, allowedCompactionTime);
String fileName = fileStore.getFileName();
if (compactFully && FileUtils.exists(fileName)) {
// the file could have been deleted concurrently,
// so only compact if the file still exists
MVStoreTool.compact(fileName, true);
}
} else {
close();
}
}
}
/**
* Close the file and the store, without writing anything.
* This will try to stop the background thread (without waiting for it).
* This method ignores all errors.
*/
public void closeImmediately() {
try {
closeStore(false, 0);
} catch (Throwable e) {
handleException(e);
}
}
private void closeStore(boolean normalShutdown, int allowedCompactionTime) {
// If any other thead have already initiated closure procedure,
// isClosed() would wait until closure is done and then we jump out of the loop.
// This is a subtle difference between !isClosed() and isOpen().
while (!isClosed()) {
setAutoCommitDelay(-1);
setOldestVersionTracker(null);
storeLock.lock();
try {
if (state == STATE_OPEN) {
state = STATE_STOPPING;
try {
try {
if (normalShutdown && fileStore != null && !fileStore.isReadOnly()) {
for (MVMap<?, ?> map : maps.values()) {
if (map.isClosed()) {
fileStore.deregisterMapRoot(map.getId());
}
}
setRetentionTime(0);
commit();
assert oldestVersionToKeep.get() == currentVersion : oldestVersionToKeep.get() + " != "
+ currentVersion;
fileStore.stop(allowedCompactionTime);
}
if (meta != null) {
meta.close();
}
for (MVMap<?, ?> m : new ArrayList<>(maps.values())) {
m.close();
}
maps.clear();
} finally {
if (fileStore != null && fileStoreShallBeClosed) {
fileStore.close();
}
}
} finally {
state = STATE_CLOSED;
}
}
} finally {
storeLock.unlock();
}
}
}
/**
* Indicates whether this MVStore is backed by FileStore,
* and therefore it's data will survive this store closure
* (but not necessary process termination in case of in-memory store).
* @return true if persistent
*/
public boolean isPersistent() {
return fileStore != null;
}
/**
* Unlike regular commit this method returns immediately if there is commit
* in progress on another thread, otherwise it acts as regular commit.
*
* This method may return BEFORE this thread changes are actually persisted!
*
* @return the new version (incremented if there were changes) or -1 if there were no commit
*/
public long tryCommit() {
return tryCommit(x -> true);
}
private long tryCommit(Predicate<MVStore> check) {
if (canStartStoreOperation() && storeLock.tryLock()) {
try {
if (check.test(this)) {
return store(false);
}
} finally {
unlockAndCheckPanicCondition();
}
}
return INITIAL_VERSION;
}
/**
* Commit the changes.
* <p>
* This method does nothing if there are no unsaved changes,
* otherwise it increments the current version
* and stores the data (for file based stores).
* <p>
* It is not necessary to call this method when auto-commit is enabled (the default
* setting), as in this case it is automatically called from time to time or
* when enough changes have accumulated. However, it may still be called to
* flush all changes to disk.
* <p>
* At most one store operation may run at any time.
*
* @return the new version (incremented if there were changes) or -1 if there were no commit
*/
public long commit() {
return commit(x -> true);
}
private long commit(Predicate<MVStore> check) {
if(canStartStoreOperation()) {
storeLock.lock();
try {
if (check.test(this)) {
return store(true);
}
} finally {
unlockAndCheckPanicCondition();
}
}
return INITIAL_VERSION;
}
private boolean canStartStoreOperation() {
// we need to prevent re-entrance, which may be possible,
// because meta map is modified within storeNow() and that
// causes beforeWrite() call with possibility of going back here
return !storeLock.isHeldByCurrentThread() || !storeOperationInProgress.get();
}
private long store(boolean syncWrite) {
assert storeLock.isHeldByCurrentThread();
if (isOpenOrStopping() && hasUnsavedChanges() && storeOperationInProgress.compareAndSet(false, true)) {
try {
@SuppressWarnings({"NonAtomicVolatileUpdate", "NonAtomicOperationOnVolatileField"})
long result = ++currentVersion;
if (fileStore == null) {
setWriteVersion(currentVersion);
} else {
if (fileStore.isReadOnly()) {
throw DataUtils.newMVStoreException(
DataUtils.ERROR_WRITING_FAILED, "This store is read-only");
}
fileStore.dropUnusedChunks();
storeNow(syncWrite);
}
return result;
} finally {
storeOperationInProgress.set(false);
}
}
return INITIAL_VERSION;
}
private void setWriteVersion(long version) {
for (Iterator<MVMap<?, ?>> iter = maps.values().iterator(); iter.hasNext(); ) {
MVMap<?, ?> map = iter.next();
assert isRegularMap(map);
if (map.setWriteVersion(version) == null) {
iter.remove();
}
}
meta.setWriteVersion(version);
onVersionChange(version);
}
@SuppressWarnings({"NonAtomicVolatileUpdate", "NonAtomicOperationOnVolatileField"})
void storeNow() {
// it is ok, since that path suppose to be single-threaded under storeLock
++currentVersion;
storeNow(true);
}
private void storeNow(boolean syncWrite) {
try {
int currentUnsavedMemory = unsavedMemory;
long version = currentVersion;
assert storeLock.isHeldByCurrentThread();
fileStore.storeIt(collectChangedMapRoots(version), version, syncWrite);
// some pages might have been changed in the meantime (in the newest
// version)
saveNeeded = false;
unsavedMemory = Math.max(0, unsavedMemory - currentUnsavedMemory);
} catch (MVStoreException e) {
panic(e);
} catch (Throwable e) {
panic(DataUtils.newMVStoreException(DataUtils.ERROR_INTERNAL, "{0}", e.toString(),
e));
}
}
private ArrayList<Page<?,?>> collectChangedMapRoots(long version) {
long lastStoredVersion = version - 2;
ArrayList<Page<?,?>> changed = new ArrayList<>();
for (Iterator<MVMap<?, ?>> iter = maps.values().iterator(); iter.hasNext(); ) {
MVMap<?, ?> map = iter.next();
RootReference<?,?> rootReference = map.setWriteVersion(version);
if (rootReference == null) {
iter.remove();
} else if (map.getCreateVersion() < version && // if map was created after storing started, skip it
!map.isVolatile() &&
map.hasChangesSince(lastStoredVersion)) {
assert rootReference.version <= version : rootReference.version + " > " + version;
// simply checking rootPage.isSaved() won't work here because
// after deletion previously saved page
// may pop up as a root, but we still need
// to save new root pos in meta
changed.add(rootReference.root);
}
}
RootReference<?,?> rootReference = meta.setWriteVersion(version);
if (meta.hasChangesSince(lastStoredVersion) || metaChanged) {
assert rootReference != null && rootReference.version <= version
: rootReference == null ? "null" : rootReference.version + " > " + version;
changed.add(rootReference.root);
}
return changed;
}
public long getTimeAbsolute() {
long now = System.currentTimeMillis();
if (lastTimeAbsolute != 0 && now < lastTimeAbsolute) {
// time seems to have run backwards - this can happen
// when the system time is adjusted, for example
// on a leap second
now = lastTimeAbsolute;
} else {
lastTimeAbsolute = now;
}
return now;
}
/**
* Check whether there are any unsaved changes.
*
* @return if there are any changes
*/
public boolean hasUnsavedChanges() {
if (metaChanged) {
return true;
}
long lastStoredVersion = currentVersion - 1;
for (MVMap<?, ?> m : maps.values()) {
if (!m.isClosed()) {
if(m.hasChangesSince(lastStoredVersion)) {
return true;
}
}
}
return fileStore != null && fileStore.hasChangesSince(lastStoredVersion);
}
public void executeFilestoreOperation(Runnable operation) {
storeLock.lock();
try {
checkNotClosed();
fileStore.executeFileStoreOperation(operation);
} catch (MVStoreException e) {
panic(e);
} catch (Throwable e) {
panic(DataUtils.newMVStoreException(
DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
} finally {
unlockAndCheckPanicCondition();
}
}
<R> R tryExecuteUnderStoreLock(Callable<R> operation) throws InterruptedException {
R result = null;
if (storeLock.tryLock(10, TimeUnit.MILLISECONDS)) {
try {
result = operation.call();
} catch (MVStoreException e) {
panic(e);
} catch (Throwable e) {
panic(DataUtils.newMVStoreException(
DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
} finally {
unlockAndCheckPanicCondition();
}
}
return result;
}
/**
* Force all stored changes to be written to the storage. The default
* implementation calls FileChannel.force(true).
*/
public void sync() {
checkOpen();
FileStore<?> f = fileStore;
if (f != null) {
f.sync();
}
}
/**
* Compact store file, that is, compact blocks that have a low
* fill rate, and move chunks next to each other. This will typically
* shrink the file. Changes are flushed to the file, and old
* chunks are overwritten.
*
* @param maxCompactTime the maximum time in milliseconds to compact
*/
public void compactFile(int maxCompactTime) {
if (fileStore != null) {
setRetentionTime(0);
storeLock.lock();
try {
fileStore.compactStore(maxCompactTime);
} finally {
unlockAndCheckPanicCondition();
}
}
}
/**
* Try to increase the fill rate by re-writing partially full chunks. Chunks
* with a low number of live items are re-written.
* <p>
* If the current fill rate is higher than the target fill rate, nothing is
* done.
* <p>
* Please note this method will not necessarily reduce the file size, as
* empty chunks are not overwritten.
* <p>
* Only data of open maps can be moved. For maps that are not open, the old
* chunk is still referenced. Therefore, it is recommended to open all maps
* before calling this method.
*
* @param targetFillRate the minimum percentage of live entries
* @param write the minimum number of bytes to write
* @return if any chunk was re-written
*/
public boolean compact(int targetFillRate, int write) {
checkOpen();
return fileStore != null && fileStore.compact(targetFillRate, write);
}
public int getFillRate() {
return fileStore.getFillRate();
}
/**
* Read a page.
*
* @param <K> key type
* @param <V> value type
*
* @param map the map
* @param pos the page position
* @return the page
*/
<K,V> Page<K,V> readPage(MVMap<K,V> map, long pos) {
checkNotClosed();
return fileStore.readPage(map, pos);
}
/**
* Remove a page.
* @param pos the position of the page
* @param version at which page was removed
* @param pinned whether page is considered pinned
* @param pageNo sequential page number within chunk
*/
void accountForRemovedPage(long pos, long version, boolean pinned, int pageNo) {
fileStore.accountForRemovedPage(pos, version, pinned, pageNo);
}
Compressor getCompressorFast() {
if (compressorFast == null) {
compressorFast = new CompressLZF();
}
return compressorFast;
}
Compressor getCompressorHigh() {
if (compressorHigh == null) {
compressorHigh = new CompressDeflate();
}
return compressorHigh;
}
int getCompressionLevel() {
return compressionLevel;
}
public int getKeysPerPage() {
return keysPerPage;
}
public long getMaxPageSize() {
return fileStore == null ? Long.MAX_VALUE : fileStore.getMaxPageSize();
}
/**
* Get the maximum cache size, in MB.
* Note that this does not include the page chunk references cache, which is
* 25% of the size of the page cache.
*
* @return the cache size
*/
public int getCacheSize() {
return fileStore == null ? 0 : fileStore.getCacheSize();
}
/**
* Get the amount of memory used for caching, in MB.
* Note that this does not include the page chunk references cache, which is
* 25% of the size of the page cache.
*
* @return the amount of memory used for caching
*/
public int getCacheSizeUsed() {
return fileStore == null ? 0 : fileStore.getCacheSizeUsed();
}
/**
* Set the maximum memory to be used by the cache.
*
* @param kb the maximum size in KB
*/
public void setCacheSize(int kb) {
if (fileStore != null) {
fileStore.setCacheSize(Math.max(1, kb / 1024));
}
}
public boolean isSpaceReused() {
return fileStore.isSpaceReused();
}
/**
* Whether empty space in the file should be re-used. If enabled, old data
* is overwritten (default). If disabled, writes are appended at the end of
* the file.
* <p>
* This setting is specially useful for online backup. To create an online
* backup, disable this setting, then copy the file (starting at the
* beginning of the file). In this case, concurrent backup and write
* operations are possible (obviously the backup process needs to be faster
* than the write operations).
*
* @param reuseSpace the new value
*/
public void setReuseSpace(boolean reuseSpace) {
fileStore.setReuseSpace(reuseSpace);
}
public int getRetentionTime() {
return fileStore == null ? 0 : fileStore.getRetentionTime();
}
/**
* How long to retain old, persisted chunks, in milliseconds. Chunks that
* are older may be overwritten once they contain no live data.
* <p>
* The default value is 45000 (45 seconds) when using the default file
* store. It is assumed that a file system and hard disk will flush all
* write buffers within this time. Using a lower value might be dangerous,
* unless the file system and hard disk flush the buffers earlier. To
* manually flush the buffers, use
* <code>MVStore.getFile().force(true)</code>, however please note that
* according to various tests this does not always work as expected
* depending on the operating system and hardware.
* <p>
* The retention time needs to be long enough to allow reading old chunks
* while traversing over the entries of a map.
* <p>
* This setting is not persisted.
*
* @param ms how many milliseconds to retain old chunks (0 to overwrite them
* as early as possible)
*/
public void setRetentionTime(int ms) {
if (fileStore != null) {
fileStore.setRetentionTime(ms);
}
}
/**
* Indicates whether store versions are rolling.
* @return true if versions are rolling, false otherwise
*/
public boolean isVersioningRequired() {
return fileStore != null && !fileStore.isReadOnly() || versionsToKeep > 0;
}
/**
* How many versions to retain for in-memory stores. If not set, 5 old
* versions are retained.
*
* @param count the number of versions to keep
*/
public void setVersionsToKeep(int count) {
this.versionsToKeep = count;
}
/**
* Get the oldest version to retain in memory (for in-memory stores).
*
* @return the version
*/
public long getVersionsToKeep() {
return versionsToKeep;
}
/**
* Get the oldest version to retain.
* We keep at least number of previous versions specified by "versionsToKeep"
* configuration parameter (default 5).
* Previously it was used only in case of non-persistent MVStore.
* Now it's honored in all cases (although H2 always sets it to zero).
* Oldest version determination also takes into account calls (de)registerVersionUsage(),
* and will not release the version, while version is still in use.
*
* @return the version
*/
long getOldestVersionToKeep() {
return Math.min(oldestVersionToKeep.get(),
Math.max(currentVersion - versionsToKeep, INITIAL_VERSION));
}
private void setOldestVersionToKeep(long version) {
boolean success;
do {
long current = oldestVersionToKeep.get();
// Oldest version may only advance, never goes back
success = version <= current ||
oldestVersionToKeep.compareAndSet(current, version);
} while (!success);
assert version <= currentVersion : version + " <= " + currentVersion;
if (oldestVersionTracker != null) {
oldestVersionTracker.accept(version);
}
}
public void setOldestVersionTracker(LongConsumer callback) {
oldestVersionTracker = callback;
}
/**
* Check whether all data can be read from this version. This requires that
* all chunks referenced by this version are still available (not
* overwritten).
*
* @param version the version
* @return true if all data can be read
*/
private boolean isKnownVersion(long version) {
long curVersion = getCurrentVersion();
if (version > curVersion || version < 0) {
return false;
}
if (version == curVersion) {
// no stored data
return true;
}
return fileStore == null || fileStore.isKnownVersion(version);
}
/**
* Adjust amount of "unsaved memory" meaning amount of RAM occupied by pages
* not saved yet to the file. This is the amount which triggers auto-commit.
*
* @param memory adjustment
*/
public void registerUnsavedMemory(int memory) {
assert fileStore != null;
// this counter was intentionally left unprotected against race
// condition for performance reasons
// TODO: evaluate performance impact of atomic implementation,
// since updates to unsavedMemory are largely aggregated now
unsavedMemory += memory;
if (needStore()) {
saveNeeded = true;
}
}
void registerUnsavedMemoryAndCommitIfNeeded(int memory) {
registerUnsavedMemory(memory);
if (saveNeeded) {
commit();
}
}
/**
* This method is called before writing to a map.
*
* @param map the map
*/
void beforeWrite(MVMap<?, ?> map) {
if (saveNeeded && isOpenOrStopping() &&
// condition below is to prevent potential deadlock,
// because we should never seek storeLock while holding
// map root lock
(storeLock.isHeldByCurrentThread() || !map.getRoot().isLockedByCurrentThread()) &&
// to avoid infinite recursion via store() -> dropUnusedChunks() -> layout.remove()
fileStore.isRegularMap(map)) {
saveNeeded = false;
// check again, because it could have been written by now
if (needStore()) {
// if unsaved memory creation rate is too high,
// some back pressure need to be applied
// to slow things down and avoid OOME
if (requireStore() && !map.isSingleWriter()) {
commit(MVStore::requireStore);
} else {
tryCommit(MVStore::needStore);
}
}
}
}
private boolean requireStore() {
return 3 * unsavedMemory > 4 * autoCommitMemory;
}
private boolean needStore() {
return autoCommitMemory > 0 && fileStore.shouldSaveNow(unsavedMemory, autoCommitMemory);
}
/**
* Get the store version. The store version is usually used to upgrade the
* structure of the store after upgrading the application. Initially the
* store version is 0, until it is changed.
*
* @return the store version
*/
public int getStoreVersion() {
checkOpen();
String x = meta.get("setting.storeVersion");
return x == null ? 0 : DataUtils.parseHexInt(x);
}
/**
* Update the store version.
*
* @param version the new store version
*/
public void setStoreVersion(int version) {
storeLock.lock();
try {
checkOpen();
markMetaChanged();
meta.put("setting.storeVersion", Integer.toHexString(version));
} finally {
storeLock.unlock();
}
}
/**
* Revert to the beginning of the current version, reverting all uncommitted
* changes.
*/
public void rollback() {
rollbackTo(currentVersion);
}
/**
* Revert to the beginning of the given version. All later changes (stored
* or not) are forgotten. All maps that were created later are closed. A
* rollback to a version before the last stored version is immediately
* persisted. Rollback to version 0 means all data is removed.
*
* @param version the version to revert to
*/
public void rollbackTo(long version) {
storeLock.lock();
try {
currentVersion = version;
checkOpen();
DataUtils.checkArgument(isKnownVersion(version), "Unknown version {0}", version);
TxCounter txCounter;
while ((txCounter = versions.peekLast()) != null && txCounter.version >= version) {
versions.removeLast();
}
currentTxCounter = new TxCounter(version);
if (oldestVersionToKeep.get() > version) {
oldestVersionToKeep.set(version);
}
if (fileStore != null) {
fileStore.rollbackTo(version);
}
if (!meta.rollbackRoot(version)) {
meta.setRootPos(getRootPos(meta.getId()), version - 1);
}
metaChanged = false;
for (MVMap<?, ?> m : new ArrayList<>(maps.values())) {
int id = m.getId();
if (m.getCreateVersion() >= version) {
m.close();
maps.remove(id);
} else {
if (!m.rollbackRoot(version)) {
m.setRootPos(getRootPos(id), version);
}
}
}
onVersionChange(currentVersion);
assert !hasUnsavedChanges();
} finally {
unlockAndCheckPanicCondition();
}
}
private long getRootPos(int mapId) {
return fileStore == null ? 0 : fileStore.getRootPos(mapId);
}
/**
* Get the current version of the data. When a new store is created, the
* version is 0.
*
* @return the version
*/
public long getCurrentVersion() {
return currentVersion;
}
void setCurrentVersion(long curVersion) {
currentVersion = curVersion;
}
/**
* Get the file store.
*
* @return the file store
*/
public FileStore<?> getFileStore() {
return fileStore;
}
/**
* Get the store header. This data is for informational purposes only. The
* data is subject to change in future versions. The data should not be
* modified (doing so may corrupt the store).
*
* @return the store header
*/
public Map<String, Object> getStoreHeader() {
return fileStore.getStoreHeader();
}
private void checkOpen() {
if (!isOpen()) {
throw DataUtils.newMVStoreException(DataUtils.ERROR_CLOSED,
"This store is closed", panicException);
}
}
private void checkNotClosed() {
if (!isOpenOrStopping()) {
throw DataUtils.newMVStoreException(DataUtils.ERROR_CLOSED,
"This store is closed", panicException);
}
}
/**
* Rename a map.
*
* @param map the map
* @param newName the new name
*/
public void renameMap(MVMap<?, ?> map, String newName) {
checkOpen();
DataUtils.checkArgument(isRegularMap(map), "Renaming the meta map is not allowed");
int id = map.getId();
String oldName = getMapName(id);
if (oldName != null && !oldName.equals(newName)) {
String idHexStr = Integer.toHexString(id);
// at first create a new name as an "alias"
String existingIdHexStr = meta.putIfAbsent(DataUtils.META_NAME + newName, idHexStr);
// we need to cope with the case of previously unfinished rename
DataUtils.checkArgument(
existingIdHexStr == null || existingIdHexStr.equals(idHexStr),
"A map named {0} already exists", newName);
// switch roles of a new and old names - old one is an alias now
meta.put(MVMap.getMapKey(id), map.asString(newName));
// get rid of the old name completely
meta.remove(DataUtils.META_NAME + oldName);
markMetaChanged();
}
}
/**
* Remove a map from the current version of the store.
*
* @param map the map to remove
*/
public void removeMap(MVMap<?,?> map) {
storeLock.lock();
try {
checkOpen();
DataUtils.checkArgument(isRegularMap(map), "Removing the meta map is not allowed");
RootReference<?,?> rootReference = map.clearIt();
map.close();
updateCounter += rootReference.updateCounter;
updateAttemptCounter += rootReference.updateAttemptCounter;
int id = map.getId();
String name = getMapName(id);
if (meta.remove(MVMap.getMapKey(id)) != null) {
markMetaChanged();
}
if (meta.remove(DataUtils.META_NAME + name) != null) {
markMetaChanged();
}
// normally actual map removal is delayed, up until this current version go out os scope,
// but for in-memory case, when versions rolling is turned off, do it now
if (!isVersioningRequired()) {
maps.remove(id);
}
} finally {
storeLock.unlock();
}
}
/**
* Performs final stage of map removal - delete root location info from the layout table.
* Map is supposedly closed and anonymous and has no outstanding usage by now.
*
* @param mapId to deregister
*/
void deregisterMapRoot(int mapId) {
if (fileStore != null && fileStore.deregisterMapRoot(mapId)) {
markMetaChanged();
}
}
/**
* Remove map by name.
*
* @param name the map name
*/
public void removeMap(String name) {
int id = getMapId(name);
if(id > 0) {
MVMap<?, ?> map = getMap(id);
if (map == null) {
map = openMap(name, MVStoreTool.getGenericMapBuilder());
}
removeMap(map);
}
}
/**
* Get the name of the given map.
*
* @param id the map id
* @return the name, or null if not found
*/
public String getMapName(int id) {
String m = meta.get(MVMap.getMapKey(id));
return m == null ? null : DataUtils.getMapName(m);
}
private int getMapId(String name) {
String m = meta.get(DataUtils.META_NAME + name);
return m == null ? -1 : DataUtils.parseHexInt(m);
}
public void populateInfo(BiConsumer<String, String> consumer) {
consumer.accept("info.UPDATE_FAILURE_PERCENT",
String.format(Locale.ENGLISH, "%.2f%%", 100 * getUpdateFailureRatio()));
consumer.accept("info.LEAF_RATIO", Integer.toString(getLeafRatio()));
if (fileStore != null) {
fileStore.populateInfo(consumer);
}
}
boolean handleException(Throwable ex) {
if (backgroundExceptionHandler != null) {
try {
backgroundExceptionHandler.uncaughtException(Thread.currentThread(), ex);
} catch(Throwable e) {
if (ex != e) { // OOME may be the same
ex.addSuppressed(e);
}
}
return true;
}
return false;
}
boolean isOpen() {
return state == STATE_OPEN;
}
/**
* Determine that store is open, or wait for it to be closed (by other thread)
* @return true if store is open, false otherwise
*/
public boolean isClosed() {
if (isOpen()) {
return false;
}
storeLock.lock();
try {
return state == STATE_CLOSED;
} finally {
storeLock.unlock();
}
}
private boolean isOpenOrStopping() {
return state <= STATE_STOPPING;
}
/**
* Set the maximum delay in milliseconds to auto-commit changes.
* <p>
* To disable auto-commit, set the value to 0. In this case, changes are
* only committed when explicitly calling commit.
* <p>
* The default is 1000, meaning all changes are committed after at most one
* second.
*
* @param millis the maximum delay
*/
public void setAutoCommitDelay(int millis) {
if (fileStore != null) {
fileStore.setAutoCommitDelay(millis);
}
}
/**
* Get the auto-commit delay.
*
* @return the delay in milliseconds, or 0 if auto-commit is disabled.
*/
public int getAutoCommitDelay() {
return fileStore == null ? 0 : fileStore.getAutoCommitDelay();
}
/**
* Get the maximum memory (in bytes) used for unsaved pages. If this number
* is exceeded, unsaved changes are stored to disk.
*
* @return the memory in bytes
*/
public int getAutoCommitMemory() {
return autoCommitMemory;
}
/**
* Get the estimated memory (in bytes) of unsaved data. If the value exceeds
* the auto-commit memory, the changes are committed.
* <p>
* The returned value is an estimation only.
*
* @return the memory in bytes
*/
public int getUnsavedMemory() {
return unsavedMemory;
}
/**
* Whether the store is read-only.
*
* @return true if it is
*/
public boolean isReadOnly() {
return fileStore != null && fileStore.isReadOnly();
}
private int getLeafRatio() {
return (int)(leafCount * 100 / Math.max(1, leafCount + nonLeafCount));
}
private double getUpdateFailureRatio() {
long updateCounter = this.updateCounter;
long updateAttemptCounter = this.updateAttemptCounter;
RootReference<?,?> rootReference = meta.getRoot();
updateCounter += rootReference.updateCounter;
updateAttemptCounter += rootReference.updateAttemptCounter;
for (MVMap<?, ?> map : maps.values()) {
RootReference<?,?> root = map.getRoot();
updateCounter += root.updateCounter;
updateAttemptCounter += root.updateAttemptCounter;
}
return updateAttemptCounter == 0 ? 0 : 1 - ((double)updateCounter / updateAttemptCounter);
}
/**
* Register opened operation (transaction).
* This would increment usage counter for the current version.
* This version (and all after it) should not be dropped until all
* transactions involved are closed and usage counter goes to zero.
* @return TxCounter to be decremented when operation finishes (transaction closed).
*/
public TxCounter registerVersionUsage() {
TxCounter txCounter;
while(true) {
txCounter = currentTxCounter;
if(txCounter.incrementAndGet() > 0) {
return txCounter;
}
// The only way for counter to be negative
// if it was retrieved right before onVersionChange()
// and now onVersionChange() is done.
// This version is eligible for reclamation now
// and should not be used here, so restore count
// not to upset accounting and try again with a new
// version (currentTxCounter should have changed).
assert txCounter != currentTxCounter : txCounter;
txCounter.decrementAndGet();
}
}
/**
* De-register (close) completed operation (transaction).
* This will decrement usage counter for the corresponding version.
* If counter reaches zero, that version (and all unused after it)
* can be dropped immediately.
*
* @param txCounter to be decremented, obtained from registerVersionUsage()
*/
public void deregisterVersionUsage(TxCounter txCounter) {
if(decrementVersionUsageCounter(txCounter)) {
if (storeLock.isHeldByCurrentThread()) {
dropUnusedVersions();
} else if (storeLock.tryLock()) {
try {
dropUnusedVersions();
} finally {
storeLock.unlock();
}
}
}
}
/**
* De-register (close) completed operation (transaction).
* This will decrement usage counter for the corresponding version.
*
* @param txCounter to be decremented, obtained from registerVersionUsage()
* @return true if counter reaches zero, which indicates that version is no longer in use, false otherwise.
*/
public boolean decrementVersionUsageCounter(TxCounter txCounter) {
return txCounter != null && txCounter.decrementAndGet() <= 0;
}
void onVersionChange(long version) {
metaChanged = false;
TxCounter txCounter = currentTxCounter;
assert txCounter.get() >= 0;
versions.add(txCounter);
currentTxCounter = new TxCounter(version);
txCounter.decrementAndGet();
dropUnusedVersions();
}
private void dropUnusedVersions() {
TxCounter txCounter;
while ((txCounter = versions.peek()) != null
&& txCounter.get() < 0) {
versions.poll();
}
long oldestVersionToKeep = (txCounter != null ? txCounter : currentTxCounter).version;
setOldestVersionToKeep(oldestVersionToKeep);
}
public void countNewPage(boolean leaf) {
if (leaf) {
++leafCount;
} else {
++nonLeafCount;
}
}
/**
* Class TxCounter is a simple data structure to hold version of the store
* along with the counter of open transactions,
* which are still operating on this version.
*/
public static final class TxCounter {
/**
* Version of a store, this TxCounter is related to
*/
public final long version;
/**
* Counter of outstanding operation on this version of a store
*/
private volatile int counter;
private static final AtomicIntegerFieldUpdater<TxCounter> counterUpdater =
AtomicIntegerFieldUpdater.newUpdater(TxCounter.class, "counter");
TxCounter(long version) {
this.version = version;
}
int get() {
return counter;
}
/**
* Increment and get the counter value.
*
* @return the new value
*/
int incrementAndGet() {
return counterUpdater.incrementAndGet(this);
}
/**
* Decrement and get the counter values.
*
* @return the new value
*/
int decrementAndGet() {
return counterUpdater.decrementAndGet(this);
}
@Override
public String toString() {
return "v=" + version + " / cnt=" + counter;
}
}
/**
* A builder for an MVStore.
*/
public static final class Builder {
private final HashMap<String, Object> config;
private Builder(HashMap<String, Object> config) {
this.config = config;
}
/**
* Creates new instance of MVStore.Builder.
*/
public Builder() {
config = new HashMap<>();
}
private Builder set(String key, Object value) {
config.put(key, value);
return this;
}
/**
* Disable auto-commit, by setting the auto-commit delay and auto-commit
* buffer size to 0.
*
* @return this
*/
public Builder autoCommitDisabled() {
// we have a separate config option so that
// no thread is started if the write delay is 0
// (if we only had a setter in the MVStore,
// the thread would need to be started in any case)
//set("autoCommitBufferSize", 0);
return set("autoCommitDelay", 0);
}
/**
* Set the size of the write buffer, in KB disk space (for file-based
* stores). Unless auto-commit is disabled, changes are automatically
* saved if there are more than this amount of changes.
* <p>
* The default is 1024 KB.
* <p>
* When the value is set to 0 or lower, data is not automatically
* stored.
*
* @param kb the write buffer size, in kilobytes
* @return this
*/
public Builder autoCommitBufferSize(int kb) {
return set("autoCommitBufferSize", kb);
}
/**
* Set the auto-compact target fill rate. If the average fill rate (the
* percentage of the storage space that contains active data) of the
* chunks is lower, then the chunks with a low fill rate are re-written.
* Also, if the percentage of empty space between chunks is higher than
* this value, then chunks at the end of the file are moved. Compaction
* stops if the target fill rate is reached.
* <p>
* The default value is 90 (90%). The value 0 disables auto-compacting.
* </p>
*
* @param percent the target fill rate
* @return this
*/
public Builder autoCompactFillRate(int percent) {
return set("autoCompactFillRate", percent);
}
/**
* Use the following file name. If the file does not exist, it is
* automatically created. The parent directory already must exist.
*
* @param fileName the file name
* @return this
*/
public Builder fileName(String fileName) {
return set("fileName", fileName);
}
/**
* Encrypt / decrypt the file using the given password. This method has
* no effect for in-memory stores. The password is passed as a
* char array so that it can be cleared as soon as possible. Please note
* there is still a small risk that password stays in memory (due to
* Java garbage collection). Also, the hashed encryption key is kept in
* memory as long as the file is open.
*
* @param password the password
* @return this
*/
public Builder encryptionKey(char[] password) {
return set("encryptionKey", password);
}
/**
* Open the file in read-only mode. In this case, a shared lock will be
* acquired to ensure the file is not concurrently opened in write mode.
* <p>
* If this option is not used, the file is locked exclusively.
* <p>
* Please note a store may only be opened once in every JVM (no matter
* whether it is opened in read-only or read-write mode), because each
* file may be locked only once in a process.
*
* @return this
*/
public Builder readOnly() {
return set("readOnly", 1);
}
/**
* Set the number of keys per page.
*
* @param keyCount the number of keys
* @return this
*/
public Builder keysPerPage(int keyCount) {
return set("keysPerPage", keyCount);
}
/**
* Open the file in recovery mode, where some errors may be ignored.
*
* @return this
*/
public Builder recoveryMode() {
return set("recoveryMode", 1);
}
/**
* Set the read cache size in MB. The default is 16 MB.
*
* @param mb the cache size in megabytes
* @return this
*/
public Builder cacheSize(int mb) {
return set("cacheSize", mb);
}
/**
* Set the read cache concurrency. The default is 16, meaning 16
* segments are used.
*
* @param concurrency the cache concurrency
* @return this
*/
public Builder cacheConcurrency(int concurrency) {
return set("cacheConcurrency", concurrency);
}
/**
* Compress data before writing using the LZF algorithm. This will save
* about 50% of the disk space, but will slow down read and write
* operations slightly.
* <p>
* This setting only affects writes; it is not necessary to enable
* compression when reading, even if compression was enabled when
* writing.
*
* @return this
*/
public Builder compress() {
return set("compress", 1);
}
/**
* Compress data before writing using the Deflate algorithm. This will
* save more disk space, but will slow down read and write operations
* quite a bit.
* <p>
* This setting only affects writes; it is not necessary to enable
* compression when reading, even if compression was enabled when
* writing.
*
* @return this
*/
public Builder compressHigh() {
return set("compress", 2);
}
/**
* Set the amount of memory a page should contain at most, in bytes,
* before it is split. The default is 16 KB for persistent stores and 4
* KB for in-memory stores. This is not a limit in the page size, as
* pages with one entry can get larger. It is just the point where pages
* that contain more than one entry are split.
*
* @param pageSplitSize the page size
* @return this
*/
public Builder pageSplitSize(int pageSplitSize) {
return set("pageSplitSize", pageSplitSize);
}
/**
* Set the listener to be used for exceptions that occur when writing in
* the background thread.
*
* @param exceptionHandler the handler
* @return this
*/
public Builder backgroundExceptionHandler(
Thread.UncaughtExceptionHandler exceptionHandler) {
return set("backgroundExceptionHandler", exceptionHandler);
}
/**
* Use the provided file store instead of the default one.
* <p>
* File stores passed in this way need to be open. They are not closed
* when closing the store.
* <p>
* Please note that any kind of store (including an off-heap store) is
* considered a "persistence", while an "in-memory store" means objects
* are not persisted and fully kept in the JVM heap.
*
* @param store the file store
* @return this
*/
public Builder fileStore(FileStore<?> store) {
return set("fileStore", store);
}
public Builder adoptFileStore(FileStore store) {
set("fileStoreIsAdopted", true);
return set("fileStore", store);
}
/**
* Open the store.
*
* @return the opened store
*/
public MVStore open() {
return new MVStore(config);
}
@Override
public String toString() {
return DataUtils.appendMap(new StringBuilder(), config).toString();
}
/**
* Read the configuration from a string.
*
* @param s the string representation
* @return the builder
*/
@SuppressWarnings({"unchecked", "rawtypes", "unused"})
public static Builder fromString(String s) {
// Cast from HashMap<String, String> to HashMap<String, Object> is safe
return new Builder((HashMap) DataUtils.parseMap(s));
}
}
}
| h2database/h2database | h2/src/main/org/h2/mvstore/MVStore.java |
45,334 | package com.mxgraph.online;
import java.util.Arrays;
/** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
* with RFC 2045.<br><br>
* On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
* on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
* compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
*
* On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
* about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
* arrays (< 30 bytes). If source/destination is a <code>String</code> this
* version is about three times as fast due to the fact that the Commons Codec result has to be recoded
* to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
*
* This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
* allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
* as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
* whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
* is quite low it probably does.<br><br>
*
* The encoder produces the same output as the Sun one except that the Sun's encoder appends
* a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
* length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
* Commons codec seem to always att a trailing line separator.<br><br>
*
* <b>Note!</b>
* The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
* thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
* format types. The methods not used can simply be commented out.<br><br>
*
* There is also a "fast" version of all decode methods that works the same way as the normal ones, but
* har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
* the input is known and it hasn't bee tampered with.<br><br>
*
* If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
*
* Licence (BSD):
* ==============
*
* Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* Neither the name of the MiG InfoCom AB nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* @version 2.2
* @author Mikael Grev
* Date: 2004-aug-02
* Time: 11:31:11
*/
public class mxBase64
{
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
private static final int[] IA = new int[256];
static
{
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
// ****************************************************************************************
// * char[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static char[] encodeToChar(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;)
{
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8
| (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2)
{
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0)
{
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10)
| (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(char[] sArr)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++)
// If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i]] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;)
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++)
{ // j only increased if a valid char was found.
int c = IA[sArr[s++]];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len)
{
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12
| IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19)
{
sIx += 2;
cc = 0;
}
}
if (d < len)
{
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * byte[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;)
{
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8
| (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2)
{
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0)
{
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10)
| (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++)
// If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i] & 0xff] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;)
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++)
{ // j only increased if a valid char was found.
int c = IA[sArr[s++] & 0xff];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len)
{
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12
| IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19)
{
sIx += 2;
cc = 0;
}
}
if (d < len)
{
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * String version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static String encodeToString(byte[] sArr, boolean lineSep)
{
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
/** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
* and without line separators.<br>
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
* @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(String str)
{
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++)
// If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
// Count '=' at end
int pad = 0;
for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
if (str.charAt(i) == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++)
{ // j only increased if a valid char was found.
int c = IA[str.charAt(s++)];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len)
{
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String s)
{
// Check special case
int sLen = s.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1
: 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;)
{
// Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12
| IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19)
{
sIx += 2;
cc = 0;
}
}
if (d < len)
{
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[s.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/mxBase64.java |
Subsets and Splits