index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/serviceworker/ServiceWorkerErrorMessage.java
package com.github.kklisura.cdt.protocol.v2023.types.serviceworker; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** ServiceWorker error message. */ public class ServiceWorkerErrorMessage { private String errorMessage; private String registrationId; private String versionId; private String sourceURL; private Integer lineNumber; private Integer columnNumber; public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getRegistrationId() { return registrationId; } public void setRegistrationId(String registrationId) { this.registrationId = registrationId; } public String getVersionId() { return versionId; } public void setVersionId(String versionId) { this.versionId = versionId; } public String getSourceURL() { return sourceURL; } public void setSourceURL(String sourceURL) { this.sourceURL = sourceURL; } public Integer getLineNumber() { return lineNumber; } public void setLineNumber(Integer lineNumber) { this.lineNumber = lineNumber; } public Integer getColumnNumber() { return columnNumber; } public void setColumnNumber(Integer columnNumber) { this.columnNumber = columnNumber; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/serviceworker/ServiceWorkerRegistration.java
package com.github.kklisura.cdt.protocol.v2023.types.serviceworker; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** ServiceWorker registration. */ public class ServiceWorkerRegistration { private String registrationId; private String scopeURL; private Boolean isDeleted; public String getRegistrationId() { return registrationId; } public void setRegistrationId(String registrationId) { this.registrationId = registrationId; } public String getScopeURL() { return scopeURL; } public void setScopeURL(String scopeURL) { this.scopeURL = scopeURL; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/serviceworker/ServiceWorkerVersion.java
package com.github.kklisura.cdt.protocol.v2023.types.serviceworker; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; /** ServiceWorker version. */ public class ServiceWorkerVersion { private String versionId; private String registrationId; private String scriptURL; private ServiceWorkerVersionRunningStatus runningStatus; private ServiceWorkerVersionStatus status; @Optional private Double scriptLastModified; @Optional private Double scriptResponseTime; @Optional private List<String> controlledClients; @Optional private String targetId; public String getVersionId() { return versionId; } public void setVersionId(String versionId) { this.versionId = versionId; } public String getRegistrationId() { return registrationId; } public void setRegistrationId(String registrationId) { this.registrationId = registrationId; } public String getScriptURL() { return scriptURL; } public void setScriptURL(String scriptURL) { this.scriptURL = scriptURL; } public ServiceWorkerVersionRunningStatus getRunningStatus() { return runningStatus; } public void setRunningStatus(ServiceWorkerVersionRunningStatus runningStatus) { this.runningStatus = runningStatus; } public ServiceWorkerVersionStatus getStatus() { return status; } public void setStatus(ServiceWorkerVersionStatus status) { this.status = status; } /** The Last-Modified header value of the main script. */ public Double getScriptLastModified() { return scriptLastModified; } /** The Last-Modified header value of the main script. */ public void setScriptLastModified(Double scriptLastModified) { this.scriptLastModified = scriptLastModified; } /** * The time at which the response headers of the main script were received from the server. For * cached script it is the last time the cache entry was validated. */ public Double getScriptResponseTime() { return scriptResponseTime; } /** * The time at which the response headers of the main script were received from the server. For * cached script it is the last time the cache entry was validated. */ public void setScriptResponseTime(Double scriptResponseTime) { this.scriptResponseTime = scriptResponseTime; } public List<String> getControlledClients() { return controlledClients; } public void setControlledClients(List<String> controlledClients) { this.controlledClients = controlledClients; } public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/serviceworker/ServiceWorkerVersionRunningStatus.java
package com.github.kklisura.cdt.protocol.v2023.types.serviceworker; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum ServiceWorkerVersionRunningStatus { @JsonProperty("stopped") STOPPED, @JsonProperty("starting") STARTING, @JsonProperty("running") RUNNING, @JsonProperty("stopping") STOPPING }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/serviceworker/ServiceWorkerVersionStatus.java
package com.github.kklisura.cdt.protocol.v2023.types.serviceworker; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum ServiceWorkerVersionStatus { @JsonProperty("new") NEW, @JsonProperty("installing") INSTALLING, @JsonProperty("installed") INSTALLED, @JsonProperty("activating") ACTIVATING, @JsonProperty("activated") ACTIVATED, @JsonProperty("redundant") REDUNDANT }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/AttributionReportingAggregationKeysEntry.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; @Experimental public class AttributionReportingAggregationKeysEntry { private String key; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/AttributionReportingFilterDataEntry.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; import java.util.List; @Experimental public class AttributionReportingFilterDataEntry { private String key; private List<String> values; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/AttributionReportingSourceRegistration.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; @Experimental public class AttributionReportingSourceRegistration { private Double time; @Optional private Integer expiry; @Optional private Integer eventReportWindow; @Optional private Integer aggregatableReportWindow; private AttributionReportingSourceType type; private String sourceOrigin; private String reportingOrigin; private List<String> destinationSites; private String eventId; private String priority; private List<AttributionReportingFilterDataEntry> filterData; private List<AttributionReportingAggregationKeysEntry> aggregationKeys; @Optional private String debugKey; public Double getTime() { return time; } public void setTime(Double time) { this.time = time; } /** duration in seconds */ public Integer getExpiry() { return expiry; } /** duration in seconds */ public void setExpiry(Integer expiry) { this.expiry = expiry; } /** duration in seconds */ public Integer getEventReportWindow() { return eventReportWindow; } /** duration in seconds */ public void setEventReportWindow(Integer eventReportWindow) { this.eventReportWindow = eventReportWindow; } /** duration in seconds */ public Integer getAggregatableReportWindow() { return aggregatableReportWindow; } /** duration in seconds */ public void setAggregatableReportWindow(Integer aggregatableReportWindow) { this.aggregatableReportWindow = aggregatableReportWindow; } public AttributionReportingSourceType getType() { return type; } public void setType(AttributionReportingSourceType type) { this.type = type; } public String getSourceOrigin() { return sourceOrigin; } public void setSourceOrigin(String sourceOrigin) { this.sourceOrigin = sourceOrigin; } public String getReportingOrigin() { return reportingOrigin; } public void setReportingOrigin(String reportingOrigin) { this.reportingOrigin = reportingOrigin; } public List<String> getDestinationSites() { return destinationSites; } public void setDestinationSites(List<String> destinationSites) { this.destinationSites = destinationSites; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public List<AttributionReportingFilterDataEntry> getFilterData() { return filterData; } public void setFilterData(List<AttributionReportingFilterDataEntry> filterData) { this.filterData = filterData; } public List<AttributionReportingAggregationKeysEntry> getAggregationKeys() { return aggregationKeys; } public void setAggregationKeys(List<AttributionReportingAggregationKeysEntry> aggregationKeys) { this.aggregationKeys = aggregationKeys; } public String getDebugKey() { return debugKey; } public void setDebugKey(String debugKey) { this.debugKey = debugKey; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/AttributionReportingSourceRegistrationResult.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum AttributionReportingSourceRegistrationResult { @JsonProperty("success") SUCCESS, @JsonProperty("internalError") INTERNAL_ERROR, @JsonProperty("insufficientSourceCapacity") INSUFFICIENT_SOURCE_CAPACITY, @JsonProperty("insufficientUniqueDestinationCapacity") INSUFFICIENT_UNIQUE_DESTINATION_CAPACITY, @JsonProperty("excessiveReportingOrigins") EXCESSIVE_REPORTING_ORIGINS, @JsonProperty("prohibitedByBrowserPolicy") PROHIBITED_BY_BROWSER_POLICY, @JsonProperty("successNoised") SUCCESS_NOISED, @JsonProperty("destinationReportingLimitReached") DESTINATION_REPORTING_LIMIT_REACHED, @JsonProperty("destinationGlobalLimitReached") DESTINATION_GLOBAL_LIMIT_REACHED, @JsonProperty("destinationBothLimitsReached") DESTINATION_BOTH_LIMITS_REACHED, @JsonProperty("reportingOriginsPerSiteLimitReached") REPORTING_ORIGINS_PER_SITE_LIMIT_REACHED }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/AttributionReportingSourceType.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum AttributionReportingSourceType { @JsonProperty("navigation") NAVIGATION, @JsonProperty("event") EVENT }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/InterestGroupAccessType.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of interest group access types. */ public enum InterestGroupAccessType { @JsonProperty("join") JOIN, @JsonProperty("leave") LEAVE, @JsonProperty("update") UPDATE, @JsonProperty("loaded") LOADED, @JsonProperty("bid") BID, @JsonProperty("win") WIN }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/InterestGroupAd.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; /** Ad advertising element inside an interest group. */ public class InterestGroupAd { private String renderUrl; @Optional private String metadata; public String getRenderUrl() { return renderUrl; } public void setRenderUrl(String renderUrl) { this.renderUrl = renderUrl; } public String getMetadata() { return metadata; } public void setMetadata(String metadata) { this.metadata = metadata; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/InterestGroupDetails.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; /** The full details of an interest group. */ public class InterestGroupDetails { private String ownerOrigin; private String name; private Double expirationTime; private String joiningOrigin; @Optional private String biddingUrl; @Optional private String biddingWasmHelperUrl; @Optional private String updateUrl; @Optional private String trustedBiddingSignalsUrl; private List<String> trustedBiddingSignalsKeys; @Optional private String userBiddingSignals; private List<InterestGroupAd> ads; private List<InterestGroupAd> adComponents; public String getOwnerOrigin() { return ownerOrigin; } public void setOwnerOrigin(String ownerOrigin) { this.ownerOrigin = ownerOrigin; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getExpirationTime() { return expirationTime; } public void setExpirationTime(Double expirationTime) { this.expirationTime = expirationTime; } public String getJoiningOrigin() { return joiningOrigin; } public void setJoiningOrigin(String joiningOrigin) { this.joiningOrigin = joiningOrigin; } public String getBiddingUrl() { return biddingUrl; } public void setBiddingUrl(String biddingUrl) { this.biddingUrl = biddingUrl; } public String getBiddingWasmHelperUrl() { return biddingWasmHelperUrl; } public void setBiddingWasmHelperUrl(String biddingWasmHelperUrl) { this.biddingWasmHelperUrl = biddingWasmHelperUrl; } public String getUpdateUrl() { return updateUrl; } public void setUpdateUrl(String updateUrl) { this.updateUrl = updateUrl; } public String getTrustedBiddingSignalsUrl() { return trustedBiddingSignalsUrl; } public void setTrustedBiddingSignalsUrl(String trustedBiddingSignalsUrl) { this.trustedBiddingSignalsUrl = trustedBiddingSignalsUrl; } public List<String> getTrustedBiddingSignalsKeys() { return trustedBiddingSignalsKeys; } public void setTrustedBiddingSignalsKeys(List<String> trustedBiddingSignalsKeys) { this.trustedBiddingSignalsKeys = trustedBiddingSignalsKeys; } public String getUserBiddingSignals() { return userBiddingSignals; } public void setUserBiddingSignals(String userBiddingSignals) { this.userBiddingSignals = userBiddingSignals; } public List<InterestGroupAd> getAds() { return ads; } public void setAds(List<InterestGroupAd> ads) { this.ads = ads; } public List<InterestGroupAd> getAdComponents() { return adComponents; } public void setAdComponents(List<InterestGroupAd> adComponents) { this.adComponents = adComponents; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageAccessParams.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; /** * Bundles the parameters for shared storage access events whose presence/absence can vary according * to SharedStorageAccessType. */ public class SharedStorageAccessParams { @Optional private String scriptSourceUrl; @Optional private String operationName; @Optional private String serializedData; @Optional private List<SharedStorageUrlWithMetadata> urlsWithMetadata; @Optional private String key; @Optional private String value; @Optional private Boolean ignoreIfPresent; /** Spec of the module script URL. Present only for SharedStorageAccessType.documentAddModule. */ public String getScriptSourceUrl() { return scriptSourceUrl; } /** Spec of the module script URL. Present only for SharedStorageAccessType.documentAddModule. */ public void setScriptSourceUrl(String scriptSourceUrl) { this.scriptSourceUrl = scriptSourceUrl; } /** * Name of the registered operation to be run. Present only for * SharedStorageAccessType.documentRun and SharedStorageAccessType.documentSelectURL. */ public String getOperationName() { return operationName; } /** * Name of the registered operation to be run. Present only for * SharedStorageAccessType.documentRun and SharedStorageAccessType.documentSelectURL. */ public void setOperationName(String operationName) { this.operationName = operationName; } /** * The operation's serialized data in bytes (converted to a string). Present only for * SharedStorageAccessType.documentRun and SharedStorageAccessType.documentSelectURL. */ public String getSerializedData() { return serializedData; } /** * The operation's serialized data in bytes (converted to a string). Present only for * SharedStorageAccessType.documentRun and SharedStorageAccessType.documentSelectURL. */ public void setSerializedData(String serializedData) { this.serializedData = serializedData; } /** * Array of candidate URLs' specs, along with any associated metadata. Present only for * SharedStorageAccessType.documentSelectURL. */ public List<SharedStorageUrlWithMetadata> getUrlsWithMetadata() { return urlsWithMetadata; } /** * Array of candidate URLs' specs, along with any associated metadata. Present only for * SharedStorageAccessType.documentSelectURL. */ public void setUrlsWithMetadata(List<SharedStorageUrlWithMetadata> urlsWithMetadata) { this.urlsWithMetadata = urlsWithMetadata; } /** * Key for a specific entry in an origin's shared storage. Present only for * SharedStorageAccessType.documentSet, SharedStorageAccessType.documentAppend, * SharedStorageAccessType.documentDelete, SharedStorageAccessType.workletSet, * SharedStorageAccessType.workletAppend, SharedStorageAccessType.workletDelete, and * SharedStorageAccessType.workletGet. */ public String getKey() { return key; } /** * Key for a specific entry in an origin's shared storage. Present only for * SharedStorageAccessType.documentSet, SharedStorageAccessType.documentAppend, * SharedStorageAccessType.documentDelete, SharedStorageAccessType.workletSet, * SharedStorageAccessType.workletAppend, SharedStorageAccessType.workletDelete, and * SharedStorageAccessType.workletGet. */ public void setKey(String key) { this.key = key; } /** * Value for a specific entry in an origin's shared storage. Present only for * SharedStorageAccessType.documentSet, SharedStorageAccessType.documentAppend, * SharedStorageAccessType.workletSet, and SharedStorageAccessType.workletAppend. */ public String getValue() { return value; } /** * Value for a specific entry in an origin's shared storage. Present only for * SharedStorageAccessType.documentSet, SharedStorageAccessType.documentAppend, * SharedStorageAccessType.workletSet, and SharedStorageAccessType.workletAppend. */ public void setValue(String value) { this.value = value; } /** * Whether or not to set an entry for a key if that key is already present. Present only for * SharedStorageAccessType.documentSet and SharedStorageAccessType.workletSet. */ public Boolean getIgnoreIfPresent() { return ignoreIfPresent; } /** * Whether or not to set an entry for a key if that key is already present. Present only for * SharedStorageAccessType.documentSet and SharedStorageAccessType.workletSet. */ public void setIgnoreIfPresent(Boolean ignoreIfPresent) { this.ignoreIfPresent = ignoreIfPresent; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageAccessType.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of shared storage access types. */ public enum SharedStorageAccessType { @JsonProperty("documentAddModule") DOCUMENT_ADD_MODULE, @JsonProperty("documentSelectURL") DOCUMENT_SELECT_URL, @JsonProperty("documentRun") DOCUMENT_RUN, @JsonProperty("documentSet") DOCUMENT_SET, @JsonProperty("documentAppend") DOCUMENT_APPEND, @JsonProperty("documentDelete") DOCUMENT_DELETE, @JsonProperty("documentClear") DOCUMENT_CLEAR, @JsonProperty("workletSet") WORKLET_SET, @JsonProperty("workletAppend") WORKLET_APPEND, @JsonProperty("workletDelete") WORKLET_DELETE, @JsonProperty("workletClear") WORKLET_CLEAR, @JsonProperty("workletGet") WORKLET_GET, @JsonProperty("workletKeys") WORKLET_KEYS, @JsonProperty("workletEntries") WORKLET_ENTRIES, @JsonProperty("workletLength") WORKLET_LENGTH, @JsonProperty("workletRemainingBudget") WORKLET_REMAINING_BUDGET }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageEntry.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Struct for a single key-value pair in an origin's shared storage. */ public class SharedStorageEntry { private String key; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageMetadata.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Details for an origin's shared storage. */ public class SharedStorageMetadata { private Double creationTime; private Integer length; private Double remainingBudget; public Double getCreationTime() { return creationTime; } public void setCreationTime(Double creationTime) { this.creationTime = creationTime; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Double getRemainingBudget() { return remainingBudget; } public void setRemainingBudget(Double remainingBudget) { this.remainingBudget = remainingBudget; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageReportingMetadata.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Pair of reporting metadata details for a candidate URL for `selectURL()`. */ public class SharedStorageReportingMetadata { private String eventType; private String reportingUrl; public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getReportingUrl() { return reportingUrl; } public void setReportingUrl(String reportingUrl) { this.reportingUrl = reportingUrl; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/SharedStorageUrlWithMetadata.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import java.util.List; /** Bundles a candidate URL with its reporting metadata. */ public class SharedStorageUrlWithMetadata { private String url; private List<SharedStorageReportingMetadata> reportingMetadata; /** Spec of candidate URL. */ public String getUrl() { return url; } /** Spec of candidate URL. */ public void setUrl(String url) { this.url = url; } /** Any associated reporting metadata. */ public List<SharedStorageReportingMetadata> getReportingMetadata() { return reportingMetadata; } /** Any associated reporting metadata. */ public void setReportingMetadata(List<SharedStorageReportingMetadata> reportingMetadata) { this.reportingMetadata = reportingMetadata; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/StorageBucket.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; public class StorageBucket { private String storageKey; @Optional private String name; public String getStorageKey() { return storageKey; } public void setStorageKey(String storageKey) { this.storageKey = storageKey; } /** If not specified, it is the default bucket of the storageKey. */ public String getName() { return name; } /** If not specified, it is the default bucket of the storageKey. */ public void setName(String name) { this.name = name; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/StorageBucketInfo.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ public class StorageBucketInfo { private StorageBucket bucket; private String id; private Double expiration; private Double quota; private Boolean persistent; private StorageBucketsDurability durability; public StorageBucket getBucket() { return bucket; } public void setBucket(StorageBucket bucket) { this.bucket = bucket; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Double getExpiration() { return expiration; } public void setExpiration(Double expiration) { this.expiration = expiration; } /** Storage quota (bytes). */ public Double getQuota() { return quota; } /** Storage quota (bytes). */ public void setQuota(Double quota) { this.quota = quota; } public Boolean getPersistent() { return persistent; } public void setPersistent(Boolean persistent) { this.persistent = persistent; } public StorageBucketsDurability getDurability() { return durability; } public void setDurability(StorageBucketsDurability durability) { this.durability = durability; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/StorageBucketsDurability.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum StorageBucketsDurability { @JsonProperty("relaxed") RELAXED, @JsonProperty("strict") STRICT }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/StorageType.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of possible storage types. */ public enum StorageType { @JsonProperty("appcache") APPCACHE, @JsonProperty("cookies") COOKIES, @JsonProperty("file_systems") FILE_SYSTEMS, @JsonProperty("indexeddb") INDEXEDDB, @JsonProperty("local_storage") LOCAL_STORAGE, @JsonProperty("shader_cache") SHADER_CACHE, @JsonProperty("websql") WEBSQL, @JsonProperty("service_workers") SERVICE_WORKERS, @JsonProperty("cache_storage") CACHE_STORAGE, @JsonProperty("interest_groups") INTEREST_GROUPS, @JsonProperty("shared_storage") SHARED_STORAGE, @JsonProperty("storage_buckets") STORAGE_BUCKETS, @JsonProperty("all") ALL, @JsonProperty("other") OTHER }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/TrustTokens.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; /** * Pair of issuer origin and number of available (signed, but not used) Trust Tokens from that * issuer. */ @Experimental public class TrustTokens { private String issuerOrigin; private Double count; public String getIssuerOrigin() { return issuerOrigin; } public void setIssuerOrigin(String issuerOrigin) { this.issuerOrigin = issuerOrigin; } public Double getCount() { return count; } public void setCount(Double count) { this.count = count; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/UsageAndQuota.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import java.util.List; public class UsageAndQuota { private Double usage; private Double quota; private Boolean overrideActive; private List<UsageForType> usageBreakdown; /** Storage usage (bytes). */ public Double getUsage() { return usage; } /** Storage usage (bytes). */ public void setUsage(Double usage) { this.usage = usage; } /** Storage quota (bytes). */ public Double getQuota() { return quota; } /** Storage quota (bytes). */ public void setQuota(Double quota) { this.quota = quota; } /** Whether or not the origin has an active storage quota override */ public Boolean getOverrideActive() { return overrideActive; } /** Whether or not the origin has an active storage quota override */ public void setOverrideActive(Boolean overrideActive) { this.overrideActive = overrideActive; } /** Storage usage per type (bytes). */ public List<UsageForType> getUsageBreakdown() { return usageBreakdown; } /** Storage usage per type (bytes). */ public void setUsageBreakdown(List<UsageForType> usageBreakdown) { this.usageBreakdown = usageBreakdown; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/storage/UsageForType.java
package com.github.kklisura.cdt.protocol.v2023.types.storage; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Usage for a storage type. */ public class UsageForType { private StorageType storageType; private Double usage; /** Name of storage type. */ public StorageType getStorageType() { return storageType; } /** Name of storage type. */ public void setStorageType(StorageType storageType) { this.storageType = storageType; } /** Storage usage (bytes). */ public Double getUsage() { return usage; } /** Storage usage (bytes). */ public void setUsage(Double usage) { this.usage = usage; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/GPUDevice.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; /** Describes a single graphics processor (GPU). */ public class GPUDevice { private Double vendorId; private Double deviceId; @Optional private Double subSysId; @Optional private Double revision; private String vendorString; private String deviceString; private String driverVendor; private String driverVersion; /** PCI ID of the GPU vendor, if available; 0 otherwise. */ public Double getVendorId() { return vendorId; } /** PCI ID of the GPU vendor, if available; 0 otherwise. */ public void setVendorId(Double vendorId) { this.vendorId = vendorId; } /** PCI ID of the GPU device, if available; 0 otherwise. */ public Double getDeviceId() { return deviceId; } /** PCI ID of the GPU device, if available; 0 otherwise. */ public void setDeviceId(Double deviceId) { this.deviceId = deviceId; } /** Sub sys ID of the GPU, only available on Windows. */ public Double getSubSysId() { return subSysId; } /** Sub sys ID of the GPU, only available on Windows. */ public void setSubSysId(Double subSysId) { this.subSysId = subSysId; } /** Revision of the GPU, only available on Windows. */ public Double getRevision() { return revision; } /** Revision of the GPU, only available on Windows. */ public void setRevision(Double revision) { this.revision = revision; } /** String description of the GPU vendor, if the PCI ID is not available. */ public String getVendorString() { return vendorString; } /** String description of the GPU vendor, if the PCI ID is not available. */ public void setVendorString(String vendorString) { this.vendorString = vendorString; } /** String description of the GPU device, if the PCI ID is not available. */ public String getDeviceString() { return deviceString; } /** String description of the GPU device, if the PCI ID is not available. */ public void setDeviceString(String deviceString) { this.deviceString = deviceString; } /** String description of the GPU driver vendor. */ public String getDriverVendor() { return driverVendor; } /** String description of the GPU driver vendor. */ public void setDriverVendor(String driverVendor) { this.driverVendor = driverVendor; } /** String description of the GPU driver version. */ public String getDriverVersion() { return driverVersion; } /** String description of the GPU driver version. */ public void setDriverVersion(String driverVersion) { this.driverVersion = driverVersion; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/GPUInfo.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; import java.util.Map; /** Provides information about the GPU(s) on the system. */ public class GPUInfo { private List<GPUDevice> devices; @Optional private Map<String, Object> auxAttributes; @Optional private Map<String, Object> featureStatus; private List<String> driverBugWorkarounds; private List<VideoDecodeAcceleratorCapability> videoDecoding; private List<VideoEncodeAcceleratorCapability> videoEncoding; private List<ImageDecodeAcceleratorCapability> imageDecoding; /** The graphics devices on the system. Element 0 is the primary GPU. */ public List<GPUDevice> getDevices() { return devices; } /** The graphics devices on the system. Element 0 is the primary GPU. */ public void setDevices(List<GPUDevice> devices) { this.devices = devices; } /** An optional dictionary of additional GPU related attributes. */ public Map<String, Object> getAuxAttributes() { return auxAttributes; } /** An optional dictionary of additional GPU related attributes. */ public void setAuxAttributes(Map<String, Object> auxAttributes) { this.auxAttributes = auxAttributes; } /** An optional dictionary of graphics features and their status. */ public Map<String, Object> getFeatureStatus() { return featureStatus; } /** An optional dictionary of graphics features and their status. */ public void setFeatureStatus(Map<String, Object> featureStatus) { this.featureStatus = featureStatus; } /** An optional array of GPU driver bug workarounds. */ public List<String> getDriverBugWorkarounds() { return driverBugWorkarounds; } /** An optional array of GPU driver bug workarounds. */ public void setDriverBugWorkarounds(List<String> driverBugWorkarounds) { this.driverBugWorkarounds = driverBugWorkarounds; } /** Supported accelerated video decoding capabilities. */ public List<VideoDecodeAcceleratorCapability> getVideoDecoding() { return videoDecoding; } /** Supported accelerated video decoding capabilities. */ public void setVideoDecoding(List<VideoDecodeAcceleratorCapability> videoDecoding) { this.videoDecoding = videoDecoding; } /** Supported accelerated video encoding capabilities. */ public List<VideoEncodeAcceleratorCapability> getVideoEncoding() { return videoEncoding; } /** Supported accelerated video encoding capabilities. */ public void setVideoEncoding(List<VideoEncodeAcceleratorCapability> videoEncoding) { this.videoEncoding = videoEncoding; } /** Supported accelerated image decoding capabilities. */ public List<ImageDecodeAcceleratorCapability> getImageDecoding() { return imageDecoding; } /** Supported accelerated image decoding capabilities. */ public void setImageDecoding(List<ImageDecodeAcceleratorCapability> imageDecoding) { this.imageDecoding = imageDecoding; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/ImageDecodeAcceleratorCapability.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import java.util.List; /** * Describes a supported image decoding profile with its associated minimum and maximum resolutions * and subsampling. */ public class ImageDecodeAcceleratorCapability { private ImageType imageType; private Size maxDimensions; private Size minDimensions; private List<SubsamplingFormat> subsamplings; /** Image coded, e.g. Jpeg. */ public ImageType getImageType() { return imageType; } /** Image coded, e.g. Jpeg. */ public void setImageType(ImageType imageType) { this.imageType = imageType; } /** Maximum supported dimensions of the image in pixels. */ public Size getMaxDimensions() { return maxDimensions; } /** Maximum supported dimensions of the image in pixels. */ public void setMaxDimensions(Size maxDimensions) { this.maxDimensions = maxDimensions; } /** Minimum supported dimensions of the image in pixels. */ public Size getMinDimensions() { return minDimensions; } /** Minimum supported dimensions of the image in pixels. */ public void setMinDimensions(Size minDimensions) { this.minDimensions = minDimensions; } /** Optional array of supported subsampling formats, e.g. 4:2:0, if known. */ public List<SubsamplingFormat> getSubsamplings() { return subsamplings; } /** Optional array of supported subsampling formats, e.g. 4:2:0, if known. */ public void setSubsamplings(List<SubsamplingFormat> subsamplings) { this.subsamplings = subsamplings; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/ImageType.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Image format of a given image. */ public enum ImageType { @JsonProperty("jpeg") JPEG, @JsonProperty("webp") WEBP, @JsonProperty("unknown") UNKNOWN }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/Info.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ public class Info { private GPUInfo gpu; private String modelName; private String modelVersion; private String commandLine; /** Information about the GPUs on the system. */ public GPUInfo getGpu() { return gpu; } /** Information about the GPUs on the system. */ public void setGpu(GPUInfo gpu) { this.gpu = gpu; } /** * A platform-dependent description of the model of the machine. On Mac OS, this is, for example, * 'MacBookPro'. Will be the empty string if not supported. */ public String getModelName() { return modelName; } /** * A platform-dependent description of the model of the machine. On Mac OS, this is, for example, * 'MacBookPro'. Will be the empty string if not supported. */ public void setModelName(String modelName) { this.modelName = modelName; } /** * A platform-dependent description of the version of the machine. On Mac OS, this is, for * example, '10.1'. Will be the empty string if not supported. */ public String getModelVersion() { return modelVersion; } /** * A platform-dependent description of the version of the machine. On Mac OS, this is, for * example, '10.1'. Will be the empty string if not supported. */ public void setModelVersion(String modelVersion) { this.modelVersion = modelVersion; } /** * The command line string used to launch the browser. Will be the empty string if not supported. */ public String getCommandLine() { return commandLine; } /** * The command line string used to launch the browser. Will be the empty string if not supported. */ public void setCommandLine(String commandLine) { this.commandLine = commandLine; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/ProcessInfo.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Represents process info. */ public class ProcessInfo { private String type; private Integer id; private Double cpuTime; /** Specifies process type. */ public String getType() { return type; } /** Specifies process type. */ public void setType(String type) { this.type = type; } /** Specifies process id. */ public Integer getId() { return id; } /** Specifies process id. */ public void setId(Integer id) { this.id = id; } /** * Specifies cumulative CPU usage in seconds across all threads of the process since the process * start. */ public Double getCpuTime() { return cpuTime; } /** * Specifies cumulative CPU usage in seconds across all threads of the process since the process * start. */ public void setCpuTime(Double cpuTime) { this.cpuTime = cpuTime; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/Size.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Describes the width and height dimensions of an entity. */ public class Size { private Integer width; private Integer height; /** Width in pixels. */ public Integer getWidth() { return width; } /** Width in pixels. */ public void setWidth(Integer width) { this.width = width; } /** Height in pixels. */ public Integer getHeight() { return height; } /** Height in pixels. */ public void setHeight(Integer height) { this.height = height; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/SubsamplingFormat.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** YUV subsampling type of the pixels of a given image. */ public enum SubsamplingFormat { @JsonProperty("yuv420") YUV_420, @JsonProperty("yuv422") YUV_422, @JsonProperty("yuv444") YUV_444 }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/VideoDecodeAcceleratorCapability.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** * Describes a supported video decoding profile with its associated minimum and maximum resolutions. */ public class VideoDecodeAcceleratorCapability { private String profile; private Size maxResolution; private Size minResolution; /** Video codec profile that is supported, e.g. VP9 Profile 2. */ public String getProfile() { return profile; } /** Video codec profile that is supported, e.g. VP9 Profile 2. */ public void setProfile(String profile) { this.profile = profile; } /** Maximum video dimensions in pixels supported for this |profile|. */ public Size getMaxResolution() { return maxResolution; } /** Maximum video dimensions in pixels supported for this |profile|. */ public void setMaxResolution(Size maxResolution) { this.maxResolution = maxResolution; } /** Minimum video dimensions in pixels supported for this |profile|. */ public Size getMinResolution() { return minResolution; } /** Minimum video dimensions in pixels supported for this |profile|. */ public void setMinResolution(Size minResolution) { this.minResolution = minResolution; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/systeminfo/VideoEncodeAcceleratorCapability.java
package com.github.kklisura.cdt.protocol.v2023.types.systeminfo; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** * Describes a supported video encoding profile with its associated maximum resolution and maximum * framerate. */ public class VideoEncodeAcceleratorCapability { private String profile; private Size maxResolution; private Integer maxFramerateNumerator; private Integer maxFramerateDenominator; /** Video codec profile that is supported, e.g H264 Main. */ public String getProfile() { return profile; } /** Video codec profile that is supported, e.g H264 Main. */ public void setProfile(String profile) { this.profile = profile; } /** Maximum video dimensions in pixels supported for this |profile|. */ public Size getMaxResolution() { return maxResolution; } /** Maximum video dimensions in pixels supported for this |profile|. */ public void setMaxResolution(Size maxResolution) { this.maxResolution = maxResolution; } /** * Maximum encoding framerate in frames per second supported for this |profile|, as fraction's * numerator and denominator, e.g. 24/1 fps, 24000/1001 fps, etc. */ public Integer getMaxFramerateNumerator() { return maxFramerateNumerator; } /** * Maximum encoding framerate in frames per second supported for this |profile|, as fraction's * numerator and denominator, e.g. 24/1 fps, 24000/1001 fps, etc. */ public void setMaxFramerateNumerator(Integer maxFramerateNumerator) { this.maxFramerateNumerator = maxFramerateNumerator; } public Integer getMaxFramerateDenominator() { return maxFramerateDenominator; } public void setMaxFramerateDenominator(Integer maxFramerateDenominator) { this.maxFramerateDenominator = maxFramerateDenominator; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/target/FilterEntry.java
package com.github.kklisura.cdt.protocol.v2023.types.target; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; /** A filter used by target query/discovery/auto-attach operations. */ @Experimental public class FilterEntry { @Optional private Boolean exclude; @Optional private String type; /** If set, causes exclusion of mathcing targets from the list. */ public Boolean getExclude() { return exclude; } /** If set, causes exclusion of mathcing targets from the list. */ public void setExclude(Boolean exclude) { this.exclude = exclude; } /** If not present, matches any type. */ public String getType() { return type; } /** If not present, matches any type. */ public void setType(String type) { this.type = type; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/target/RemoteLocation.java
package com.github.kklisura.cdt.protocol.v2023.types.target; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; @Experimental public class RemoteLocation { private String host; private Integer port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/target/TargetInfo.java
package com.github.kklisura.cdt.protocol.v2023.types.target; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental; import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; public class TargetInfo { private String targetId; private String type; private String title; private String url; private Boolean attached; @Optional private String openerId; @Experimental private Boolean canAccessOpener; @Experimental @Optional private String openerFrameId; @Experimental @Optional private String browserContextId; @Experimental @Optional private String subtype; public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } /** Whether the target has an attached client. */ public Boolean getAttached() { return attached; } /** Whether the target has an attached client. */ public void setAttached(Boolean attached) { this.attached = attached; } /** Opener target Id */ public String getOpenerId() { return openerId; } /** Opener target Id */ public void setOpenerId(String openerId) { this.openerId = openerId; } /** Whether the target has access to the originating window. */ public Boolean getCanAccessOpener() { return canAccessOpener; } /** Whether the target has access to the originating window. */ public void setCanAccessOpener(Boolean canAccessOpener) { this.canAccessOpener = canAccessOpener; } /** Frame id of originating window (is only set if target has an opener). */ public String getOpenerFrameId() { return openerFrameId; } /** Frame id of originating window (is only set if target has an opener). */ public void setOpenerFrameId(String openerFrameId) { this.openerFrameId = openerFrameId; } public String getBrowserContextId() { return browserContextId; } public void setBrowserContextId(String browserContextId) { this.browserContextId = browserContextId; } /** * Provides additional details for specific target types. For example, for the type of "page", * this may be set to "portal" or "prerender". */ public String getSubtype() { return subtype; } /** * Provides additional details for specific target types. For example, for the type of "page", * this may be set to "portal" or "prerender". */ public void setSubtype(String subtype) { this.subtype = subtype; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/MemoryDumpLevelOfDetail.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** * Details exposed when memory request explicitly declared. Keep consistent with * memory_dump_request_args.h and memory_instrumentation.mojom */ public enum MemoryDumpLevelOfDetail { @JsonProperty("background") BACKGROUND, @JsonProperty("light") LIGHT, @JsonProperty("detailed") DETAILED }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/RequestMemoryDump.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ public class RequestMemoryDump { private String dumpGuid; private Boolean success; /** GUID of the resulting global memory dump. */ public String getDumpGuid() { return dumpGuid; } /** GUID of the resulting global memory dump. */ public void setDumpGuid(String dumpGuid) { this.dumpGuid = dumpGuid; } /** True iff the global memory dump succeeded. */ public Boolean getSuccess() { return success; } /** True iff the global memory dump succeeded. */ public void setSuccess(Boolean success) { this.success = success; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/StartTransferMode.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** * Whether to report trace events as series of dataCollected events or to save trace to a stream * (defaults to `ReportEvents`). */ public enum StartTransferMode { @JsonProperty("ReportEvents") REPORT_EVENTS, @JsonProperty("ReturnAsStream") RETURN_AS_STREAM }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/StreamCompression.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Compression type to use for traces returned via streams. */ public enum StreamCompression { @JsonProperty("none") NONE, @JsonProperty("gzip") GZIP }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/StreamFormat.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** * Data format of a trace. Can be either the legacy JSON format or the protocol buffer format. Note * that the JSON format will be deprecated soon. */ public enum StreamFormat { @JsonProperty("json") JSON, @JsonProperty("proto") PROTO }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/TraceConfig.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; import java.util.List; import java.util.Map; public class TraceConfig { @Optional private TraceConfigRecordMode recordMode; @Optional private Double traceBufferSizeInKb; @Optional private Boolean enableSampling; @Optional private Boolean enableSystrace; @Optional private Boolean enableArgumentFilter; @Optional private List<String> includedCategories; @Optional private List<String> excludedCategories; @Optional private List<String> syntheticDelays; @Optional private Map<String, Object> memoryDumpConfig; /** Controls how the trace buffer stores data. */ public TraceConfigRecordMode getRecordMode() { return recordMode; } /** Controls how the trace buffer stores data. */ public void setRecordMode(TraceConfigRecordMode recordMode) { this.recordMode = recordMode; } /** * Size of the trace buffer in kilobytes. If not specified or zero is passed, a default value of * 200 MB would be used. */ public Double getTraceBufferSizeInKb() { return traceBufferSizeInKb; } /** * Size of the trace buffer in kilobytes. If not specified or zero is passed, a default value of * 200 MB would be used. */ public void setTraceBufferSizeInKb(Double traceBufferSizeInKb) { this.traceBufferSizeInKb = traceBufferSizeInKb; } /** Turns on JavaScript stack sampling. */ public Boolean getEnableSampling() { return enableSampling; } /** Turns on JavaScript stack sampling. */ public void setEnableSampling(Boolean enableSampling) { this.enableSampling = enableSampling; } /** Turns on system tracing. */ public Boolean getEnableSystrace() { return enableSystrace; } /** Turns on system tracing. */ public void setEnableSystrace(Boolean enableSystrace) { this.enableSystrace = enableSystrace; } /** Turns on argument filter. */ public Boolean getEnableArgumentFilter() { return enableArgumentFilter; } /** Turns on argument filter. */ public void setEnableArgumentFilter(Boolean enableArgumentFilter) { this.enableArgumentFilter = enableArgumentFilter; } /** Included category filters. */ public List<String> getIncludedCategories() { return includedCategories; } /** Included category filters. */ public void setIncludedCategories(List<String> includedCategories) { this.includedCategories = includedCategories; } /** Excluded category filters. */ public List<String> getExcludedCategories() { return excludedCategories; } /** Excluded category filters. */ public void setExcludedCategories(List<String> excludedCategories) { this.excludedCategories = excludedCategories; } /** Configuration to synthesize the delays in tracing. */ public List<String> getSyntheticDelays() { return syntheticDelays; } /** Configuration to synthesize the delays in tracing. */ public void setSyntheticDelays(List<String> syntheticDelays) { this.syntheticDelays = syntheticDelays; } /** Configuration for memory dump triggers. Used only when "memory-infra" category is enabled. */ public Map<String, Object> getMemoryDumpConfig() { return memoryDumpConfig; } /** Configuration for memory dump triggers. Used only when "memory-infra" category is enabled. */ public void setMemoryDumpConfig(Map<String, Object> memoryDumpConfig) { this.memoryDumpConfig = memoryDumpConfig; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/TraceConfigRecordMode.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Controls how the trace buffer stores data. */ public enum TraceConfigRecordMode { @JsonProperty("recordUntilFull") RECORD_UNTIL_FULL, @JsonProperty("recordContinuously") RECORD_CONTINUOUSLY, @JsonProperty("recordAsMuchAsPossible") RECORD_AS_MUCH_AS_POSSIBLE, @JsonProperty("echoToConsole") ECHO_TO_CONSOLE }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/tracing/TracingBackend.java
package com.github.kklisura.cdt.protocol.v2023.types.tracing; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** * Backend type to use for tracing. `chrome` uses the Chrome-integrated tracing service and is * supported on all platforms. `system` is only supported on Chrome OS and uses the Perfetto system * tracing service. `auto` chooses `system` when the perfettoConfig provided to Tracing.start * specifies at least one non-Chrome data source; otherwise uses `chrome`. */ public enum TracingBackend { @JsonProperty("auto") AUTO, @JsonProperty("chrome") CHROME, @JsonProperty("system") SYSTEM }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/AudioListener.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Protocol object for AudioListener */ public class AudioListener { private String listenerId; private String contextId; public String getListenerId() { return listenerId; } public void setListenerId(String listenerId) { this.listenerId = listenerId; } public String getContextId() { return contextId; } public void setContextId(String contextId) { this.contextId = contextId; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/AudioNode.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Protocol object for AudioNode */ public class AudioNode { private String nodeId; private String contextId; private String nodeType; private Double numberOfInputs; private Double numberOfOutputs; private Double channelCount; private ChannelCountMode channelCountMode; private ChannelInterpretation channelInterpretation; public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getContextId() { return contextId; } public void setContextId(String contextId) { this.contextId = contextId; } public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } public Double getNumberOfInputs() { return numberOfInputs; } public void setNumberOfInputs(Double numberOfInputs) { this.numberOfInputs = numberOfInputs; } public Double getNumberOfOutputs() { return numberOfOutputs; } public void setNumberOfOutputs(Double numberOfOutputs) { this.numberOfOutputs = numberOfOutputs; } public Double getChannelCount() { return channelCount; } public void setChannelCount(Double channelCount) { this.channelCount = channelCount; } public ChannelCountMode getChannelCountMode() { return channelCountMode; } public void setChannelCountMode(ChannelCountMode channelCountMode) { this.channelCountMode = channelCountMode; } public ChannelInterpretation getChannelInterpretation() { return channelInterpretation; } public void setChannelInterpretation(ChannelInterpretation channelInterpretation) { this.channelInterpretation = channelInterpretation; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/AudioParam.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Protocol object for AudioParam */ public class AudioParam { private String paramId; private String nodeId; private String contextId; private String paramType; private AutomationRate rate; private Double defaultValue; private Double minValue; private Double maxValue; public String getParamId() { return paramId; } public void setParamId(String paramId) { this.paramId = paramId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getContextId() { return contextId; } public void setContextId(String contextId) { this.contextId = contextId; } public String getParamType() { return paramType; } public void setParamType(String paramType) { this.paramType = paramType; } public AutomationRate getRate() { return rate; } public void setRate(AutomationRate rate) { this.rate = rate; } public Double getDefaultValue() { return defaultValue; } public void setDefaultValue(Double defaultValue) { this.defaultValue = defaultValue; } public Double getMinValue() { return minValue; } public void setMinValue(Double minValue) { this.minValue = minValue; } public Double getMaxValue() { return maxValue; } public void setMaxValue(Double maxValue) { this.maxValue = maxValue; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/AutomationRate.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of AudioParam::AutomationRate from the spec */ public enum AutomationRate { @JsonProperty("a-rate") A_RATE, @JsonProperty("k-rate") K_RATE }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/BaseAudioContext.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; /** Protocol object for BaseAudioContext */ public class BaseAudioContext { private String contextId; private ContextType contextType; private ContextState contextState; @Optional private ContextRealtimeData realtimeData; private Double callbackBufferSize; private Double maxOutputChannelCount; private Double sampleRate; public String getContextId() { return contextId; } public void setContextId(String contextId) { this.contextId = contextId; } public ContextType getContextType() { return contextType; } public void setContextType(ContextType contextType) { this.contextType = contextType; } public ContextState getContextState() { return contextState; } public void setContextState(ContextState contextState) { this.contextState = contextState; } public ContextRealtimeData getRealtimeData() { return realtimeData; } public void setRealtimeData(ContextRealtimeData realtimeData) { this.realtimeData = realtimeData; } /** Platform-dependent callback buffer size. */ public Double getCallbackBufferSize() { return callbackBufferSize; } /** Platform-dependent callback buffer size. */ public void setCallbackBufferSize(Double callbackBufferSize) { this.callbackBufferSize = callbackBufferSize; } /** Number of output channels supported by audio hardware in use. */ public Double getMaxOutputChannelCount() { return maxOutputChannelCount; } /** Number of output channels supported by audio hardware in use. */ public void setMaxOutputChannelCount(Double maxOutputChannelCount) { this.maxOutputChannelCount = maxOutputChannelCount; } /** Context sample rate. */ public Double getSampleRate() { return sampleRate; } /** Context sample rate. */ public void setSampleRate(Double sampleRate) { this.sampleRate = sampleRate; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/ChannelCountMode.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of AudioNode::ChannelCountMode from the spec */ public enum ChannelCountMode { @JsonProperty("clamped-max") CLAMPED_MAX, @JsonProperty("explicit") EXPLICIT, @JsonProperty("max") MAX }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/ChannelInterpretation.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of AudioNode::ChannelInterpretation from the spec */ public enum ChannelInterpretation { @JsonProperty("discrete") DISCRETE, @JsonProperty("speakers") SPEAKERS }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/ContextRealtimeData.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ /** Fields in AudioContext that change in real-time. */ public class ContextRealtimeData { private Double currentTime; private Double renderCapacity; private Double callbackIntervalMean; private Double callbackIntervalVariance; /** The current context time in second in BaseAudioContext. */ public Double getCurrentTime() { return currentTime; } /** The current context time in second in BaseAudioContext. */ public void setCurrentTime(Double currentTime) { this.currentTime = currentTime; } /** * The time spent on rendering graph divided by render quantum duration, and multiplied by 100. * 100 means the audio renderer reached the full capacity and glitch may occur. */ public Double getRenderCapacity() { return renderCapacity; } /** * The time spent on rendering graph divided by render quantum duration, and multiplied by 100. * 100 means the audio renderer reached the full capacity and glitch may occur. */ public void setRenderCapacity(Double renderCapacity) { this.renderCapacity = renderCapacity; } /** A running mean of callback interval. */ public Double getCallbackIntervalMean() { return callbackIntervalMean; } /** A running mean of callback interval. */ public void setCallbackIntervalMean(Double callbackIntervalMean) { this.callbackIntervalMean = callbackIntervalMean; } /** A running variance of callback interval. */ public Double getCallbackIntervalVariance() { return callbackIntervalVariance; } /** A running variance of callback interval. */ public void setCallbackIntervalVariance(Double callbackIntervalVariance) { this.callbackIntervalVariance = callbackIntervalVariance; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/ContextState.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of AudioContextState from the spec */ public enum ContextState { @JsonProperty("suspended") SUSPENDED, @JsonProperty("running") RUNNING, @JsonProperty("closed") CLOSED }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webaudio/ContextType.java
package com.github.kklisura.cdt.protocol.v2023.types.webaudio; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; /** Enum of BaseAudioContext types */ public enum ContextType { @JsonProperty("realtime") REALTIME, @JsonProperty("offline") OFFLINE }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webauthn/AuthenticatorProtocol.java
package com.github.kklisura.cdt.protocol.v2023.types.webauthn; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum AuthenticatorProtocol { @JsonProperty("u2f") U_2F, @JsonProperty("ctap2") CTAP_2 }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webauthn/AuthenticatorTransport.java
package com.github.kklisura.cdt.protocol.v2023.types.webauthn; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum AuthenticatorTransport { @JsonProperty("usb") USB, @JsonProperty("nfc") NFC, @JsonProperty("ble") BLE, @JsonProperty("cable") CABLE, @JsonProperty("internal") INTERNAL }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webauthn/Credential.java
package com.github.kklisura.cdt.protocol.v2023.types.webauthn; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; public class Credential { private String credentialId; private Boolean isResidentCredential; @Optional private String rpId; private String privateKey; @Optional private String userHandle; private Integer signCount; @Optional private String largeBlob; public String getCredentialId() { return credentialId; } public void setCredentialId(String credentialId) { this.credentialId = credentialId; } public Boolean getIsResidentCredential() { return isResidentCredential; } public void setIsResidentCredential(Boolean isResidentCredential) { this.isResidentCredential = isResidentCredential; } /** Relying Party ID the credential is scoped to. Must be set when adding a credential. */ public String getRpId() { return rpId; } /** Relying Party ID the credential is scoped to. Must be set when adding a credential. */ public void setRpId(String rpId) { this.rpId = rpId; } /** * The ECDSA P-256 private key in PKCS#8 format. (Encoded as a base64 string when passed over * JSON) */ public String getPrivateKey() { return privateKey; } /** * The ECDSA P-256 private key in PKCS#8 format. (Encoded as a base64 string when passed over * JSON) */ public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } /** * An opaque byte sequence with a maximum size of 64 bytes mapping the credential to a specific * user. (Encoded as a base64 string when passed over JSON) */ public String getUserHandle() { return userHandle; } /** * An opaque byte sequence with a maximum size of 64 bytes mapping the credential to a specific * user. (Encoded as a base64 string when passed over JSON) */ public void setUserHandle(String userHandle) { this.userHandle = userHandle; } /** * Signature counter. This is incremented by one for each successful assertion. See * https://w3c.github.io/webauthn/#signature-counter */ public Integer getSignCount() { return signCount; } /** * Signature counter. This is incremented by one for each successful assertion. See * https://w3c.github.io/webauthn/#signature-counter */ public void setSignCount(Integer signCount) { this.signCount = signCount; } /** * The large blob associated with the credential. See * https://w3c.github.io/webauthn/#sctn-large-blob-extension (Encoded as a base64 string when * passed over JSON) */ public String getLargeBlob() { return largeBlob; } /** * The large blob associated with the credential. See * https://w3c.github.io/webauthn/#sctn-large-blob-extension (Encoded as a base64 string when * passed over JSON) */ public void setLargeBlob(String largeBlob) { this.largeBlob = largeBlob; } }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webauthn/Ctap2Version.java
package com.github.kklisura.cdt.protocol.v2023.types.webauthn; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.fasterxml.jackson.annotation.JsonProperty; public enum Ctap2Version { @JsonProperty("ctap2_0") CTAP_2_0, @JsonProperty("ctap2_1") CTAP_2_1 }
0
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/types/webauthn/VirtualAuthenticatorOptions.java
package com.github.kklisura.cdt.protocol.v2023.types.webauthn; /*- * #%L * cdt-java-client * %% * Copyright (C) 2018 - 2023 Kenan Klisura * %% * 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. * #L% */ import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional; public class VirtualAuthenticatorOptions { private AuthenticatorProtocol protocol; @Optional private Ctap2Version ctap2Version; private AuthenticatorTransport transport; @Optional private Boolean hasResidentKey; @Optional private Boolean hasUserVerification; @Optional private Boolean hasLargeBlob; @Optional private Boolean hasCredBlob; @Optional private Boolean hasMinPinLength; @Optional private Boolean hasPrf; @Optional private Boolean automaticPresenceSimulation; @Optional private Boolean isUserVerified; public AuthenticatorProtocol getProtocol() { return protocol; } public void setProtocol(AuthenticatorProtocol protocol) { this.protocol = protocol; } /** Defaults to ctap2_0. Ignored if |protocol| == u2f. */ public Ctap2Version getCtap2Version() { return ctap2Version; } /** Defaults to ctap2_0. Ignored if |protocol| == u2f. */ public void setCtap2Version(Ctap2Version ctap2Version) { this.ctap2Version = ctap2Version; } public AuthenticatorTransport getTransport() { return transport; } public void setTransport(AuthenticatorTransport transport) { this.transport = transport; } /** Defaults to false. */ public Boolean getHasResidentKey() { return hasResidentKey; } /** Defaults to false. */ public void setHasResidentKey(Boolean hasResidentKey) { this.hasResidentKey = hasResidentKey; } /** Defaults to false. */ public Boolean getHasUserVerification() { return hasUserVerification; } /** Defaults to false. */ public void setHasUserVerification(Boolean hasUserVerification) { this.hasUserVerification = hasUserVerification; } /** * If set to true, the authenticator will support the largeBlob extension. * https://w3c.github.io/webauthn#largeBlob Defaults to false. */ public Boolean getHasLargeBlob() { return hasLargeBlob; } /** * If set to true, the authenticator will support the largeBlob extension. * https://w3c.github.io/webauthn#largeBlob Defaults to false. */ public void setHasLargeBlob(Boolean hasLargeBlob) { this.hasLargeBlob = hasLargeBlob; } /** * If set to true, the authenticator will support the credBlob extension. * https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html#sctn-credBlob-extension * Defaults to false. */ public Boolean getHasCredBlob() { return hasCredBlob; } /** * If set to true, the authenticator will support the credBlob extension. * https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html#sctn-credBlob-extension * Defaults to false. */ public void setHasCredBlob(Boolean hasCredBlob) { this.hasCredBlob = hasCredBlob; } /** * If set to true, the authenticator will support the minPinLength extension. * https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#sctn-minpinlength-extension * Defaults to false. */ public Boolean getHasMinPinLength() { return hasMinPinLength; } /** * If set to true, the authenticator will support the minPinLength extension. * https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#sctn-minpinlength-extension * Defaults to false. */ public void setHasMinPinLength(Boolean hasMinPinLength) { this.hasMinPinLength = hasMinPinLength; } /** * If set to true, the authenticator will support the prf extension. * https://w3c.github.io/webauthn/#prf-extension Defaults to false. */ public Boolean getHasPrf() { return hasPrf; } /** * If set to true, the authenticator will support the prf extension. * https://w3c.github.io/webauthn/#prf-extension Defaults to false. */ public void setHasPrf(Boolean hasPrf) { this.hasPrf = hasPrf; } /** * If set to true, tests of user presence will succeed immediately. Otherwise, they will not be * resolved. Defaults to true. */ public Boolean getAutomaticPresenceSimulation() { return automaticPresenceSimulation; } /** * If set to true, tests of user presence will succeed immediately. Otherwise, they will not be * resolved. Defaults to true. */ public void setAutomaticPresenceSimulation(Boolean automaticPresenceSimulation) { this.automaticPresenceSimulation = automaticPresenceSimulation; } /** Sets whether User Verification succeeds or fails for an authenticator. Defaults to false. */ public Boolean getIsUserVerified() { return isUserVerified; } /** Sets whether User Verification succeeds or fails for an authenticator. Defaults to false. */ public void setIsUserVerified(Boolean isUserVerified) { this.isUserVerified = isUserVerified; } }
0
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar/client/Command.java
package ai.platon.pulsar.client; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class Command { public static void main(String[] args) throws Exception { var command = """ Go to https://www.amazon.com/dp/B0C1H26C46 After browser launch: clear browser cookies. After page load: scroll to the middle. Summarize the product. Extract: product name, price, ratings. Find all links containing /dp/. """; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8182/api/commands/plain")) .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString(command)).build(); String response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body(); System.out.println(response); } }
0
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar/client/CommandSSE.java
package ai.platon.pulsar.client; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class CommandSSE { public static void main(String[] args) throws Exception { var command = """ Go to https://www.amazon.com/dp/B0C1H26C46 After browser launch: clear browser cookies. After page load: scroll to the middle. Summarize the product. Extract: product name, price, ratings. Find all links containing /dp/. """; // Send command to server var request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8182/api/commands/plain?mode=async")) .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString(command)) .build(); var id = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body(); System.out.println(id); // Receive server send events var client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build(); var sseRequest = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8182/api/commands/" + id + "/stream")) .header("Accept", "text/event-stream") .GET() .build(); // Process the SSE stream until command completes client.send(sseRequest, HttpResponse.BodyHandlers.ofLines()) .body() .forEach(line -> { if (line.startsWith("data:")) { String data = line.substring(5).trim(); System.out.println("SSE update: " + data); } }); } }
0
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-client/3.0.15/ai/platon/pulsar/client/Scraper.java
package ai.platon.pulsar.client; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; /** * A simple scraper which just send an X-SQL request to the pulsar server and get the scrape result */ public class Scraper { public static void main(String[] args) throws IOException, InterruptedException { var sql = """ select dom_first_text(dom, '#productTitle') as `title`, dom_first_text(dom, '#price tr td:contains(List Price) ~ td') as `listprice`, dom_first_text(dom, '#price tr td:matches(^Price) ~ td, #price_inside_buybox') as `price`, array_join_to_string(dom_all_texts(dom, '#wayfinding-breadcrumbs_container ul li a'), '|') as `categories`, dom_base_uri(dom) as `baseUri` from load_and_select('https://www.amazon.com/dp/B0C1H26C46', ':root') """; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8182/api/x/e")) .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString(sql)).build(); String response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body(); System.out.println(response); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/DateTimeDetector.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import java.text.ParseException; import java.time.*; import java.util.Date; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Detect a date time in a text. * @see org.apache.commons.lang3.time.DateUtils */ public class DateTimeDetector { public static final int MIN_DATE_TIME_STR_LENGTH = "2015-01-01 12:00".length(); public static final int MIN_YEAR_MONTH_STR_LENGTH = "201501".length(); public static final int MIN_DATE_STR_LENGTH = "20150101".length(); public static final int MAX_META_STR_LENGTH = 200; public static final int MAX_DATE_TIME_STR_LENGTH = "EEE, dd MMM yyyy HH:mm:ss zzz".length(); public static final int MAX_TITLE_LENGTH = 350; public static final String[] BAD_DATE_TIME_STRING_CONTAINS = new String[]{ "GMT+8", "UTC+8", "Processed", "访问", "刷新", "visit" }; public static final int OLD_DATE_DAYS = 30; public static final LocalDate CURRENT_DATE = LocalDate.now(); public static final long CURRENT_DATE_EPOCH_DAYS = CURRENT_DATE.toEpochDay(); public static final int CURRENT_YEAR = CURRENT_DATE.getYear(); public static final String CURRENT_YEAR_STR = String.valueOf(CURRENT_YEAR); public static final int CURRENT_MONTH = CURRENT_DATE.getMonthValue(); public static final int YEAR_LOWER_BOUND = 1990; public static final List<String> VALID_WORK_YEARS = IntStream.range(2010, 2030) .mapToObj(String::valueOf).collect(Collectors.toList()); public static final List<String> VALID_WORK_YEARS_SHORT = IntStream.range(10, 30) .mapToObj(String::valueOf).collect(Collectors.toList()); public static final String[] VALID_WORK_YEARS_ARRAY = VALID_WORK_YEARS.toArray(new String[0]); public static final String[] VALID_WORK_YEARS_SHORT_ARRAY = VALID_WORK_YEARS_SHORT.toArray(new String[0]); public static Set<String> OLD_YEARS; public static Set<String> OLD_MONTH; public static Pattern OLD_MONTH_URL_DATE_PATTERN; // 2016-03-05 20:07:51 // TODO : What's the difference between HH and hh? 24 hours VS 12 hours? public static String[] COMMON_DATE_FORMATS = new String[]{ "yyyyMMdd", "yyyy.MM.dd", "yyyy-MM-dd", "yyyy年MM月dd日", "yyyy/MM/dd", }; public static String[] COMMON_DATE_TIME_FORMATS = new String[]{ "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd hh:mm", "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy年MM月dd日 HH:mm", "yyyy年MM月dd日 hh:mm", "yyyy年MM月dd日 HH:mm:ss", "yyyy年MM月dd日 hh:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd hh:mm", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd hh:mm:ss", "yyyy/MM/dd HH:mm:ss.SSS zzz", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz", "dd.MM.yyyy zzz", "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", "EEE MMM dd HH:mm:ss zzz yyyy", "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss", "EEE, dd-MMM-yy HH:mm:ss zzz" }; static { // 1 years ago OLD_YEARS = IntStream.range(YEAR_LOWER_BOUND, CURRENT_YEAR).mapToObj(String::valueOf).collect(Collectors.toSet()); // 2 month ago OLD_MONTH = IntStream.range(1, CURRENT_MONTH - 1).mapToObj(m -> String.format("%02d", m)).collect(Collectors.toSet()); String monthPattern = StringUtils.join(OLD_MONTH, "|"); if (CURRENT_MONTH <= 2) { monthPattern = "\\d{2}"; } // eg : ".+2016[/\.-]?(01|02|03|04|05|06|07|08|09).+" OLD_MONTH_URL_DATE_PATTERN = Pattern.compile(".+" + CURRENT_YEAR + "[/\\.-]?(" + monthPattern + ").+"); } private final String[] dateFormats; private final String[] dateTimeFormats; private ZoneId zoneId; public DateTimeDetector() { this(COMMON_DATE_FORMATS, COMMON_DATE_TIME_FORMATS); } public DateTimeDetector(ZoneId zoneId) { this(COMMON_DATE_FORMATS, COMMON_DATE_TIME_FORMATS, zoneId); } public DateTimeDetector(String[] dateFormats, String[] dateTimeFormats) { this(dateFormats, dateTimeFormats, ZoneId.systemDefault()); } public DateTimeDetector(String[] dateFormats, String[] dateTimeFormats, ZoneId zoneId) { this.dateFormats = dateFormats; this.dateTimeFormats = dateTimeFormats; this.zoneId = zoneId; if (CURRENT_YEAR > 2030) { System.out.println("This program must be refined after 2030"); System.exit(2030); } } public ZoneId getZoneId() { return zoneId; } public void setZoneId(ZoneId zoneId) { this.zoneId = zoneId; } /** * Detect a possible date time string in a text */ public String detectPossibleDateTimeString(String text) { String possibleDate = StringUtils.substringBefore(text, "\n"); int dateStart = StringUtils.indexOfAny(possibleDate, VALID_WORK_YEARS_ARRAY); if (dateStart == StringUtils.INDEX_NOT_FOUND) { dateStart = StringUtils.indexOfAny(possibleDate, VALID_WORK_YEARS_SHORT_ARRAY); if (dateStart != StringUtils.INDEX_NOT_FOUND) { // OK for years possibleDate = "20" + possibleDate.substring(dateStart); if (possibleDate.matches("20[0-9][0-9][\\-\\./年]?\\d+.+")) { dateStart = 0; } } } if (dateStart < 0 || dateStart >= possibleDate.length()) { return null; } int dateEnd = Math.min(possibleDate.length(), dateStart + MAX_DATE_TIME_STR_LENGTH); possibleDate = possibleDate.substring(dateStart, dateEnd); possibleDate = possibleDate.replaceAll("[\\./年月]", "-").trim(); return possibleDate; } /** * Try to detect a best date time */ public OffsetDateTime detectDateTimeLeniently(String text) { OffsetDateTime dateTime = detectDateTime(text); if (dateTime == null) { dateTime = detectDate(text); } return dateTime; } public OffsetDateTime detectDateTime(String text) { if (text == null || text.length() < MIN_DATE_TIME_STR_LENGTH) { return null; } // \p{Z} or \p{Separator}: any kind of whitespace or invisible separator. text = text.replaceAll("\\p{Zs}", " ").trim(); // text = text.replaceAll("\\s+", " ").trim(); // May be automatically generated date time final String finalText = text; if (Stream.of(BAD_DATE_TIME_STRING_CONTAINS).anyMatch(finalText::contains)) { return null; } final int dateTimeStart = StringUtils.indexOfAny(text, VALID_WORK_YEARS_ARRAY); if (dateTimeStart == StringUtils.INDEX_NOT_FOUND) { return null; } // For example : "2017-12-20 11:18:35" final int dateEnd = StringUtils.indexOf(text, " ", dateTimeStart); if (dateEnd < 0) { // TODO : try getTextDocument date } // Find the datetime string's end final int timeStart = dateEnd + 1; int pos = timeStart; for (; pos < text.length(); ++pos) { Character ch = text.charAt(pos); if (!Character.isDigit(ch) && ch != ':') { break; } } final int dateTimeEnd = pos; String possibleDate = StringUtils.substring(text, dateTimeStart, dateTimeEnd); // try getTextDocument datetime OffsetDateTime dateTime = null; if (possibleDate.length() >= MIN_DATE_TIME_STR_LENGTH) { dateTime = parseDateTimeStrictly(possibleDate); } return dateTime; } public YearMonth detectYearMonth(String text) { String possibleYearMonth = detectPossibleDateTimeString(text); return possibleYearMonth != null ? tryParseYearMonthStrictly(possibleYearMonth) : null; } public YearMonth tryParseYearMonthStrictly(String possibleYearMonth) { try { final Pattern pattern = Pattern.compile("20[0-9][0-9][0-1][0-9].+"); final Pattern pattern2 = Pattern.compile("20[0-9][0-9]-[0-1]?[0-9].+"); if (pattern.matcher(possibleYearMonth).matches()) { possibleYearMonth = possibleYearMonth.substring(0, 4) + "-" + possibleYearMonth.substring(4, 6); return YearMonth.parse(possibleYearMonth); } else if (pattern2.matcher(possibleYearMonth).matches()) { String[] parts = possibleYearMonth.split("-"); if (parts.length >= 2 && parts[0].length() == 4) { if (parts[1].length() == 1) { parts[1] = "0" + parts[1]; } possibleYearMonth = parts[0] + "-" + parts[1]; return YearMonth.parse(possibleYearMonth); } } } catch (Throwable ignored) { } return null; } /** * Detect a date */ public OffsetDateTime detectDate(String text) { String possibleDate = detectPossibleDateTimeString(text); return possibleDate != null ? tryParseDateTimeStrictly(possibleDate) : null; } /** * Try parse a date time */ public OffsetDateTime tryParseDateTimeStrictly(String possibleDate) { try { final Pattern pattern = Pattern.compile("20[0-9][0-9][0-1][0-9][0-3][0-9].+"); final Pattern pattern2 = Pattern.compile("20[0-9][0-9]-[0-1]?[0-9]-[0-3]?[0-9].+"); if (pattern.matcher(possibleDate).matches()) { possibleDate = StringUtils.substring(possibleDate, 0, "yyyyMMdd".length()); } else if (pattern2.matcher(possibleDate).matches()) { String[] parts = possibleDate.split("-"); if (parts.length >= 3 && parts[0].length() == 4) { if (parts[1].length() == 1) { parts[1] = "0" + parts[1]; } if (parts[2].length() == 1) { parts[2] = "0" + parts[2]; } if (parts[2].length() > 2) { parts[2] = parts[2].substring(0, 2); } possibleDate = parts[0] + "-" + parts[1] + "-" + parts[2]; } } else { possibleDate = null; } return possibleDate == null ? null : parseDateStrictly(possibleDate, dateFormats); } catch (Throwable ignored) { } return null; } public OffsetDateTime parseDateStrictly(String dateStr) { return parseDateStrictly(dateStr, dateFormats); } public OffsetDateTime parseDateTimeStrictly(String dateStr) { return parseDateStrictly(dateStr, dateTimeFormats); } public OffsetDateTime parseDateStrictly(String dateStr, String... formats) { Date parsedDate = null; try { parsedDate = DateUtils.parseDateStrictly(dateStr, formats); } catch (ParseException ignored) { } return parsedDate == null ? null : OffsetDateTime.ofInstant(parsedDate.toInstant(), zoneId); } public Instant parseDateTimeStrictly(String dateStr, Instant defaultValue) { try { return DateUtils.parseDateStrictly(dateStr, dateTimeFormats).toInstant(); } catch (Throwable ignored) { } return defaultValue; } /** * For urls who contains date information, for example * http://bond.hexun.com/2011-01-07/126641872.html * * @param text a {@link java.lang.String} object. * @param days a int. * @param zoneId a {@link java.time.ZoneId} object. * @return a boolean. */ public boolean containsOldDate(String text, int days, ZoneId zoneId) { if (text == null) { return false; } YearMonth yearMonth = detectYearMonth(text); if (yearMonth == null) { return false; } OffsetDateTime dateTime = yearMonth.atEndOfMonth().atTime(0, 0).atZone(zoneId).toOffsetDateTime(); if (DateTimes.isDaysBefore(dateTime, days)) { return true; } dateTime = detectDate(text); return dateTime != null && DateTimes.isDaysBefore(dateTime, days); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/DublinCore.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common; /** * A collection of Dublin Core metadata names. * * @see <a href="http://dublincore.org">dublincore.org</a> * @author Chris Mattmann * @author J&eacute;r&ocirc;me Charron * @version $Id: $Id */ public interface DublinCore { /** * Typically, Format may include the media-type or dimensions of the resource. * Format may be used to determine the software, hardware or other equipment * needed to display or operate the resource. Examples of dimensions include * size and duration. Recommended best practice is to select a value from a * controlled vocabulary (for example, the list of Internet Media Types [MIME] * defining computer media formats). */ String FORMAT = "format"; /** * Recommended best practice is to identify the resource by means of a string * or number conforming to a formal identification system. Example formal * identification systems include the Uniform Resource Identifier (URI) * (including the Uniform Resource Locator (URL)), the Digital Object * Identifier (DOI) and the International Standard Book Number (ISBN). */ String IDENTIFIER = "identifier"; /** * Date on which the resource was changed. */ String MODIFIED = "modified"; /** * An entity responsible for making contributions to the content of the * resource. Examples of a Contributor include a person, an organisation, or a * service. Typically, the name of a Contributor should be used to indicate * the entity. */ String CONTRIBUTOR = "contributor"; /** * The extent or scope of the content of the resource. Coverage will typically * include spatial location (a place name or geographic coordinates), temporal * period (a period label, date, or date range) or jurisdiction (such as a * named administrative entity). Recommended best practice is to select a * value from a controlled vocabulary (for example, the Thesaurus of * Geographic Names [TGN]) and that, where appropriate, named places or time * periods be used in preference to numeric identifiers such as sets of * coordinates or date ranges. */ String COVERAGE = "coverage"; /** * An entity primarily responsible for making the content of the resource. * Examples of a Creator include a person, an organisation, or a service. * Typically, the name of a Creator should be used to indicate the entity. */ String CREATOR = "creator"; /** * A date associated with an event in the life cycle of the resource. * Typically, Date will be associated with the creation or availability of the * resource. Recommended best practice for encoding the date value is defined * in a profile of ISO 8601 [W3CDTF] and follows the YYYY-MM-DD format. */ String DATE = "date"; /** * An account of the content of the resource. Description may include but is * not limited to: an abstract, table of contents, reference to a graphical * representation of content or a free-text account of the content. */ String DESCRIPTION = "description"; /** * A language of the intellectual content of the resource. Recommended best * practice is to use RFC 3066 [RFC3066], which, in conjunction with ISO 639 * [ISO639], defines two- and three-letter primary language tags with optional * subtags. Examples include "en" or "eng" for English, "akk" for Akkadian, * and "en-GB" for English used in the United Kingdom. */ String LANGUAGE = "language"; /** * An entity responsible for making the resource available. Examples of a * Publisher include a person, an organisation, or a service. Typically, the * name of a Publisher should be used to indicate the entity. */ String PUBLISHER = "publisher"; /** * A reference to a related resource. Recommended best practice is to * reference the resource by means of a string or number conforming to a * formal identification system. */ String RELATION = "relation"; /** * Information about rights held in and over the resource. Typically, a Rights * element will contain a rights management statement for the resource, or * reference a service providing such information. Rights information often * encompasses Intellectual Property Rights (IPR), Copyright, and various * Property Rights. If the Rights element is absent, no assumptions can be * made about the status of these and other rights with respect to the * resource. */ String RIGHTS = "rights"; /** * A reference to a resource from which the present resource is derived. The * present resource may be derived from the Source resource in whole or in * part. Recommended best practice is to reference the resource by means of a * string or number conforming to a formal identification system. */ String SOURCE = "source"; /** * The topic of the content of the resource. Typically, a Subject will be * expressed as keywords, key phrases or classification codes that describe a * topic of the resource. Recommended best practice is to select a value from * a controlled vocabulary or formal classification scheme. */ String SUBJECT = "subject"; /** * A name given to the resource. Typically, a Title will be a name by which * the resource is formally known. */ String TITLE = "title"; /** * The nature or genre of the content of the resource. Type includes terms * describing general categories, functions, genres, or aggregation levels for * content. Recommended best practice is to select a value from a controlled * vocabulary (for example, the DCMI Type Vocabulary [DCMITYPE]). To describe * the physical or digital manifestation of the resource, use the Format * element. */ String TYPE = "type"; }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/HttpHeaders.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common; /** * A collection of HTTP header names. * <p> * TODO: use guava HttpHeaders * * @author vincent * @version $Id: $Id */ public interface HttpHeaders { String TRANSFER_ENCODING = "Transfer-Encoding"; /** * Content encoding from http header, it's a suggestion * but Q_TRUSTED_CONTENT_ENCODING can be trusted * */ String CONTENT_ENCODING = "Content-Encoding"; String CONTENT_LANGUAGE = "Content-Language"; String CONTENT_LENGTH = "Content-Length"; String CONTENT_LOCATION = "Content-Location"; String CONTENT_DISPOSITION = "Content-Disposition"; String CONTENT_MD5 = "Content-MD5"; String CONTENT_TYPE = "Content-Type"; String LAST_MODIFIED = "Last-Modified"; String LOCATION = "Location"; // Internal usage String Q_TRUSTED_CONTENT_ENCODING = "Q-Trusted-Content-Encoding"; String Q_VERSION = "Q-Version"; String Q_USERNAME = "Q-Username"; String Q_PASSWORD = "Q-Password"; String Q_JOB_ID = "Q-Job-Id"; String Q_PRIORITY = "Q-Priority"; String Q_QUEUE_ID = "Q-Queue-Id"; String Q_ITEM_ID = "Q-Item-Id"; String Q_REQUEST_TIME = "Q-Request-Time"; // should be millis from epoch, e.g. System.currentTimeMillis() String Q_RESPONSE_TIME = "Q-Response-Time"; // should be millis from epoch, e.g. System.currentTimeMillis() String Q_STATUS_CODE = "Q-Status-Code"; String Q_CHECKSUM = "Q-Checksum"; String Q_URL = "Q-Url"; }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/NetUtil.java
package ai.platon.pulsar.common; import ai.platon.pulsar.common.urls.URLUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.*; import java.time.Duration; import java.util.regex.Pattern; /** * <p>NetUtil class.</p> * * @author vincent * @version $Id: $Id */ public class NetUtil { private static final Logger log = LoggerFactory.getLogger(NetUtil.class); public static Duration CONNECTION_TIMEOUT = Duration.ofSeconds(3); public static Duration PROXY_CONNECTION_TIMEOUT = Duration.ofSeconds(3); // Pattern for matching ip[:port] public static final Pattern IP_PORT_PATTERN = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d+)?"); public static boolean testNetwork(String host, int port) { return testTcpNetwork(host, port); } public static boolean testHttpNetwork(String url) { var u = URLUtils.getURLOrNull(url); if (u == null) { return false; } return testHttpNetwork(u.getHost(), u.getPort()); } public static boolean testHttpNetwork(URL url) { return testHttpNetwork(url, null); } public static boolean testHttpNetwork(URL url, Proxy proxy) { boolean reachable = false; try { HttpURLConnection con; if (proxy != null) { con = (HttpURLConnection) url.openConnection(proxy); } else { con = (HttpURLConnection) url.openConnection(); } con.setConnectTimeout((int) PROXY_CONNECTION_TIMEOUT.toMillis()); con.connect(); if (proxy != null) { log.debug("Proxy is available {} for {}", proxy, url); } reachable = true; con.disconnect(); } catch (Exception ignored) { } return reachable; } public static boolean testHttpNetwork(String host, int port) { if (host.isBlank()) { return false; } try { URL url = new URL("http", host, port, "/"); return testHttpNetwork(url); } catch (MalformedURLException ignored) { } return false; } public static boolean testTcpNetwork(String host, int port) { return testTcpNetwork(host, port, CONNECTION_TIMEOUT); } public static boolean testTcpNetwork(String host, int port, Duration timeout) { if (host.isBlank()) { return false; } boolean reachable = false; Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(host, port), (int)timeout.toMillis()); reachable = socket.isConnected(); socket.close(); } catch (Exception ignored) { // logger.warn("can not connect to " + ip + ":" + port); } return reachable; } public static String getHostname() { try {return "" + InetAddress.getLocalHost();} catch(UnknownHostException uhe) {return "" + uhe;} } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/PulsarParams.java
package ai.platon.pulsar.common; import ai.platon.pulsar.common.config.Params; import java.util.Map; /** * Created by vincent on 16-9-24. * * @author vincent * @version $Id: $Id */ public class PulsarParams extends Params { public static final String VAR_FETCH_STATE = "fetch_state"; public static final String VAR_PREV_FETCH_TIME_BEFORE_UPDATE = "prev_fetch_time_before_update"; public static final String VAR_PRIVACY_CONTEXT_DISPLAY = "privacy_context_name"; /** * Privacy agent variable name */ public static final String VAR_PRIVACY_AGENT = "VAR_PRIVACY_AGENT"; /** * Additional load status to report by PageLoadStatusFormatter. * */ public static final String VAR_ADD_LOAD_STATUS = "additional_load_status"; /** * If this task is a scrape task * TODO: this is a temporary solution * */ public static final String VAR_IS_SCRAPE = "IS_SCRAPE"; public static final String VAR_LOAD_OPTIONS = "LOAD_OPTIONS"; /** * <p>Constructor for PulsarParams.</p> */ public PulsarParams() { } /** * <p>Constructor for PulsarParams.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. */ public PulsarParams(String key, Object value, Object... others) { super(key, value, others); } /** * <p>Constructor for PulsarParams.</p> * * @param args a {@link java.util.Map} object. */ public PulsarParams(Map<String, Object> args) { super(args); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/RegexExtractor.java
package ai.platon.pulsar.common; import org.apache.commons.lang3.tuple.Pair; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by vincent on 17-8-3. * Copyright @ 2013-2023 Platon AI. All rights reserved * * @author vincent * @version $Id: $Id */ public class RegexExtractor { private String defaultKeyIfAbsent = ""; private String defaultValueIfAbsent = ""; /** * <p>Constructor for RegexExtractor.</p> */ public RegexExtractor() { } /** * <p>re1.</p> * * @param text a {@link java.lang.String} object. * @param regex a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public String re1(String text, String regex) { return re1(text, Pattern.compile(regex), 1); } /** * <p>re1.</p> * * @param text a {@link java.lang.String} object. * @param pattern a {@link java.util.regex.Pattern} object. * @return a {@link java.lang.String} object. */ public String re1(String text, Pattern pattern) { return re1(text, pattern, 1); } /** * <p>re1.</p> * * @param text a {@link java.lang.String} object. * @param regex a {@link java.lang.String} object. * @param valueGroup a int. * @return a {@link java.lang.String} object. */ public String re1(String text, String regex, int valueGroup) { return re1(text, Pattern.compile(regex)); } /** * <p>re1.</p> * * @param text a {@link java.lang.String} object. * @param pattern a {@link java.util.regex.Pattern} object. * @param valueGroup a int. * @return a {@link java.lang.String} object. */ public String re1(String text, Pattern pattern, int valueGroup) { String result = defaultValueIfAbsent; Matcher matcher = pattern.matcher(text); if (matcher.find()) { int groupCount = matcher.groupCount(); if (valueGroup <= groupCount) { String v = matcher.group(valueGroup); if (v != null) { result = v.trim(); } } } return result; } /** * <p>re2.</p> * * @param text a {@link java.lang.String} object. * @param regex a {@link java.lang.String} object. * @return a {@link org.apache.commons.lang3.tuple.Pair} object. */ public Pair<String, String> re2(String text, String regex) { return re2(text, Pattern.compile(regex), 1, 2); } /** * <p>re2.</p> * * @param text a {@link java.lang.String} object. * @param pattern a {@link java.util.regex.Pattern} object. * @return a {@link org.apache.commons.lang3.tuple.Pair} object. */ public Pair<String, String> re2(String text, Pattern pattern) { return re2(text, pattern, 1, 2); } /** * <p>re2.</p> * * @param text a {@link java.lang.String} object. * @param regex a {@link java.lang.String} object. * @param keyGroup a int. * @param valueGroup a int. * @return a {@link org.apache.commons.lang3.tuple.Pair} object. */ public Pair<String, String> re2(String text, String regex, int keyGroup, int valueGroup) { return re2(text, Pattern.compile(regex), keyGroup, valueGroup); } /** * <p>re2.</p> * * @param text a {@link java.lang.String} object. * @param pattern a {@link java.util.regex.Pattern} object. * @param keyGroup a int. * @param valueGroup a int. * @return a {@link org.apache.commons.lang3.tuple.Pair} object. */ public Pair<String, String> re2(String text, Pattern pattern, int keyGroup, int valueGroup) { Pair<String, String> parts = Pair.of(defaultKeyIfAbsent, defaultValueIfAbsent); Matcher matcher = pattern.matcher(text); if (matcher.find()) { int groupCount = matcher.groupCount(); if (keyGroup <= groupCount && valueGroup <= groupCount) { String k = matcher.group(keyGroup); String v = matcher.group(valueGroup); if (k != null && v != null) { parts = Pair.of(k.trim(), v.trim()); } } } return parts; } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/SParser.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import java.io.*; import java.lang.ref.WeakReference; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static ai.platon.pulsar.common.LogsKt.getLogger; /** * A common string parser * * @author vincent * @version $Id: $Id */ public class SParser { public static final Logger LOG = getLogger(SParser.class); public static final Duration INVALID_DURATION = Duration.ofSeconds(Integer.MIN_VALUE); private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> CACHE_CLASSES = new WeakHashMap<>(); /** * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}. */ private static final Class<?> NEGATIVE_CACHE_SENTINEL = NegativeCacheSentinel.class; /** * Stores the mapping of key to the resource which modifies or loads * the key most recently */ private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{[^\\}\\$\u0020]+\\}"); private static final int MAX_SUBST = 20; /** * TODO: consider ResourceLoader */ private ClassLoader classLoader; { classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = SParser.class.getClassLoader(); } } private String value; /** * <p>Constructor for SParser.</p> */ public SParser() { } /** * <p>Constructor for SParser.</p> * * @param value a {@link java.lang.String} object. */ public SParser(String value) { this.value = value; } /** * <p>wrap.</p> * * @param value a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.SParser} object. */ public static SParser wrap(String value) { return new SParser(value); } /** * <p>set.</p> * * @param value a {@link java.lang.String} object. */ public void set(String value) { this.value = value; } /** * <p>setIfUnset.</p> * * @param value a {@link java.lang.String} object. */ public synchronized void setIfUnset(String value) { if (this.value == null) { set(value); } } /** * Get the value of property, <code>null</code> if * no such property exists. * <p> * Values are processed for <a href="#VariableExpansion">variable expansion</a> * before being returned. * * @return the value of or its replacing property, * or null if no such property exists. */ public String get() { return substituteVars(value); } /** * Get the value of property as a trimmed <code>String</code>, * <code>null</code> if no such property exists. * <p> * Values are processed for <a href="#VariableExpansion">variable expansion</a> * before being returned. * * @return the value of or its replacing property, * or null if no such property exists. */ public String getTrimmed() { if (null == value) { return null; } else { return value.trim(); } } /** * Get the value of property as a trimmed <code>String</code>, * <code>defaultValue</code> if no such property exists. * See @{Configuration#getTrimmed} for more details. * * @param defaultValue the property default value. * @return the value of or defaultValue * if it is not set. */ public String getTrimmed(String defaultValue) { String ret = getTrimmed(); return ret == null ? defaultValue : ret; } /** * <p>getRaw.</p> * * @return a {@link java.lang.String} object. */ public String getRaw() { return value; } /** * <p>get.</p> * * @param defaultValue a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public String get(String defaultValue) { return value == null ? defaultValue : value; } /** * Get an integer value, if the configured value is invalid or not set, return the default value. * * @throws NumberFormatException when the value is invalid * */ public int getInt(int defaultValue) { String valueString = getTrimmed(); if (valueString == null) { return defaultValue; } String hexString = getHexDigits(valueString); if (hexString != null) { return Integer.parseInt(hexString, 16); } return Integer.parseInt(valueString); } /** * <p>getInts.</p> * * @return an array of {@link int} objects. */ public int[] getInts() { String[] strings = getTrimmedStrings(); int[] ints = new int[strings.length]; for (int i = 0; i < strings.length; i++) { ints[i] = Integer.parseInt(strings[i]); } return ints; } /** * <p>setInt.</p> * * @param value a int. */ public void setInt(int value) { set(Integer.toString(value)); } /** * Get the value of property as a <code>long</code>. * If no such property exists, the provided default value is returned, * or if the specified value is not a valid <code>long</code>, * then an error is thrown. * * @param defaultValue default value. * @return property value as a <code>long</code>, * or <code>defaultValue</code>. * @throws java.lang.NumberFormatException when the value is invalid */ public long getLong(long defaultValue) { String valueString = getTrimmed(); if (valueString == null) return defaultValue; String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); } /** * Get the value of property as a <code>long</code> or * human readable format. If no such property exists, the provided default * value is returned, or if the specified value is not a valid * <code>long</code> or human readable format, then an error is thrown. You * can use the following suffix (case insensitive): k(kilo), m(mega), g(giga), * t(tera), p(peta), e(exa) * * @param defaultValue default value. * @return property value as a <code>long</code>, * or <code>defaultValue</code>. * @throws java.lang.NumberFormatException when the value is invalid */ public long getLongBytes(long defaultValue) { String valueString = getTrimmed(); if (valueString == null) return defaultValue; return TraditionalBinaryPrefix.string2long(valueString); } private String getHexDigits(String value) { boolean negative = false; String str = value; String hexString = null; if (value.startsWith("-")) { negative = true; str = value.substring(1); } if (str.startsWith("0x") || str.startsWith("0X")) { hexString = str.substring(2); if (negative) { hexString = "-" + hexString; } return hexString; } return null; } /** * Set the value of property to a <code>long</code>. * * @param value <code>long</code> value of the property. */ public void setLong(long value) { set(Long.toString(value)); } /** * Get the value of property as a <code>float</code>. * If no such property exists, the provided default value is returned, * or if the specified value is not a valid <code>float</code>, * then an error is thrown. * * @param defaultValue default value. * @return property value as a <code>float</code>, * or <code>defaultValue</code>. * @throws java.lang.NumberFormatException when the value is invalid */ public float getFloat(float defaultValue) { String valueString = getTrimmed(); if (valueString == null) return defaultValue; return Float.parseFloat(valueString); } /** * Set the value of property to a <code>float</code>. * * @param value property value. */ public void setFloat(float value) { set(Float.toString(value)); } /** * Get the value of property as a <code>double</code>. * If no such property exists, the provided default value is returned, * or if the specified value is not a valid <code>double</code>, * then an error is thrown. * * @param defaultValue default value. * @return property value as a <code>double</code>, * or <code>defaultValue</code>. * @throws java.lang.NumberFormatException when the value is invalid */ public double getDouble(double defaultValue) { String valueString = getTrimmed(); if (valueString == null) return defaultValue; return Double.parseDouble(valueString); } /** * Set the value of property to a <code>double</code>. * * @param value property value. */ public void setDouble(double value) { set(Double.toString(value)); } /** * Get the value of property as a <code>boolean</code>. * If no such property is specified, or if the specified value is not a valid * <code>boolean</code>, then <code>defaultValue</code> is returned. * * @param defaultValue default value. * @return property value as a <code>boolean</code>, * or <code>defaultValue</code>. */ public boolean getBoolean(boolean defaultValue) { String valueString = getTrimmed(); if (null == valueString || valueString.isEmpty()) { return defaultValue; } valueString = valueString.toLowerCase(); if ("true".equals(valueString)) return true; else if ("false".equals(valueString)) return false; else return defaultValue; } /** * Set the value of property to a <code>boolean</code>. * * @param value <code>boolean</code> value of the property. */ public void setBoolean(boolean value) { set(Boolean.toString(value)); } /** * Set the given property, if it is currently unset. * * @param value new value */ public void setBooleanIfUnset(boolean value) { setIfUnset(Boolean.toString(value)); } /** * Set the value of property to the given type. This * is equivalent to <code>set(&lt;name&gt;, value.toString())</code>. * * @param value new value * @param <T> a T object. */ public <T extends Enum<T>> void setEnum(T value) { set(value.toString()); } /** * Return value matching this enumerated type. * * @param defaultValue Value returned if no mapping exists * @param <T> a T object. * @return a T object. * @throws java.lang.IllegalArgumentException If mapping is illegal for the type * provided */ public <T extends Enum<T>> T getEnum(T defaultValue) { return null == value ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), value); } /** * Set the value to the given time duration * * @param value Time duration * @param unit Unit of time */ public void setTimeDuration(long value, TimeUnit unit) { set(value + ParsedTimeDuration.unitFor(unit).suffix()); } /** * Return time duration in the given time unit. Valid units are encoded in * properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds * (ms), seconds (s), minutes (m), hours (h), and days (d). * * @param defaultValue Value returned if no mapping exists. * @param unit Unit to convert the stored property, if it exists. * @return The time duration * @throws java.lang.NumberFormatException If the property stripped of its unit is not * a number */ public long getTimeDuration(long defaultValue, TimeUnit unit) { if (null == value) { return defaultValue; } value = value.trim(); ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(value); if (null == vUnit) { LOG.warn("No unit for " + "(" + value + ") assuming " + unit); vUnit = ParsedTimeDuration.unitFor(unit); } else { value = value.substring(0, value.lastIndexOf(vUnit.suffix())); } return unit.convert(Long.parseLong(value), vUnit.unit()); } /** * Get the value of property as a <code>Pattern</code>. * If no such property is specified, or if the specified value is not a valid * <code>Pattern</code>, then <code>DefaultValue</code> is returned. * * @param defaultValue default value * @return property value as a compiled Pattern, or defaultValue */ public Pattern getPattern(Pattern defaultValue) { if (null == value || value.isEmpty()) { return defaultValue; } try { return Pattern.compile(value); } catch (PatternSyntaxException pse) { LOG.warn("Regular expression '" + value + "' for property '" + "' not valid. Using default", pse); return defaultValue; } } /** * Set the given property to <code>Pattern</code>. * If the pattern is passed as null, sets the empty pattern which results in * further calls to getPattern(...) returning the default value. * * @param pattern new value */ public void setPattern(Pattern pattern) { if (null == pattern) { set(null); } else { set(pattern.pattern()); } } /** * Parse the given attribute as a set of integer ranges * * @param defaultValue the default value if it is not set * @return a new set of ranges from the configured value */ public IntegerRanges getRange(String defaultValue) { return new IntegerRanges(get(defaultValue)); } /** * Get the comma delimited values of property as * a collection of <code>String</code>s. * If no such property is specified then empty collection is returned. * <p> * * @return property value as a collection of <code>String</code>s. */ public Collection<String> getStringCollection() { return Strings.getStringCollection(value); } /** * <p>getPair.</p> * * @param defaultValue a {@link org.apache.commons.lang3.tuple.Pair} object. * @return a {@link org.apache.commons.lang3.tuple.Pair} object. */ public Pair<String, String> getPair(Pair<String, String> defaultValue) { if (value == null) { return defaultValue; } int pos = value.indexOf(":"); if (pos > 0 && pos < value.length() - 1) { return Pair.of(value.substring(0, pos), value.substring(pos)); } return defaultValue; } /** * <p>getKvs.</p> * * @return a {@link java.util.Map} object. */ public Map<String, String> getKvs() { return getKvs("[\\s+|,]", ":"); } /** * <p>getKvs.</p> * * @param kvDelimeter a {@link java.lang.String} object. * @return a {@link java.util.Map} object. */ public Map<String, String> getKvs(String kvDelimeter) { return getKvs("[\\s+|,]", kvDelimeter); } /** * <p>getKvs.</p> * * @param pairDelimeterPattern a {@link java.lang.String} object. * @param kvDelimeter a {@link java.lang.String} object. * @return a {@link java.util.Map} object. */ public Map<String, String> getKvs(String pairDelimeterPattern, String kvDelimeter) { Map<String, String> kvs = new HashMap<>(); if (value == null) { return kvs; } for (String s : value.split(pairDelimeterPattern)) { int pos = s.indexOf(kvDelimeter); if (pos > 0 && pos < s.length() - 1) { kvs.put(s.substring(0, pos), s.substring(pos + 1)); } } return kvs; } /** * Get the comma delimited values of property as * an array of <code>String</code>s. * If no such property is specified then <code>null</code> is returned. * * @return property value as an array of <code>String</code>s, * or <code>null</code>. */ public String[] getStrings() { return Strings.getStrings(value); } /** * Set the array of string values for property as * as comma delimited values. * * @param values The values */ public void setStrings(String... values) { set(Strings.arrayToString(values)); } /** * Get the comma delimited values of property as * an array of <code>String</code>s. * If no such property is specified then default value is returned. * * @param defaultValue The default value * @return property value as an array of <code>String</code>s, * or default value. */ public String[] getStrings(String... defaultValue) { if (value == null) { return defaultValue; } else { return Strings.getStrings(value); } } /** * Get the comma delimited values of property as * a collection of <code>String</code>s, trimmed of the leading and trailing whitespace. * If no such property is specified then empty <code>Collection</code> is returned. * * @return property value as a collection of <code>String</code>s, or empty <code>Collection</code> */ public Collection<String> getTrimmedStringCollection() { if (null == value) { return Collections.emptyList(); } return Strings.getTrimmedStringCollection(value); } /** * Get the comma delimited values of property as * an array of <code>String</code>s, trimmed of the leading and trailing whitespace. * If no such property is specified then an empty array is returned. * * @return property value as an array of trimmed <code>String</code>s, * or empty array. */ public String[] getTrimmedStrings() { return Strings.getTrimmedStrings(value); } /** * Get the comma delimited values of property as * an array of <code>String</code>s, trimmed of the leading and trailing whitespace. * If no such property is specified then default value is returned. * * @param defaultValue The default value * @return property value as an array of trimmed <code>String</code>s, * or default value. */ public String[] getTrimmedStrings(String... defaultValue) { if (null == value) { return defaultValue; } else { return Strings.getTrimmedStrings(value); } } /** * Get a unsigned integer, if the configured value is negative or not set, return the default value * * @param defaultValue The default value return if the configured value is negative * @return a positive integer */ public Integer getUint(int defaultValue) { int value = getInt(defaultValue); if (value < 0) { value = defaultValue; } return value; } /** * Get a unsigned long integer, if the configured value is negative, return the default value * * @param defaultValue The default value return if the configured value is negative * @return a positive long integer */ public Long getUlong(long defaultValue) { Long value = getLong(defaultValue); if (value < 0) { value = defaultValue; } return value; } /** * <p>setIfNotNull.</p> * * @param value a {@link java.lang.String} object. */ public void setIfNotNull(String value) { if (value != null) { set(value); } } /** * <p>setIfNotEmpty.</p> * * @param value a {@link java.lang.String} object. */ public void setIfNotEmpty(String value) { if (value != null && !value.isEmpty()) { set(value); } } /** * Support both ISO-8601 standard and hadoop time duration format * ISO-8601 standard : PnDTnHnMn.nS * Hadoop time duration format : Valid units are : ns, us, ms, s, m, h, d. * * @param defaultValue a {@link java.time.Duration} object. * @return a {@link java.time.Duration} object. */ public Duration getDuration(Duration defaultValue) { if (value == null || value.length() < 2) { return defaultValue; } String upperCase = value.toUpperCase(); try { if (upperCase.startsWith("P") || upperCase.startsWith("-P")) { try { return Duration.parse(upperCase); } catch (Throwable ignored) { return defaultValue; } } // Can not use TimeUnit.SECONDS because of unacceptable precision long value = getTimeDuration(Integer.MIN_VALUE, TimeUnit.MILLISECONDS); if (value == Integer.MIN_VALUE) { return defaultValue; } return Duration.ofMillis(value); } catch (Throwable e) { return defaultValue; } } /** * Retrieves the duration. * <p> * This method obtains the duration by invoking another overloaded getDuration method. * It uses a constant named INVALID_DURATION as a default value, indicating that if a valid duration cannot be * obtained, an invalid Duration object will be returned. * <p> * Support both ISO-8601 standard and hadoop time duration format * <p> * * ISO-8601 standard : PnDTnHnMn.nS * * Hadoop time duration format : Valid units are : ns, us, ms, s, m, h, d. * <p> * Note: for hadoop time duration format, the unit is always lowercase, and only single unit is allowed. * * @return A Duration object representing the duration of a process. If a valid duration cannot be obtained, * it returns an object representing an invalid duration. */ public Duration getDuration() { return getDuration(INVALID_DURATION); } /** * Try to detect a date time from the text and convert it to be a instant * If no date time detected, return Instant.EPOCH */ public Instant getInstant() { return getInstant(Instant.EPOCH); } /** * Try to detect a date time from the text and convert it to be a instant * If no date time detected, return defaultValue * * Accept the following format: * 1. yyyy-MM-dd[ HH[:mm[:ss]]] * 2. ISO_INSTANT, or yyyy-MM-ddTHH:mm:ssZ */ public Instant getInstant(Instant defaultValue) { if (value == null) { return defaultValue; } if (NumberUtils.isDigits(value)) { return Instant.ofEpochMilli(getLong(defaultValue.toEpochMilli())); } return DateTimes.parseBestInstant(value); } public Path getPath(Path defaultValue, boolean createDirectories) throws IOException { Path path = (value != null) ? Paths.get(value) : defaultValue; if (createDirectories) { Files.createDirectories(path.getParent()); } return path; } public Path getPath(Path defaultValue) { try { Path path = (value != null) ? Paths.get(value) : defaultValue; Files.createDirectories(path.getParent()); return path; } catch (Throwable ignored) { } return defaultValue; } @Nullable public Path getPathOrNull() { try { if (value != null) { Path path = Paths.get(value); Files.createDirectories(path.getParent()); return path; } } catch (Throwable ignored) { } return null; } /** * Load a class by name. * * @param name The class name * @return the class object. * @throws java.lang.ClassNotFoundException if the class is not found. */ public Class<?> getClassByName(String name) throws ClassNotFoundException { Class<?> ret = getClassByNameOrNull(name); if (ret == null) { throw new ClassNotFoundException("Class " + name + " not found"); } return ret; } /** * Load a class by name, returning null rather than throwing an exception * if it couldn't be loaded. This is to avoid the overhead of creating * an exception. * * @param name the class name * @return the class object, or null if it could not be found. */ public Class<?> getClassByNameOrNull(String name) { Map<String, WeakReference<Class<?>>> map; synchronized (CACHE_CLASSES) { map = CACHE_CLASSES.computeIfAbsent(classLoader, k -> Collections.synchronizedMap(new WeakHashMap<>())); } Class<?> clazz = null; WeakReference<Class<?>> ref = map.get(name); if (ref != null) { clazz = ref.get(); } if (clazz == null) { try { // clazz = ResourceLoader.INSTANCE.loadUserClass(name); clazz = Class.forName(name, true, classLoader); } catch (ClassNotFoundException e) { // Leave a marker that the class isn't found map.put(name, new WeakReference<>(NEGATIVE_CACHE_SENTINEL)); return null; } // two putters can race here, but they'll put the same class map.put(name, new WeakReference<>(clazz)); return clazz; } else if (clazz == NEGATIVE_CACHE_SENTINEL) { return null; // not found } else { // cache hit return clazz; } } /** * Get the value of property * as an array of <code>Class</code>. * The value of the property specifies a list of comma separated class names. * If no such property is specified, then <code>defaultValue</code> is * returned. * * @param defaultValue default value. * @return property value as a <code>Class[]</code>, * or <code>defaultValue</code>. */ public Class<?>[] getClasses(Class<?>... defaultValue) { String[] classnames = getTrimmedStrings(); if (classnames == null) return defaultValue; try { Class<?>[] classes = new Class<?>[classnames.length]; for (int i = 0; i < classnames.length; i++) { classes[i] = getClassByName(classnames[i]); } return classes; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * Get the value as a <code>Class</code>. * If no such property is specified, then <code>defaultValue</code> is * returned. * * @param defaultValue default value. * @return property value as a <code>Class</code>, * or <code>defaultValue</code>. */ public Class<?> getClass(Class<?> defaultValue) { String valueString = getTrimmed(); if (valueString == null) return defaultValue; try { return getClassByName(valueString); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * Set the value to <code>theClass</code> implementing the given interface <code>xface</code>. * <p> * If no such property is specified, then <code>defaultValue</code> is * returned. * <p> * An exception is thrown if the returned class does not implement the named * interface. * * @param defaultValue default value. * @param xface the interface implemented by the named class. * @param <U> The base class * @return property value as a <code>Class</code>, * or <code>defaultValue</code>. */ public <U> Class<? extends U> getClass(Class<? extends U> defaultValue, Class<U> xface) { try { Class<?> theClass = getClass(defaultValue); if (theClass != null && !xface.isAssignableFrom(theClass)) throw new RuntimeException(theClass + " not " + xface.getName()); else if (theClass != null) return theClass.asSubclass(xface); else return null; } catch (Exception e) { throw new RuntimeException(e); } } /** * Set the value to <code>theClass</code> implementing the given interface <code>xface</code>. * <p> * An exception is thrown if <code>theClass</code> does not implement the * interface <code>xface</code>. * * @param theClass property value. * @param xface the interface implemented by the named class. */ public void setClass(Class<?> theClass, Class<?> xface) { if (!xface.isAssignableFrom(theClass)) throw new RuntimeException(theClass + " not " + xface.getName()); set(theClass.getName()); } /** * Get a local file name under a directory named in <i>dirsProp</i> with * the given <i>path</i>. If <i>dirsProp</i> contains multiple directories, * then one is chosen based on <i>path</i>'s hash code. If the selected * directory does not exist, an attempt is made to create it. * * @param dirsProp directory in which to locate the file. * @param path file-path. * @return local file under the directory with the given path. * @throws java.io.IOException If no valid local directories */ public File getFile(String dirsProp, String path) throws IOException { String[] dirs = getTrimmedStrings(dirsProp); int hashCode = path.hashCode(); for (int i = 0; i < dirs.length; i++) { // try each local dir int index = (hashCode + i & Integer.MAX_VALUE) % dirs.length; File file = new File(dirs[index], path); File dir = file.getParentFile(); if (dir.exists() || dir.mkdirs()) { return file; } } throw new IOException("No valid local directories in property: " + dirsProp); } /** * Get the {@link java.net.URL} for the named resource. * * @return the url for the named resource. */ public URL getResource() { return classLoader.getResource(value); } /** * Get an input stream * * @return an input stream attached to the resource. */ public InputStream getResourceAsInputStream() { try { URL url = getResource(); if (url == null) { LOG.info(value + " not found"); return null; } else { LOG.info("found resource " + value + " at " + url); } return url.openStream(); } catch (Exception e) { return null; } } /** * Get a {@link java.io.Reader} * * @return a reader attached to the resource. */ public Reader getResourceAsReader() { try { URL url = getResource(); if (url == null) { LOG.info(value + " not found"); return null; } else { LOG.info("found resource " + value + " at " + url); } return new InputStreamReader(url.openStream()); } catch (Exception e) { return null; } } /** * Get the {@link java.lang.ClassLoader} for this job. * * @return the correct class loader. */ public ClassLoader getClassLoader() { return classLoader; } /** * Set the class loader that will be used to load the various objects. * * @param classLoader the new class loader. */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } private String substituteVars(String expr) { if (expr == null) { return null; } Matcher match = VAR_PATTERN.matcher(""); String eval = expr; for (int s = 0; s < MAX_SUBST; s++) { match.reset(eval); if (!match.find()) { return eval; } String var = match.group(); var = var.substring(2, var.length() - 1); // remove ${ .. } String val = null; try { val = System.getProperty(var); } catch (SecurityException se) { LOG.warn("Unexpected SecurityException in Configuration", se); } if (val == null) { val = getRaw(); } if (val == null) { return eval; // return literal ${var}: var is unbound } // substitute eval = eval.substring(0, match.start()) + val + eval.substring(match.end()); } throw new IllegalArgumentException("Variable substitution depth too large: " + MAX_SUBST + " " + expr); } enum ParsedTimeDuration { NS { TimeUnit unit() { return TimeUnit.NANOSECONDS; } String suffix() { return "ns"; } }, US { TimeUnit unit() { return TimeUnit.MICROSECONDS; } String suffix() { return "us"; } }, MS { TimeUnit unit() { return TimeUnit.MILLISECONDS; } String suffix() { return "ms"; } }, S { TimeUnit unit() { return TimeUnit.SECONDS; } String suffix() { return "s"; } }, M { TimeUnit unit() { return TimeUnit.MINUTES; } String suffix() { return "m"; } }, H { TimeUnit unit() { return TimeUnit.HOURS; } String suffix() { return "h"; } }, D { TimeUnit unit() { return TimeUnit.DAYS; } String suffix() { return "d"; } }; static ParsedTimeDuration unitFor(String s) { for (ParsedTimeDuration ptd : values()) { // iteration order is in decl order, so SECONDS matched last if (s.endsWith(ptd.suffix())) { return ptd; } } return null; } static ParsedTimeDuration unitFor(TimeUnit unit) { for (ParsedTimeDuration ptd : values()) { if (ptd.unit() == unit) { return ptd; } } return null; } abstract TimeUnit unit(); abstract String suffix(); } private static abstract class NegativeCacheSentinel { } /** * A class that represents a set of positive integer ranges. It parses * strings of the form: "2-3,5,7-" where ranges are separated by comma and * the lower/upper bounds are separated by dash. Either the lower or upper * bound may be omitted meaning all values up to or over. So the string * above means 2, 3, 5, and 7, 8, 9, ... */ public static class IntegerRanges implements Iterable<Integer> { List<IntegerRanges.Range> ranges = new ArrayList<IntegerRanges.Range>(); public IntegerRanges() { } public IntegerRanges(String newValue) { StringTokenizer itr = new StringTokenizer(newValue, ","); while (itr.hasMoreTokens()) { String rng = itr.nextToken().trim(); String[] parts = rng.split("-", 3); if (parts.length < 1 || parts.length > 2) { throw new IllegalArgumentException("integer range badly formed: " + rng); } IntegerRanges.Range r = new IntegerRanges.Range(); r.start = convertToInt(parts[0], 0); if (parts.length == 2) { r.end = convertToInt(parts[1], Integer.MAX_VALUE); } else { r.end = r.start; } if (r.start > r.end) { throw new IllegalArgumentException("IntegerRange from " + r.start + " to " + r.end + " is invalid"); } ranges.add(r); } } /** * Convert a string to an int treating empty strings as the default value. * * @param value the string value * @param defaultValue the value for if the string is empty * @return the desired integer */ private static int convertToInt(String value, int defaultValue) { String trim = value.trim(); if (trim.length() == 0) { return defaultValue; } return Integer.parseInt(trim); } /** * Is the given value in the set of ranges * * @param value the value to check * @return is the value in the ranges? */ public boolean isIncluded(int value) { for (IntegerRanges.Range r : ranges) { if (r.start <= value && value <= r.end) { return true; } } return false; } /** * @return true if there are no values in this range, else false. */ public boolean isEmpty() { return ranges == null || ranges.isEmpty(); } @Override public String toString() { StringBuilder result = new StringBuilder(); boolean first = true; for (IntegerRanges.Range r : ranges) { if (first) { first = false; } else { result.append(','); } result.append(r.start); result.append('-'); result.append(r.end); } return result.toString(); } @Override public Iterator<Integer> iterator() { return new IntegerRanges.RangeNumberIterator(ranges); } private static class Range { int start; int end; } private static class RangeNumberIterator implements Iterator<Integer> { Iterator<IntegerRanges.Range> internal; int at; int end; public RangeNumberIterator(List<IntegerRanges.Range> ranges) { if (ranges != null) { internal = ranges.iterator(); } at = -1; end = -2; } @Override public boolean hasNext() { if (at <= end) { return true; } else if (internal != null) { return internal.hasNext(); } return false; } @Override public Integer next() { if (at <= end) { at++; return at - 1; } else if (internal != null) { IntegerRanges.Range found = internal.next(); if (found != null) { at = found.start; end = found.end; at++; return at - 1; } } return null; } @Override public void remove() { throw new UnsupportedOperationException(); } } } /** * The traditional binary prefixes, kilo, mega, ..., exa, * which can be represented by a 64-bit integer. * TraditionalBinaryPrefix symbol are case insensitive. */ public enum TraditionalBinaryPrefix { KILO(10), MEGA(KILO.bitShift + 10), GIGA(MEGA.bitShift + 10), TERA(GIGA.bitShift + 10), PETA(TERA.bitShift + 10), EXA(PETA.bitShift + 10); public final long value; public final char symbol; public final int bitShift; public final long bitMask; TraditionalBinaryPrefix(int bitShift) { this.bitShift = bitShift; this.value = 1L << bitShift; this.bitMask = this.value - 1L; this.symbol = toString().charAt(0); } /** * @param symbol The symbol * @return The TraditionalBinaryPrefix object corresponding to the symbol. */ public static TraditionalBinaryPrefix valueOf(char symbol) { symbol = Character.toUpperCase(symbol); for (TraditionalBinaryPrefix prefix : TraditionalBinaryPrefix.values()) { if (symbol == prefix.symbol) { return prefix; } } throw new IllegalArgumentException("Unknown symbol '" + symbol + "'"); } /** * Convert a string to long. * The input string is first be trimmed * and then it is parsed with traditional binary prefix. * <p> * For example, * "-1230k" will be converted to -1230 * 1024 = -1259520; * "891g" will be converted to 891 * 1024^3 = 956703965184; * * @param s input string * @return a long value represented by the input string. */ public static long string2long(String s) { s = s.trim(); final int lastpos = s.length() - 1; final char lastchar = s.charAt(lastpos); if (Character.isDigit(lastchar)) return Long.parseLong(s); else { long prefix; try { prefix = TraditionalBinaryPrefix.valueOf(lastchar).value; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid size prefix '" + lastchar + "' in '" + s + "'. Allowed prefixes are k, m, g, t, p, e(case insensitive)"); } long num = Long.parseLong(s.substring(0, lastpos)); if (num > (Long.MAX_VALUE / prefix) || num < (Long.MIN_VALUE / prefix)) { throw new IllegalArgumentException(s + " does not fit in a Long"); } return num * prefix; } } /** * Convert a long integer to a string with traditional binary prefix. * * @param n the value to be converted * @param unit The unit, e.g. "B" for bytes. * @param decimalPlaces The number of decimal places. * @return a string with traditional binary prefix. */ public static String long2String(long n, String unit, int decimalPlaces) { if (unit == null) { unit = ""; } //take care a special case if (n == Long.MIN_VALUE) { return "-8 " + EXA.symbol + unit; } final StringBuilder b = new StringBuilder(); //take care negative numbers if (n < 0) { b.append('-'); n = -n; } if (n < KILO.value) { //no prefix b.append(n); return (unit.isEmpty() ? b : b.append(" ").append(unit)).toString(); } else { //find traditional binary prefix int i = 0; for (; i < values().length && n >= values()[i].value; i++) ; TraditionalBinaryPrefix prefix = values()[i - 1]; if ((n & prefix.bitMask) == 0) { //exact division b.append(n >> prefix.bitShift); } else { final String format = "%." + decimalPlaces + "f"; String s = format(format, n / (double) prefix.value); //check a special rounding up case if (s.startsWith("1024")) { prefix = values()[i]; s = format(format, n / (double) prefix.value); } b.append(s); } return b.append(' ').append(prefix.symbol).append(unit).toString(); } } } /** * The same as String.format(Locale.ENGLISH, format, objects). */ private static String format(final String format, final Object... objects) { return String.format(Locale.ENGLISH, format, objects); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/ScoreEntry.java
package ai.platon.pulsar.common; import ai.platon.pulsar.common.config.Params; import javax.annotation.Nonnull; /** * Created by vincent on 17-4-20. * Copyright @ 2013-2023 Platon AI. All rights reserved * * @author vincent * @version $Id: $Id */ public class ScoreEntry implements Comparable<ScoreEntry> { public static final int DEFAULT_DIGITS = 5; private String name; private int priority; private int value; // Reserved for optimization private int digits = DEFAULT_DIGITS; /** * <p>Constructor for ScoreEntry.</p> * * @param name a {@link java.lang.String} object. * @param value a int. */ public ScoreEntry(String name, int value) { this(name, 0, value, DEFAULT_DIGITS); } /** * <p>Constructor for ScoreEntry.</p> * * @param name a {@link java.lang.String} object. * @param priority a int. * @param value a int. */ public ScoreEntry(String name, int priority, int value) { this(name, priority, value, DEFAULT_DIGITS); } /** * <p>Constructor for ScoreEntry.</p> * * @param name a {@link java.lang.String} object. * @param priority a int. * @param value a int. * @param digits a int. */ public ScoreEntry(String name, int priority, int value, int digits) { this.name = name; this.priority = priority; this.value = value; this.digits = digits; } /** * <p>Constructor for ScoreEntry.</p> * * @param other a {@link ai.platon.pulsar.common.ScoreEntry} object. */ public ScoreEntry(ScoreEntry other) { this.name = other.name; this.priority = other.priority; this.value = other.value; this.digits = other.digits; } /** * <p>Getter for the field <code>name</code>.</p> * * @return a {@link java.lang.String} object. */ public String getName() { return name; } /** * <p>Setter for the field <code>name</code>.</p> * * @param name a {@link java.lang.String} object. */ public void setName(String name) { this.name = name; } /** * <p>Getter for the field <code>priority</code>.</p> * * @return a int. */ public int getPriority() { return priority; } /** * <p>Setter for the field <code>priority</code>.</p> * * @param priority a int. */ public void setPriority(int priority) { this.priority = priority; } /** * <p>Getter for the field <code>value</code>.</p> * * @return a int. */ public int getValue() { return value; } /** * <p>Setter for the field <code>value</code>.</p> * * @param value a int. */ public void setValue(int value) { this.value = value; } /** * <p>Getter for the field <code>digits</code>.</p> * * @return a int. */ public int getDigits() { return digits; } /** * <p>Setter for the field <code>digits</code>.</p> * * @param digits a int. */ public void setDigits(int digits) { this.digits = digits; } /** {@inheritDoc} */ @Override public ScoreEntry clone() { return new ScoreEntry(name, priority, value, digits); } /** {@inheritDoc} */ @Override public String toString() { return Params.formatAsLine( "name", name, "priority", priority, "value", value, "digits", digits ); } /** {@inheritDoc} */ @Override public boolean equals(Object other) { if (this == other) { return true; } return other instanceof ScoreEntry && compareTo((ScoreEntry) other) == 0; } /** {@inheritDoc} */ @Override public int compareTo(@Nonnull ScoreEntry scoreEntry) { int diff = priority - scoreEntry.priority; if (diff != 0) { return diff; } return value - scoreEntry.value; } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/ScoreVector.java
package ai.platon.pulsar.common; import com.google.common.primitives.Ints; import org.apache.commons.math3.analysis.function.Sigmoid; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; /** * Created by vincent on 17-4-20. * Copyright @ 2013-2023 Platon AI. All rights reserved * * @author vincent * @version $Id: $Id */ public class ScoreVector implements Comparable<ScoreVector> { // Reserved private final int dimension; private final ArrayList<ScoreEntry> entries; public static ScoreVector ZERO = new ScoreVector(0); /** * Create zero score vector with dimension {dimension} * * @param dimension a int. */ public ScoreVector(int dimension) { this.dimension = dimension; entries = new ArrayList<>(dimension); for (int i = 0; i < dimension; ++i) { entries.add(new ScoreEntry("s" + i, i, 0, 0)); } } /** * <p>Constructor for ScoreVector.</p> * * @param dimensionStr The string representation of a integer * Use string just to explicitly say it's not a score * @param scores Score value for each dimension, the size */ public ScoreVector(String dimensionStr, int... scores) { this(Integer.parseInt(dimensionStr), Ints.asList(scores)); } /** * <p>Constructor for ScoreVector.</p> * * @param dimension a int. * @param scores a {@link java.util.Collection} object. */ public ScoreVector(int dimension, Collection<Integer> scores) { Integer[] list = scores.toArray(new Integer[0]); if (dimension != list.length) { throw new IllegalArgumentException("Illegal dimension"); } this.dimension = dimension; entries = new ArrayList<>(dimension); for (int i = 0; i < dimension; ++i) { entries.add(new ScoreEntry("s" + i, i, list[i], 0)); } } /** * <p>Constructor for ScoreVector.</p> * * @param dimension a int. * @param scores a {@link ai.platon.pulsar.common.ScoreEntry} object. */ public ScoreVector(int dimension, ScoreEntry... scores) { if (dimension != scores.length) { throw new IllegalArgumentException("Illegal dimension"); } this.dimension = dimension; entries = new ArrayList<>(dimension); entries.addAll(Arrays.asList(scores)); } /** * <p>Constructor for ScoreVector.</p> * * @param dimension a int. * @param scores a {@link java.util.List} object. */ public ScoreVector(int dimension, List<ScoreEntry> scores) { if (dimension != scores.size()) { throw new IllegalArgumentException("Illegal dimension"); } this.dimension = dimension; entries = new ArrayList<>(scores); } /** * <p>create.</p> * * @param template a {@link ai.platon.pulsar.common.ScoreVector} object. * @return a {@link ai.platon.pulsar.common.ScoreVector} object. */ public static ScoreVector create(ScoreVector template) { List<ScoreEntry> newEntries = template.entries.stream().map(ScoreEntry::clone).collect(Collectors.toList()); newEntries.forEach(scoreEntry -> scoreEntry.setValue(0)); return new ScoreVector(template.dimension, newEntries); } /** * <p>parse.</p> * * @param multiValueScore a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.ScoreVector} object. * @throws java.util.IllegalFormatException if any. */ public static ScoreVector parse(String multiValueScore) throws IllegalFormatException { String[] parts = multiValueScore.split(","); ScoreVector score = new ScoreVector(parts.length); for (int i = 0; i < parts.length; ++i) { score.setValue(i, Integer.parseInt(parts[i])); } return score; } /** * <p>combine.</p> * * @param s1 a {@link ai.platon.pulsar.common.ScoreVector} object. * @param s2 a {@link ai.platon.pulsar.common.ScoreVector} object. * @return a {@link ai.platon.pulsar.common.ScoreVector} object. */ public static ScoreVector combine(ScoreVector s1, ScoreVector s2) { List<ScoreEntry> entries = new ArrayList<>(); entries.addAll(s1.entries); entries.addAll(s2.entries); return new ScoreVector(entries.size(), entries); } /** * <p>add.</p> * * @param scores a {@link ai.platon.pulsar.common.ScoreVector} object. * @return a {@link ai.platon.pulsar.common.ScoreVector} object. */ public static ScoreVector add(ScoreVector... scores) { List<ScoreEntry> entries = new ArrayList<>(); for (ScoreVector score : scores) { entries.addAll(score.entries); } return new ScoreVector(entries.size(), entries); } /** * <p>Getter for the field <code>entries</code>.</p> * * @return a {@link java.util.List} object. */ public List<ScoreEntry> getEntries() { return entries; } /** * <p>Getter for the field <code>dimension</code>.</p> * * @return a int. */ public int getDimension() { return dimension; } /** * <p>getDigits.</p> * * @return a int. */ public int getDigits() { return entries.stream().mapToInt(ScoreEntry::getDigits).sum(); } /** * <p>size.</p> * * @return a int. */ public int size() { assert (dimension == entries.size()); return entries.size(); } /** * <p>setValue.</p> * * @param i a int. * @param value a int. */ public void setValue(int i, int value) { get(i).setValue(value); } /** * <p>setValue.</p> * * @param i a int. * @param value a float. */ public void setValue(int i, float value) { get(i).setValue((int) value); } /** * <p>setValue.</p> * * @param i a int. * @param value a double. */ public void setValue(int i, double value) { get(i).setValue((int) value); } /** * <p>setValue.</p> * * @param values a int. */ public void setValue(int... values) { for (int i = 0; i < values.length && i < entries.size(); ++i) { entries.get(i).setValue(values[i]); } } /** * <p>get.</p> * * @param i a int. * @return a {@link ai.platon.pulsar.common.ScoreEntry} object. */ public ScoreEntry get(int i) { return entries.get(i); } /** {@inheritDoc} */ @Override public ScoreVector clone() { List<ScoreEntry> newEntries = entries.stream().map(ScoreEntry::clone).collect(Collectors.toList()); return new ScoreVector(dimension, newEntries); } /** * TODO: numeric overflow, use bigint * * @return a double. */ public double toDouble() { // TODO: normalization Sigmoid sig = new Sigmoid(0, 1); double sum = 0.0; for (ScoreEntry entry : entries) { double s = entry.getValue(); s = sig.value(s); s = (int) Math.min(100 * s, 99); sum = 100 * sum + s; } return sum; } /** * {@inheritDoc} * * TODO : consider about the "bigger dimension, bigger value" semantics */ @Override public int compareTo(@Nonnull ScoreVector other) { if (size() != other.size()) { return size() - other.size(); } for (int i = 0; i < entries.size(); ++i) { ScoreEntry v1 = entries.get(i); ScoreEntry v2 = other.entries.get(i); int comp = v1.compareTo(v2); if (comp != 0) { return comp; } } return 0; } /** {@inheritDoc} */ @Override public int hashCode() { final int PRIME = 31; int hash = 1; for (ScoreEntry scoreEntry : entries) { hash = PRIME * hash + scoreEntry.getValue(); } return hash; } /** {@inheritDoc} */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof ScoreVector)) { return false; } return compareTo((ScoreVector) other) == 0; } /** {@inheritDoc} */ @Override public String toString() { return entries.stream().map(ScoreEntry::getValue).map(String::valueOf) .collect(Collectors.joining(",")); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/Strings.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.math.NumberUtils; import java.awt.event.KeyEvent; import java.nio.ByteBuffer; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; public final class Strings { final public static String[] emptyStringArray = {}; final public static char COMMA = ','; final public static String COMMA_STR = ","; final public static char FULL_WIDTH_COMMA = ','; final public static String FULL_WIDTH_COMMA_STR = ","; final public static char ESCAPE_CHAR = '\\'; // public static final Pattern HTML_CHARSET_PATTERN = Pattern.compile("^<meta(?!\\s*(?:name|value)\\s*=)(?:[^>]*?content\\s*=[\\s\"']*)?([^>]*?)[\\s\"';]*charset\\s*=[\\s\"']([a-zA-Z0-9]{3,8})([^\\s\"'(/>)]*)", CASE_INSENSITIVE); public static final Pattern HTML_CHARSET_PATTERN = Pattern.compile("^<meta.+charset\\s*=[\\s\"']*([a-zA-Z0-9\\-]{3,8})[\\s\"'/>]*", CASE_INSENSITIVE); public static final Pattern PRICE_PATTERN = Pattern.compile("[1-9](,{0,1}\\d+){0,8}(\\.\\d{1,2})|[1-9](,{0,1}\\d+){0,8}"); // all special chars on a standard keyboard public static final String DEFAULT_KEEP_CHARS = "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,./' \n\r\t"; public static final String HTML_TAG_REGEX = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; public static final String FLOAT_REGEX = "^([+-]?(\\d+\\.)?\\d+)$"; public static Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_REGEX); public static Pattern HTML_TAG_PATTERN = Pattern.compile(HTML_TAG_REGEX); public static final String NUMERIC_LIKE_REGEX = "^.{0,2}[-+]?[0-9]*\\.?[0-9]+.{0,2}$"; public static Pattern NUMERIC_LIKE_PATTERN = Pattern.compile(NUMERIC_LIKE_REGEX); public static final String MONEY_LIKE_REGEX = "^[¥¥$]?[0-9]+(\\.[0-9]{1,2})?$"; public static Pattern MONEY_LIKE_PATTERN = Pattern.compile(MONEY_LIKE_REGEX); public static final String CHINESE_PHONE_NUMBER_LIKE_REGEX = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,2,5-9])|(177))\\d{8}$"; public static Pattern CHINESE_PHONE_NUMBER_LIKE_PATTERN = Pattern.compile(CHINESE_PHONE_NUMBER_LIKE_REGEX); public static final String IP_PORT_REGEX = "^" + "(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}" // Domain name + "|" + "localhost" // localhost + "|" + "(([0-9]{1,3}\\.){3})[0-9]{1,3})" // Ip + ":" + "[0-9]{1,5}$"; // Port public static final Pattern IP_PORT_PATTERN = Pattern.compile(IP_PORT_REGEX); // Port public static final int CODE_KEYBOARD_WHITESPACE = 32; public static final int CODE_NBSP = 160; public static final String KEYBOARD_WHITESPACE = String.valueOf(CODE_KEYBOARD_WHITESPACE); // Html entity: {@code &nbsp;} looks just like a white space public static final String NBSP = String.valueOf(CODE_NBSP); public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; // memoised padding up to 10 public static final String[] padding = {"", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}; public static final Comparator<String> LongerFirstComparator = (s, s2) -> { int result = Integer.compare(s2.length(), s.length()); if (result == 0) return s.compareTo(s2); return result; }; public static final Comparator<String> ShorterFirstComparator = (s, s2) -> LongerFirstComparator.compare(s2, s); public static final Pattern PatternTime = Pattern.compile("[0-2][0-3]:[0-5][0-9]"); public static int countTimeString(String text) { Matcher matcher = PatternTime.matcher(text); int count = 0; while (matcher.find()) count++; return count; } /** * Tests if a code point is "whitespace" as defined by what it looks like. Used for Element.text etc. * * @param c code point to test * @return true if code point is whitespace, false otherwise */ public static boolean isActuallyWhitespace(int c) { return c == CODE_KEYBOARD_WHITESPACE || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == CODE_NBSP; } /** * Convenience call for {@link #toHexString(ByteBuffer, String, int)}, where * <code>sep = null; lineLen = Integer.MAX_VALUE</code>. * * @param buf The byte buffer * @return The hex string */ public static String toHexString(ByteBuffer buf) { return toHexString(buf, null, Integer.MAX_VALUE); } /** * Get a text representation of a ByteBuffer as hexadecimal String, where each * pair of hexadecimal digits corresponds to consecutive bytes in the array. * * @param buf input data * @param sep separate every pair of hexadecimal digits with this separator, or * null if no separation is needed. * @param lineLen break the output String into lines containing output for lineLen * bytes. * @return The hex string */ public static String toHexString(ByteBuffer buf, String sep, int lineLen) { return toHexString(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining(), sep, lineLen); } /** * Convenience call for {@link #toHexString(byte[], String, int)}, where * <code>sep = null; lineLen = Integer.MAX_VALUE</code>. * * @param buf the buffer * @return a {@link java.lang.String} object. */ public static String toHexString(byte[] buf) { return toHexString(buf, null, Integer.MAX_VALUE); } /** * Get a text representation of a byte[] as hexadecimal String, where each * pair of hexadecimal digits corresponds to consecutive bytes in the array. * * @param buf input data * @param sep separate every pair of hexadecimal digits with this separator, or * null if no separation is needed. * @param lineLen break the output String into lines containing output for lineLen * bytes. * @return a {@link java.lang.String} object. */ public static String toHexString(byte[] buf, String sep, int lineLen) { return toHexString(buf, 0, buf.length, sep, lineLen); } /** * Get a text representation of a byte[] as hexadecimal String, where each * pair of hexadecimal digits corresponds to consecutive bytes in the array. * * @param buf input data * @param of the offset into the byte[] to start reading * @param cb the number of bytes to read from the byte[] * @param sep separate every pair of hexadecimal digits with this separator, or * null if no separation is needed. * @param lineLen break the output String into lines containing output for lineLen * bytes. * @return a {@link java.lang.String} object. */ public static String toHexString(byte[] buf, int of, int cb, String sep, int lineLen) { if (buf == null) return null; if (lineLen <= 0) lineLen = Integer.MAX_VALUE; StringBuffer res = new StringBuffer(cb * 2); for (int c = 0; c < cb; c++) { int b = buf[of++]; res.append(HEX_DIGITS[(b >> 4) & 0xf]); res.append(HEX_DIGITS[b & 0xf]); if (c > 0 && (c % lineLen) == 0) res.append('\n'); else if (sep != null && c < lineLen - 1) res.append(sep); } return res.toString(); } // 根据Unicode编码完美的判断中文汉字和符号 public static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION; } // 完整的判断中文汉字和符号 public static boolean isChinese(String text) { char[] ch = text.toCharArray(); for (char c : ch) { if (isChinese(c)) { return true; } } return false; } public static boolean isMainlyChinese(String text, double percentage) { if ("".equals(text)) return false; return 1.0 * countChinese(text) / text.length() >= percentage; } public static int countChinese(String text) { if ("".equals(text)) return 0; int count = 0; char[] ch = text.toCharArray(); for (char c : ch) { if (isChinese(c)) { ++count; } } return count; } // 只能判断部分CJK字符(CJK统一汉字) public static boolean isChineseByREG(String str) { if (str == null) { return false; } final Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+"); return pattern.matcher(str.trim()).find(); } // 只能判断部分CJK字符(CJK统一汉字) public static boolean isChineseCharByREG(char ch) { return ch >= '\u4E00' && ch <= '\u9FBF'; } // 只能判断部分CJK字符(CJK统一汉字) public static boolean isChineseByName(String str) { if (str == null) { return false; } // 大小写不同:\\p 表示包含,\\P 表示不包含 // \\p{Cn} 的意思为 Unicode 中未被定义字符的编码,\\P{Cn} 就表示 Unicode中已经被定义字符的编码 String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}"; Pattern pattern = Pattern.compile(reg); return pattern.matcher(str.trim()).find(); } // 对整个字符串: // 1. 仅保留英文字符、数字、汉字字符和keeps中的字符 // 2. 去除网页空白:&nbsp; // // String attrName = "配 送 至:京 东 价:当&nbsp;当&nbsp;价"; // attrName = StringUtils.strip(attrName).replaceAll("[\\s+::(&nbsp;)]", // ""); // the "blank" characters in the above phrase can not be stripped public static String removeNonChar(String text) { return removeNonChar(text, null); } /** * @deprecated Use {@link #removeNonChar(String)} instead */ public static String stripNonChar(String text) { return removeNonChar(text); } /** * @deprecated Use {@link #removeNonChar(String, String)} instead */ public static String stripNonChar(String text, String keeps) { return removeNonChar(text, keeps); } public static String removeNonChar(String text, String keeps) { StringBuilder builder = new StringBuilder(); if (keeps == null) { keeps = ""; } for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isChineseCharByREG(ch)) { builder.append(ch); } else if (!keeps.equals("") && keeps.indexOf(ch) != -1) { builder.append(ch); } } return builder.toString(); } public static String trimNonChar(String text) { return trimNonChar(text, null); } /** * // 对字符串的头部和尾部: * // 1. 仅保留英文字符、数字、汉字字符和keeps中的字符 * // 2. 去除网页空白:&nbsp; */ public static String trimNonChar(String text, String keeps) { int start = 0; int end = text.length(); if (keeps == null) keeps = ""; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isChineseCharByREG(ch) || keeps.indexOf(ch) != -1) { start = i; break; } } for (int i = text.length() - 1; i >= 0; --i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isChineseCharByREG(ch) || keeps.indexOf(ch) != -1) { end = i + 1; break; } } return text.substring(start, end); } public static boolean isCJK(char ch) { return Character.UnicodeBlock.of(ch) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS; } /** * 对整个字符串: * 1. 仅保留英文字符、数字、汉字字符和 keeps 中的字符 * 2. 去除网页空白:&nbsp; * String attrName = "配 送 至:京 东 价:当&nbsp;当&nbsp;价"; * attrName = StringUtils.strip(attrName).replaceAll("[\\s+::(&nbsp;)]", ""); * the "blank" characters in the above phrase can not be removed */ public static String removeNonCJKChar(String text) { return removeNonCJKChar(text, null); } public static String removeNonCJKChar(String text, String keeps) { StringBuilder builder = new StringBuilder(); if (keeps == null) { keeps = ""; } for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isCJK(ch)) { builder.append(ch); } else if (!keeps.isEmpty() && keeps.indexOf(ch) != -1) { builder.append(ch); } } return builder.toString(); } public static String trimNonCJKChar(String text) { return trimNonCJKChar(text, null); } /** * 对字符串的头部和尾部: * 1. 仅保留英文字符、数字、汉字字符和keeps中的字符 * 2. 去除网页空白:&nbsp; */ public static String trimNonCJKChar(String text, String keeps) { int start = 0; int end = text.length(); if (keeps == null) keeps = ""; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isCJK(ch) || keeps.indexOf(ch) != -1) { start = i; break; } } for (int i = text.length() - 1; i >= 0; --i) { char ch = text.charAt(i); if (Character.isLetterOrDigit(ch) || isCJK(ch) || keeps.indexOf(ch) != -1) { end = i + 1; break; } } return text.substring(start, end); } /** * Strip non-printable characters from a string. * * @param s the string to strip. * @return a new string with non-printable characters removed. */ public static String removeNonPrintableChar(String s) { if (s == null) { return null; } StringBuilder builder = new StringBuilder(); int len = s.length(); for (int i = 0; i < len; ++i) { char ch = s.charAt(i); if (isActuallyWhitespace(ch)) { if (i > 0 && i < len - 1) { builder.append(' '); } int j = i + 1; while (j < len && isActuallyWhitespace(s.charAt(j))) { ++j; } i = j - 1; } else if (isPrintableUnicodeChar(ch)) { builder.append(ch); } } return builder.toString(); } /** * @deprecated use {@link #removeNonPrintableChar(String)} instead. */ public static String stripNonPrintableChar1(String s) { return removeNonPrintableChar(s); } public static boolean isPrintableUnicodeChar(char ch) { Character.UnicodeBlock block = Character.UnicodeBlock.of(ch); return (!Character.isISOControl(ch)) && ch != KeyEvent.CHAR_UNDEFINED && block != null && block != Character.UnicodeBlock.SPECIALS; } public static String removeControlChars(String input) { return clearControlChars(input, ""); } public static String clearControlChars(String input) { return clearControlChars(input, " "); } public static String clearControlChars(String input, String replacement) { if (input == null) { return null; } return input.replaceAll("\\p{Cntrl}", replacement); } public static String getLongestPart(final String text, final Pattern pattern) { String[] parts = pattern.split(text); if (parts.length == 1) { return ""; } String longestPart = ""; for (String p : parts) { if (p.length() > longestPart.length()) { longestPart = p; } } if (longestPart.isEmpty()) { return ""; } else { return longestPart.trim(); } } public static String getLongestPart(final String text, final String regex) { return getLongestPart(text, Pattern.compile(regex)); } /** * See CaseFormat from Guava, for example, LOWER_UNDERSCORE.to(LOWER_CAMEL, str) */ public static String csslize(String text) { text = StringUtils.uncapitalize(text).trim(); text = StringUtils.join(text.split("(?=\\p{Upper})"), "-").toLowerCase(); text = text.replaceAll("[-_]+", "-"); text = text.replaceAll("\\s+", "-"); return text; } /** * See CaseFormat from Guava, for example, LOWER_UNDERSCORE.to(LOWER_CAMEL, str) */ public static String humanize(String text) { text = StringUtils.join(text.split("(?=\\p{Upper})"), " "); text = text.replaceAll("[-_]", " ").toLowerCase().trim(); return text; } /** * See CaseFormat from Guava, for example, LOWER_UNDERSCORE.to(LOWER_CAMEL, str) */ public static String humanize(String text, String seperator) { text = StringUtils.join(text.split("(?=\\p{Upper})"), seperator); text = text.replaceAll("[-_]", seperator).toLowerCase().trim(); return text; } /** * See CaseFormat from Guava, for example, LOWER_UNDERSCORE.to(LOWER_CAMEL, str) */ public static String humanize(String text, String suffix, String seperator) { text = StringUtils.join(text.split("(?=\\p{Upper})"), seperator); text = text.replaceAll("[-_]", seperator).toLowerCase().trim(); return text + seperator + suffix; } /** * See CaseFormat from Guava, for example, LOWER_UNDERSCORE.to(LOWER_CAMEL, str) */ public static String humanize(Class clazz, String suffix, String seperator) { String text = StringUtils.join(clazz.getSimpleName().split("(?=\\p{Upper})"), seperator); text = text.replaceAll("[-_]", seperator).toLowerCase().trim(); return text + seperator + suffix; } public static int getLeadingInteger(String s, int defaultValue) { int numberEnd = StringUtils.lastIndexOfAny(s, "123456789"); if (numberEnd == StringUtils.INDEX_NOT_FOUND) { return defaultValue; } return NumberUtils.toInt(s.substring(0, numberEnd), defaultValue); } public static int getTailingInteger(String s, int defaultValue) { int numberStart = StringUtils.indexOfAny(s, "123456789"); if (numberStart == StringUtils.INDEX_NOT_FOUND) { return defaultValue; } return NumberUtils.toInt(s.substring(numberStart), defaultValue); } public static int getFirstInteger(String s, int defaultValue) { var number = getFirstInteger(s); return number == null ? defaultValue : number; } /** * @deprecated use {@link #findFirstInteger(String)} instead */ public static Integer getFirstInteger(String s) { return findFirstInteger(s); } /** * Find the first integer in the string. * * @return the first integer in the string, or null if not found */ public static Integer findFirstInteger(String s) { if (s == null) { return null; } int numberStart = StringUtils.indexOfAny(s, "123456789"); if (numberStart == StringUtils.INDEX_NOT_FOUND) { return null; } StringBuilder sb = new StringBuilder(s.length() - numberStart); for (int i = numberStart; i < s.length(); ++i) { char c = s.charAt(i); if (Character.isDigit(c)) { sb.append(c); } else if (c == ',' || c == '_') { // skip number delimiter, 12,345,678 or java style 12_345_678 // nothing to do } else { break; } } return Integer.parseInt(sb.toString()); } public static int findFirstInteger(String s, int defaultValue) { return getFirstInteger(s, defaultValue); } /** * @deprecated use {@link #findLastInteger(String)} instead */ public static int getLastInteger(String s, int defaultValue) { return findLastInteger(s, defaultValue); } /** * Find the last integer in the string. * * @return the last integer in the string, or null if not found */ public static Integer findLastInteger(String s) { if (s == null) { return null; } s = s.replaceAll("[,_]", ""); s = StringUtils.reverse(s); Pattern pattern = Pattern.compile("[0-9]+"); Matcher m = pattern.matcher(s); if (m.find()) { return NumberUtils.toInt(StringUtils.reverse(m.group())); } return null; } public static int findLastInteger(String s, int defaultValue) { Integer number = findLastInteger(s); return number == null ? defaultValue : number; } public static float getFirstFloatNumber(String s, float defaultValue) { // number separators s = s.replaceAll("[,_]", ""); Pattern pattern = Pattern.compile("[+-]?[0-9]*\\.?,?[0-9]+"); Matcher m = pattern.matcher(s); if (m.find()) { return NumberUtils.toFloat(m.group()); } return defaultValue; } public static float findLastFloatNumber(String s, float defaultValue) { s = s.replaceAll("[,_]", ""); Pattern pattern = Pattern.compile("[+-]?[0-9]*\\.?,?[0-9]+"); Matcher m = pattern.matcher(s); if (m.find()) { return NumberUtils.toFloat(m.group(m.groupCount())); } return defaultValue; } public static boolean contains(String text, CharSequence... searchCharSequences) { Validate.notNull(searchCharSequences); for (CharSequence search : searchCharSequences) { if (!text.contains(search)) return false; } return true; } public static boolean containsAny(String text, CharSequence... searchCharSequences) { Validate.notNull(searchCharSequences); for (CharSequence search : searchCharSequences) { if (text.contains(search)) return true; } return false; } public static boolean containsNone(String text, CharSequence... searchCharSequences) { Validate.notNull(searchCharSequences); for (CharSequence search : searchCharSequences) { if (text.contains(search)) return false; } return true; } /** * @deprecated use {@link org.apache.commons.lang3.StringUtils#reverse(String)} instead */ @Deprecated public static String reverse(String s) { return StringUtils.reverse(s); } public static String doubleQuoteIfContainsWhitespace(String s) { if (StringUtils.containsWhitespace(s)) return "\"" + s + "\""; else return s; } /** * Formats a decimal number in its compact, readable form. * * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(int number) { return compactFormat(number, -1, false); } /** * Formats a decimal number in its compact, readable form. * * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(long number) { return compactFormat(number, -1, false); } /** * Formats a decimal number in its compact, readable form. * * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(int number, boolean si) { return compactFormat(number, -1, si); } /** * Formats a decimal number in its compact, readable form. * * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(long number, boolean si) { return compactFormat(number, -1, si); } /** * Formats a decimal number in its compact, readable form. * * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(int number, int scale, boolean si) { return compactFormat((long) number, scale, si); } /** * Formats a decimal number in its compact, readable form. * * @param number the number to format * @param scale the scale of the format result * @param si indicate if format to a SI unit * The International System Of Units (SI) is the metric system that is used * universally as a standard for measurements. SI units play a vital role in scientific * and technological research and development. * @return The formatted number * @see <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html"> * CompactNumberFormat</a> */ public static String compactFormat(long number, int scale, boolean si) { if (number < 0) { return "-" + compactFormat(-number, scale, si); } int unit = si ? 1000 : 1024; if (number < unit) { return number + " B"; } int exp = (int) (Math.log(number) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); String format = scale > 0 ? "%," + scale + ".2f %sB" : "%,.2f %sB"; return String.format(format, number / Math.pow(unit, exp), pre); } /** * Parse key-value pairs in a line, for example : * "a=1 b=2 c=3", "x:1 y:2 z:3" * * @param line The line to parse * @return The parsed result */ public static Map<String, String> parseKvs(String line) { return parseKvs(line, "="); } /** * Parse key-value pairs in a line, for example : * "a=1 b=2 c=3", "x:1 y:2 z:3" * * @param line The line to parse * @param delimiter a {@link java.lang.String} object. * @return The parsed result */ public static Map<String, String> parseKvs(String line, String delimiter) { return SParser.wrap(line).getKvs(delimiter); } /** * All lines separated by backslashes are merged together * * @param allLines All lines separated by "\n", some of them are separated by backslash * @return All lines separated by backslashes are merged */ public static List<String> getUnslashedLines(String allLines) { return mergeSlashedLines(Arrays.asList(allLines.split("\n"))); } /** * <p>getUnslashedLines.</p> * * @param allLines a {@link java.lang.String} object. * @param EOL a {@link java.lang.String} object. * @return a {@link java.util.List} object. */ public static List<String> getUnslashedLines(String allLines, String EOL) { return mergeSlashedLines(Arrays.asList(allLines.split(EOL))); } /** * Merge lines concatenated with backslash, for example : * The line "Java Stream API is very, very useful, \\\n" * " and we use them everywhere " * can be merged into "Java Stream API is very, very useful, and we use them everywhere" * * @param slashedLine a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public static String mergeSlashedLine(String slashedLine) { slashedLine = slashedLine.replaceAll("\n", ""); slashedLine = slashedLine.replaceAll("\\\\", ""); return slashedLine; } /** * All lines separated by backslashes are merged together * * @param linesWithSlash Lines with backslash * @return All lines separated by backslashes are merged */ public static List<String> mergeSlashedLines(Iterable<String> linesWithSlash) { List<String> lines = new ArrayList<>(); StringBuilder mergedLine = new StringBuilder(); boolean merging; for (String line : linesWithSlash) { line = line.trim(); if (line.isEmpty()) { continue; } if (line.endsWith("\\")) { merging = true; mergedLine.append(StringUtils.removeEnd(line, "\\")); } else { mergedLine.append(line); merging = false; } if (!merging) { if (!mergedLine.isEmpty()) { lines.add(mergedLine.toString()); mergedLine = new StringBuilder(); } } } return lines; } @Deprecated(forRemoval = true) public static int getLongestCommonSubstring(String a, String b) { int m = a.length(); int n = b.length(); int max = 0; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (a.charAt(i) == b.charAt(j)) { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j - 1] + 1; } if (max < dp[i][j]) max = dp[i][j]; } } } return max; } public static String replaceCharsetInHtml(String html, String charset) { Matcher matcher = HTML_CHARSET_PATTERN.matcher(html); if (matcher.find()) { html = html.replaceAll(matcher.group(1), charset); } return html; } public static String[] getStrings(String str) { Collection<String> values = getStringCollection(str); if (values.isEmpty()) { return null; } return values.toArray(new String[0]); } public static String arrayToString(String[] strs) { if (strs.length == 0) { return ""; } StringBuilder sbuf = new StringBuilder(); sbuf.append(strs[0]); for (int idx = 1; idx < strs.length; idx++) { sbuf.append(","); sbuf.append(strs[idx]); } return sbuf.toString(); } public static Collection<String> getStringCollection(String str) { String delim = ","; return getStringCollection(str, delim); } public static Collection<String> getStringCollection(String str, String delim) { List<String> values = new ArrayList<String>(); if (str == null) return values; StringTokenizer tokenizer = new StringTokenizer(str, delim); while (tokenizer.hasMoreTokens()) { values.add(tokenizer.nextToken()); } return values; } /** * Splits a comma separated value <code>String</code>, trimming leading and trailing whitespace on each value. * Duplicate and empty values are removed. * * @param str a comma separated string with values * @return a <code>Collection</code> of <code>String</code> values */ public static Collection<String> getTrimmedStringCollection(String str) { Set<String> set = new LinkedHashSet<String>(Arrays.asList(getTrimmedStrings(str))); set.remove(""); return set; } /** * Splits a comma separated value <code>String</code>, trimming leading and trailing whitespace on each value. * * @param str a comma separated String with values * @return an array of <code>String</code> values */ public static String[] getTrimmedStrings(String str) { if (null == str || str.trim().isEmpty()) { return emptyStringArray; } return str.trim().split("\\s*,\\s*"); } public static boolean hasHTMLTags(String text) { Matcher matcher = HTML_TAG_PATTERN.matcher(text); return matcher.find(); } public static boolean isFloat(String text) { return FLOAT_PATTERN.matcher(text).matches(); } public static boolean isNumericLike(String text) { return NUMERIC_LIKE_PATTERN.matcher(text).matches(); } /** * <a href="https://www.regextester.com/97725">regextester</a> * * @param text a {@link String} object. * @return a boolean. */ public static boolean isMoneyLike(String text) { return MONEY_LIKE_PATTERN.matcher(text).matches(); } /** * <p>isIpPortLike.</p> * * @param text a {@link java.lang.String} object. * @return a boolean. */ public static boolean isIpPortLike(String text) { return IP_PORT_PATTERN.matcher(text).matches(); } /** * <p>isIpLike.</p> * * @param text a {@link java.lang.String} object. * @return a boolean. */ public static boolean isIpLike(String text) { return isIpV4Like(text); } public static boolean isIpV4Like(String text) { return text.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/package-info.java
/* * 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. */ /** * Miscellaneous utility classes. */ package ai.platon.pulsar.common;
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/config/AppConstants.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 ai.platon.pulsar.common.config; import ai.platon.pulsar.common.measure.ByteUnit; import java.awt.*; import java.time.Duration; import java.time.Instant; @SuppressWarnings("unused") public interface AppConstants { String PULSAR_CONTEXT_CONFIG_LOCATION = "classpath*:/pulsar-beans/app-context.xml"; String YES_STRING = "y"; String ALL_BATCHES = "all"; /** * The first non-null Unicode character is U+0001, which is the Start of Heading (SOH) character. * @link <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> * */ Character UNICODE_FIRST_CODE_POINT = '\u0001'; /** * The last Unicode character in the Unicode standard is U+10FFFF, which is the highest code point in Unicode. * @link <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> * */ Character UNICODE_LAST_CODE_POINT = '\uFFFF'; /** * An example of the shortest url * */ String SHORTEST_VALID_URL = "http://t.tt"; /** * The length of the shortest example url * */ int SHORTEST_VALID_URL_LENGTH = SHORTEST_VALID_URL.length(); /** * The example url * */ String EXAMPLE_URL = "http://example.com"; /** * The prefix of all pulsar specified urls * */ String INTERNAL_URL_PREFIX = "http://internal.pulsar.platon.ai"; /** * The url of the nil page * */ String NIL_PAGE_URL = INTERNAL_URL_PREFIX + "/nil"; /** * The url of the top page * */ String URL_TRACKER_HOME_URL = INTERNAL_URL_PREFIX + "/url/tracker"; /** * Storage * */ String MEM_STORE_CLASS = "org.apache.gora.memory.store.MemStore"; /** A minimal file backend store */ String FILE_BACKEND_STORE_CLASS = "ai.platon.pulsar.persist.gora.FileBackendPageStore"; String MONGO_STORE_CLASS = "org.apache.gora.mongodb.store.MongoStore"; String HBASE_STORE_CLASS = "org.apache.gora.hbase.store.HBaseStore"; // schema version 1.10.x // String WEBPAGE_SCHEMA = "webpage110"; /** * Schema version 1.12.x, has to be compatible with webpage110 * */ String WEBPAGE_SCHEMA = "webpage120"; /** * Fetch * */ int DISTANCE_INFINITE = 10000; Duration FETCH_TASK_TIMEOUT_DEFAULT = Duration.ofMinutes(10); /** * Parse * */ Instant TCP_IP_STANDARDIZED_TIME = Instant.parse("1982-01-01T00:00:00Z"); Instant MIN_ARTICLE_PUBLISH_TIME = Instant.parse("1995-01-01T00:00:00Z"); Duration DEFAULT_MAX_PARSE_TIME = Duration.ofSeconds(60); int MAX_LINK_PER_PAGE = 4000; /** * Local file commands * */ String CMD_PROXY_POOL_DUMP = "dump-proxy-pool"; String CMD_PROXY_FORCE_IDLE = "IPS-force-idle"; String CMD_PROXY_RECONNECT = "IPS-reconnect"; String CMD_PROXY_DISCONNECT = "IPS-disconnect"; /** * Browser * */ int DEFAULT_BROWSER_MAX_OPEN_TABS = 50; double BROWSER_TAB_REQUIRED_MEMORY = ByteUnit.GIB.toBytes(1.5); // at least 1.5 GiB to open a new tab double DEFAULT_BROWSER_RESERVED_MEMORY = ByteUnit.GIB.toBytes(2.0); // 3 GiB double DEFAULT_BROWSER_RESERVED_MEMORY_MIB = ByteUnit.BYTE.toMiB(DEFAULT_BROWSER_RESERVED_MEMORY); // 5 GiB Duration POLLING_DRIVER_TIMEOUT_DEFAULT = Duration.ofSeconds(60); Dimension DEFAULT_VIEW_PORT = new Dimension(1920, 1080); String PULSAR_META_INFORMATION_ID = "PulsarMetaInformation"; String PULSAR_META_INFORMATION_SELECTOR = "#" + PULSAR_META_INFORMATION_ID; String PULSAR_SCRIPT_SECTION_ID = "PulsarScriptSection"; String PULSAR_SCRIPT_SECTION_SELECTOR = "#" + PULSAR_SCRIPT_SECTION_ID; String PULSAR_DOCUMENT_NORMALIZED_URI = "normalizedURI"; String PULSAR_ATTR_HIDDEN = "_h"; String PULSAR_ATTR_OVERFLOW_HIDDEN = "_oh"; String PULSAR_ATTR_OVERFLOW_VISIBLE = "_visible"; String PULSAR_ATTR_ELEMENT_NODE_VI = "vi"; String PULSAR_ATTR_TEXT_NODE_VI = "tv"; String PULSAR_ATTR_COMPUTED_STYLE = "cs"; String PULSAR_ATTR_ELEMENT_NODE_DATA = "nd"; // Browser use tool String BROWSER_INTERACTIVE_ELEMENTS_SELECTOR = "a, button, input, select, textarea, " + "[role='button'], [role='link'], [onclick], [onmousedown], [onmouseup]"; /** * Other notable properties: * overflow * text-overflow * */ String CLIENT_JS_PROPERTY_NAMES = "font-size, color, background-color"; /** * Metrics * */ String DEFAULT_METRICS_NAME = "pulsar"; /** * SQL engine * */ String H2_SESSION_FACTORY = "ai.platon.pulsar.ql.h2.H2SessionFactory"; /** * Local file base url, the host is a fake host. * Consider just use http://localhost. * */ String LOCAL_FILE_BASE_URL = "http://localfile.org"; String BROWSER_SPECIFIC_URL_PREFIX = "http://browser-specific.org"; }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/config/CapabilityTypes.java
package ai.platon.pulsar.common.config; import com.google.common.annotations.Beta; /** * Created by vincent on 17-1-17. * Copyright @ 2013-2023 Platon AI. All rights reserved * * @author vincent * @version $Id: $Id */ public interface CapabilityTypes { /////////////////////////////////////////////////// // Common Parameters /** * The key to retrieve the application identity string, can be specified by system environment variable or system property. * * The default value is the current username. * */ String APP_ID_KEY = "app.ident"; /** * The key to retrieve the application name, can be specified by system environment variable or system property. * */ String APP_NAME_KEY = "app.name"; /** * The key to retrieve the profile, can be specified by system environment variable or system property. * */ String PROFILE_KEY = "profile"; /** * The key to retrieve the data directory, can be specified by system environment variable or system property. * */ String APP_DATA_DIR_KEY = "app.data.dir"; /** * The key to retrieve the base directory of the temporary files. * */ String APP_TMP_BASE_DIR_KEY = "app.tmp.base.dir"; /** * Main loop * */ String MAIN_LOOP_CONCURRENCY_OVERRIDE = "main.loop.concurrency.override"; String START = "start"; String LIMIT = "limit"; String BATCH_ID = "batch.id"; String PARAM_JOB_NAME = "job.name"; String FORCE = "force"; String RECENT_DAYS_WINDOW = "recent.days.window"; /** * Application metrics * */ String METRICS_ENABLED = "metrics.enabled"; /////////////////////////////////////////////////////////////////////////// // Crawl section String PAGE_EVENT_CLASS = "page.eventHandlers.class"; /////////////////////////////////////////////////////////////////////////// // Storage String STORAGE_CRAWL_ID = "storage.crawl.id"; String STORAGE_SCHEMA_WEBPAGE = "storage.schema.webpage"; String STORAGE_PREFERRED_SCHEMA_NAME = "preferred.schema.name"; String STORAGE_DATA_STORE_CLASS = "storage.data.store.class"; /////////////////////////////////////////////////////////////////////////// // Spring String APPLICATION_CONTEXT_CONFIG_LOCATION = "application.context.config.location"; /////////////////////////////////////////////////////////////////////////// // Load phrase /** * Deactivate the fetch component, ensuring that all pages are loaded exclusively from storage * and never fetched from the Internet. * <p> * If a page is not found in the local storage, return WebPageImpl.NIL. * */ String LOAD_DEACTIVATE_FETCH_COMPONENT = "load.deactivate.fetch.component"; /////////////////////////////////////////////////////////////////////////// // Fetch phrase String FETCH_CONCURRENCY = "fetch.concurrency"; String FETCH_TASK_TIMEOUT = "fetch.task.timeout"; String FETCH_MAX_HOST_FAILURES = "fetch.max.host.failures"; String FETCH_MAX_INTERVAL = "fetch.interval.max"; String FETCH_DEFAULT_INTERVAL = "fetch.default.interval"; /** * The maximum number of pages to export in fetch phrase. * */ String FETCH_PAGE_AUTO_EXPORT_LIMIT = "fetch.page.auto.export.limit"; /** * Fetch * */ String FETCH_PAGE_LOAD_TIMEOUT = "fetch.page.load.timeout"; String FETCH_SCRIPT_TIMEOUT = "fetch.script.timeout"; String FETCH_SCROLL_DOWN_COUNT = "fetch.scroll.down.count"; String FETCH_SCROLL_DOWN_INTERVAL = "fetch.scroll.down.interval"; String FETCH_CLIENT_JS_COMPUTED_STYLES = "fetch.browser.client.js.computed.styles"; String FETCH_CLIENT_JS_PROPERTY_NAMES = "fetch.browser.client.js.property.names"; String FETCH_MAX_CONTENT_LENGTH = "fetch.max.content.length"; /////////////////////////////////////////////////////////////////////////// // Privacy context /** * The mode of browser context, case-insensitive. * default, system_default, prototype, sequential, temporary */ String BROWSER_CONTEXT_MODE = "browser.context.mode"; /** * The number of active privacy contexts. */ String PRIVACY_CONTEXT_NUMBER = "privacy.context.number"; /** * The number of active privacy contexts. */ String BROWSER_CONTEXT_NUMBER = "browser.context.number"; /** * The minimal number of sequential privacy agents, the active privacy contexts is chosen from them. * */ String MIN_SEQUENTIAL_PRIVACY_AGENT_NUMBER = "min.sequential.privacy.agent.number"; /** * The maximum number of sequential privacy agents, the active privacy contexts is chosen from them. * */ String MAX_SEQUENTIAL_PRIVACY_AGENT_NUMBER = "max.sequential.privacy.agent.number"; /** * The class name of privacy agent generator * */ String PRIVACY_AGENT_GENERATOR_CLASS = "privacy.agent.generator.class"; String PRIVACY_MINOR_WARNING_FACTOR = "privacy.minor.warning.factor"; String PRIVACY_CONTEXT_IDLE_TIMEOUT = "privacy.idle.timeout"; String PRIVACY_CONTEXT_FAILURE_RATE_THRESHOLD = "privacy.failure.rate.threshold"; String PRIVACY_MAX_WARNINGS = "privacy.max.warnings"; String PRIVACY_CONTEXT_MIN_THROUGHPUT = "privacy.context.min.throughput"; /** * The strategy to close privacy context: asap, lazy * */ String PRIVACY_CONTEXT_CLOSE_LAZY = "privacy.close.strategy"; /////////////////////////////////////////////////////////////////////////// // Browser String CHROME_PATH = "chrome.path"; /** * The max value of tabs a browser can open * @deprecated use BROWSER_MAX_OPEN_TABS */ @Deprecated(since = "3.0.4") String BROWSER_MAX_ACTIVE_TABS = "browser.max.active.tabs"; /** * The max value of tabs a browser can open */ String BROWSER_MAX_OPEN_TABS = "browser.max.open.tabs"; /** * The web driver to use * */ String BROWSER_WEB_DRIVER_PRIORITY = "browser.web.driver.priority"; String BROWSER_DRIVER_POOL_IDLE_TIMEOUT = "browser.driver.pool.idle.timeout"; String BROWSER_TYPE = "browser.type"; @Beta String BROWSER_INCOGNITO = "browser.incognito"; /** * The browser interact settings * */ String BROWSER_INTERACT_SETTINGS = "browser.interact.settings"; String BROWSER_DISPLAY_MODE = "browser.display.mode"; String BROWSER_JS_INVADING_ENABLED = "browser.js.invading.enabled"; String BROWSER_DELETE_ALL_COOKIES = "browser.delete.all.cookies"; String BROWSER_RESPONSE_HANDLER = "browser.response.handler"; /** * The probability to block urls specified by {@code WebDriver.addBlockedURLs}, between [0, 1] * */ String BROWSER_RESOURCE_BLOCK_PROBABILITY = "browser.url.block.probability"; String BROWSER_ENABLE_UA_OVERRIDING = "browser.enable.ua.overriding"; String BROWSER_SPA_MODE = "browser.spa.mode"; /** * Whether reuse the recovered drivers to serve new tasks. * */ String BROWSER_REUSE_RECOVERED_DRIVERS = "browser.reuse.recovered.drivers"; /** * Add a --no-sandbox flag to launch the chrome if we are running inside a virtual machine, * for example, virtualbox, vmware or WSL * */ String BROWSER_LAUNCH_NO_SANDBOX = "browser.launch.no.sandbox"; String BROWSER_LAUNCH_SUPERVISOR_PROCESS = "browser.launch.supervisor.process"; String BROWSER_LAUNCH_SUPERVISOR_PROCESS_ARGS = "browser.launch.supervisor.process.args"; String POLLING_DRIVER_TIMEOUT = "polling.driver.timeout"; /////////////////////////////////////////////////////////////////////////// // Proxy /// String PROXY_POOL_MANAGER_CLASS = "proxy.pool.manager.class"; String PROXY_LOADER_CLASS = "proxy.loader.class"; String PROXY_PARSER_CLASS = "proxy.parser.class"; String PROXY_MAX_FETCH_SUCCESS = "proxy.max.fetch.success"; String PROXY_MAX_ALLOWED_PROXY_ABSENCE = "proxy.max.allowed.proxy.absence"; String PROXY_POOL_CAPACITY = "proxy.pool.size"; String PROXY_POOL_POLLING_TIMEOUT = "proxy.pool.polling.interval"; String PROXY_IDLE_TIMEOUT = "proxy.idle.timeout"; /** * The key used to retrieve a proxy rotation URL. Each time the URL is accessed, a new set of proxy IPs will be returned. * */ String PROXY_ROTATION_URL = "proxy.rotation.url"; /////////////////////////////////////////////////////////////////////////// // Network String HTTP_TIMEOUT = "http.timeout"; String HTTP_FETCH_MAX_RETRY = "http.fetch.max.retry"; /////////////////////////////////////////////////////////////////////////// // Parse phrase String PARSE_TIMEOUT = "parser.timeout"; String PARSE_MAX_URL_LENGTH = "parse.max.url.length"; String PARSE_MIN_ANCHOR_LENGTH = "parse.min.anchor.length"; String PARSE_MAX_ANCHOR_LENGTH = "parse.max.anchor.length"; String PARSE_SUPPORT_ALL_CHARSETS = "parser.support.all.charsets"; String PARSE_DEFAULT_ENCODING = "parser.character.encoding.default"; /////////////////////////////////////////////////////////////////////////// // LLM String LLM_PROVIDER = "llm.provider"; String LLM_NAME = "llm.name"; String LLM_API_KEY = "llm.apiKey"; /////////////////////////////////////////////////////////////////////////// // Other /** * Create default data collectors or not * */ String CRAWL_ENABLE_DEFAULT_DATA_COLLECTORS = "crawl.enable.default.data.collectors"; /** * Create default data collectors or not * */ String CRAWL_SMART_RETRY = "crawl.smart.retry"; /** * The size of global page cache * */ String GLOBAL_PAGE_CACHE_SIZE = "global.page.cache.size"; /** * The size of global document cache * */ String GLOBAL_DOCUMENT_CACHE_SIZE = "global.document.cache.size"; String PULSAR_DOMAIN = "pulsar.domain"; // H2 String H2_SESSION_FACTORY_CLASS = "h2.sessionFactory"; String SCENT_EXTRACT_TABULATE_CELL_TYPE = "scent.extract.tabulate.cell.type"; }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/config/Parameterized.java
package ai.platon.pulsar.common.config; /** * Created by vincent on 17-1-8. * * @author vincent * @version $Id: $Id */ public interface Parameterized { /** * <p>getParams.</p> * * @return a {@link ai.platon.pulsar.common.config.Params} object. */ default Params getParams() { return Params.EMPTY_PARAMS; } }
0
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common
java-sources/ai/platon/pulsar/pulsar-common/3.0.15/ai/platon/pulsar/common/config/Params.java
package ai.platon.pulsar.common.config; import ai.platon.pulsar.common.Strings; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Created by vincent on 16-9-24. * * @author vincent * @version $Id: $Id */ public class Params { /** * Constant <code>EMPTY_PARAMS</code> */ public static final Params EMPTY_PARAMS = new Params(); private Logger log = LoggerFactory.getLogger(Params.class); private List<Pair<String, Object>> paramsList = new LinkedList<>(); private String captionFormat = String.format("%20sParams Table%-25s\n", "----------", "----------"); private String headerFormat = String.format("%25s %-25s\n", "Name", "Value"); private String rowFormat = "%25s: %s"; private boolean cmdLineStyle = false; private List<String> distinctBooleanParams; private String pairDelimiter = " "; private String kvDelimiter = ": "; private Logger defaultLog = null; /** * <p>Constructor for Params.</p> */ public Params() { } /** * <p>Constructor for Params.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. */ public Params(String key, Object value, Object... others) { this.paramsList.addAll(toArgList(key, value, others)); } /** * <p>Constructor for Params.</p> * * @param args a {@link java.util.Map} object. */ public Params(Map<String, Object> args) { args.forEach((key, value) -> this.paramsList.add(Pair.of(key, value))); } /** * <p>of.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public static Params of(String key, Object value, Object... others) { return new Params(key, value, others); } /** * <p>of.</p> * * @param args a {@link java.util.Map} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public static Params of(Map<String, Object> args) { return new Params(args); } /** * <p>toArgList.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. * @return a {@link java.util.List} object. */ public static List<Pair<String, Object>> toArgList(String key, Object value, Object... others) { List<Pair<String, Object>> results = new LinkedList<>(); results.add(Pair.of(key, value)); if (others == null || others.length < 2) { return results; } if (others.length % 2 != 0) { throw new RuntimeException("expected name/value pairs"); } for (int i = 0; i < others.length; i += 2) { Object k = others[i]; Object v = others[i + 1]; if (k != null && v != null) { results.add(Pair.of(String.valueOf(others[i]), others[i + 1])); } } return results; } /** * Convert K/V pairs array into a map. * * @param others A K/V pairs array, the length of the array must be a even number * null key or null value pair is ignored * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @return A map contains all non-null key/values */ public static Map<String, Object> toArgMap(String key, Object value, Object... others) { Map<String, Object> results = new LinkedHashMap<>(); results.put(key, value); if (others == null || others.length < 2) { return results; } if (others.length % 2 != 0) { throw new RuntimeException("expected name/value pairs"); } for (int i = 0; i < others.length; i += 2) { Object k = others[i]; Object v = others[i + 1]; if (k != null && v != null) { results.put(String.valueOf(others[i]), others[i + 1]); } } return results; } /** * <p>formatAsLine.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. * @return a {@link java.lang.String} object. */ public static String formatAsLine(String key, Object value, Object... others) { return Params.of(key, value, others).formatAsLine(); } /** * <p>format.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. * @param others a {@link java.lang.Object} object. * @return a {@link java.lang.String} object. */ public static String format(String key, Object value, Object... others) { return Params.of(key, value, others).format(); } /** * <p>put.</p> * * @param name a {@link java.lang.String} object. * @param value a {@link java.lang.Object} object. */ public void put(String name, Object value) { paramsList.add(Pair.of(name, value)); } /** * <p>remove.</p> * * @param key a {@link java.lang.String} object. * @return a boolean. */ public boolean remove(String key) { List<Pair<String, Object>> list = paramsList.stream().filter(entry -> !entry.getKey().equals(key)).collect(Collectors.toList()); boolean removed = list.size() < paramsList.size(); if (removed) { this.paramsList = list; } return removed; } /** * <p>get.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.lang.Object} object. */ public Object get(String name) { Pair<String, Object> entry = CollectionUtils.find(paramsList, e -> e.getKey().equals(name)); return entry == null ? null : entry.getValue(); } /** * <p>get.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public String get(String name, String defaultValue) { String value = (String) get(name); return value == null ? defaultValue : value; } /** * <p>getString.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public String getString(String name) { return (String) get(name); } /** * <p>getEnum.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a T object. * @param <T> a T object. * @return a T object. */ public <T extends Enum<T>> T getEnum(String name, T defaultValue) { Object val = this.get(name); return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val.toString()); } /** * <p>getInt.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.lang.Integer} object. */ public Integer getInt(String name) { return (Integer) get(name); } /** * <p>getInt.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.lang.Integer} object. * @return a {@link java.lang.Integer} object. */ public Integer getInt(String name, Integer defaultValue) { Integer value = (Integer) get(name); return value == null ? defaultValue : value; } /** * <p>getLong.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.lang.Long} object. */ public Long getLong(String name) { return (Long) get(name); } /** * <p>getLong.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.lang.Long} object. * @return a {@link java.lang.Long} object. */ public Long getLong(String name, Long defaultValue) { Long value = (Long) get(name); return value == null ? defaultValue : value; } /** * <p>getBoolean.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.lang.Boolean} object. */ public Boolean getBoolean(String name) { return (Boolean) get(name); } /** * <p>getBoolean.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.lang.Boolean} object. * @return a {@link java.lang.Boolean} object. */ public Boolean getBoolean(String name, Boolean defaultValue) { Boolean value = (Boolean) get(name); return value == null ? defaultValue : value; } /** * <p>getStrings.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue an array of {@link java.lang.String} objects. * @return an array of {@link java.lang.String} objects. */ public String[] getStrings(String name, String[] defaultValue) { String valueString = get(name, null); if (valueString == null) { return defaultValue; } return Strings.getStrings(valueString); } /** * <p>getStringCollection.</p> * * @param name a {@link java.lang.String} object. * @param delim a {@link java.lang.String} object. * @return a {@link java.util.Collection} object. */ public Collection<String> getStringCollection(String name, String delim) { String valueString = get(name, null); return Strings.getStringCollection(valueString, delim); } /** * <p>getPath.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.nio.file.Path} object. * @throws java.io.IOException if any. */ public Path getPath(String name) throws IOException { String value = getString(name); if (value == null) return null; Path path = Paths.get(value); Files.createDirectories(path.getParent()); return path; } /** * <p>getPath.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.nio.file.Path} object. * @return a {@link java.nio.file.Path} object. * @throws java.io.IOException if any. */ public Path getPath(String name, Path defaultValue) throws IOException { String value = getString(name); Path path = value == null ? Paths.get(value) : defaultValue; Files.createDirectories(path.getParent()); return path; } /** * <p>getInstant.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.time.Instant} object. */ public Instant getInstant(String name) { return (Instant) get(name); } /** * <p>getInstant.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.time.Instant} object. * @return a {@link java.time.Instant} object. */ public Instant getInstant(String name, Instant defaultValue) { Instant value = (Instant) get(name); return value == null ? defaultValue : value; } /** * <p>getDuration.</p> * * @param name a {@link java.lang.String} object. * @return a {@link java.time.Duration} object. */ public Duration getDuration(String name) { return (Duration) get(name); } /** * <p>getDuration.</p> * * @param name a {@link java.lang.String} object. * @param defaultValue a {@link java.time.Duration} object. * @return a {@link java.time.Duration} object. */ public Duration getDuration(String name, Duration defaultValue) { Duration value = (Duration) get(name); return value == null ? defaultValue : value; } /** * <p>format.</p> * * @return a {@link java.lang.String} object. */ public String format() { return format(paramsList); } /** * <p>formatAsLine.</p> * * @return a {@link java.lang.String} object. */ public String formatAsLine() { return formatAsLine(paramsList); } /** * <p>withCaptionFormat.</p> * * @param captionFormat a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withCaptionFormat(String captionFormat) { this.captionFormat = captionFormat; return this; } /** * <p>withHeaderFormat.</p> * * @param headerFormat a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withHeaderFormat(String headerFormat) { this.headerFormat = headerFormat; return this; } /** * <p>withRowFormat.</p> * * @param rowFormat a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withRowFormat(String rowFormat) { this.rowFormat = rowFormat; return this; } /** * <p>withPairDelimiter.</p> * * @param pairDelimiter a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withPairDelimiter(String pairDelimiter) { this.pairDelimiter = pairDelimiter; return this; } /** * <p>withKVDelimiter.</p> * * @param kvDelimiter a {@link java.lang.String} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withKVDelimiter(String kvDelimiter) { this.kvDelimiter = kvDelimiter; return this; } /** * <p>iscmdLineStyle.</p> * * @return a boolean. */ public boolean isCmdLineStyle() { return cmdLineStyle; } /** * <p>withCmdLineStyle.</p> * * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withCmdLineStyle() { return withCmdLineStyle(true); } /** * <p>withCmdLineStyle.</p> * * @param isCmdLineStyle a boolean. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withCmdLineStyle(boolean isCmdLineStyle) { this.cmdLineStyle = isCmdLineStyle; return this; } public Params withDistinctBooleanParams(List<String> distinctBooleanParams) { this.distinctBooleanParams = distinctBooleanParams; return this; } /** * <p>sorted.</p> * * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params sorted() { this.paramsList = this.paramsList.stream() .sorted(Comparator.comparing(Pair::getKey)) .collect(Collectors.toList()); return this; } /** * <p>filter.</p> * * @param predicate a {@link java.util.function.Predicate} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params filter(Predicate<Pair<String, Object>> predicate) { this.paramsList = this.paramsList.stream() .filter(predicate) .collect(Collectors.toList()); return this; } /** * <p>distinct.</p> * * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params distinct() { this.paramsList = this.paramsList.stream() .distinct() .collect(Collectors.toList()); return this; } /** * <p>merge.</p> * * @param others a {@link ai.platon.pulsar.common.config.Params} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params merge(Params... others) { if (others != null && others.length > 0) { Arrays.stream(others).forEach(params -> this.paramsList.addAll(params.getParamsList())); } return this; } /** * <p>merge.</p> * * @param others a {@link java.util.Collection} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params merge(Collection<Params> others) { others.forEach(params -> this.paramsList.addAll(params.getParamsList())); return this; } /** * <p>Getter for the field <code>paramsList</code>.</p> * * @return a {@link java.util.List} object. */ public List<Pair<String, Object>> getParamsList() { return paramsList; } /** * <p>asMap.</p> * * @return a {@link java.util.Map} object. */ public Map<String, Object> asMap() { Map<String, Object> result = new HashMap<>(); paramsList.forEach(p -> result.put(p.getKey(), p.getValue())); return result; } /** * <p>asStringMap.</p> * * @return a {@link java.util.Map} object. */ public Map<String, String> asStringMap() { Map<String, String> result = new HashMap<>(); paramsList.forEach(p -> result.put(p.getKey(), p.getValue().toString())); return result; } /** * <p>withLogger.</p> * * @param logger a {@link org.slf4j.Logger} object. * @return a {@link ai.platon.pulsar.common.config.Params} object. */ public Params withLogger(Logger logger) { this.defaultLog = logger; return this; } /** * <p>debug.</p> */ public void debug() { debug(false); } /** * <p>debug.</p> * * @param inline a boolean. */ public void debug(boolean inline) { if (defaultLog != null) { defaultLog.debug(inline ? formatAsLine() : format()); } else { log.debug(inline ? formatAsLine() : format()); } } /** * <p>info.</p> */ public void info() { info(false); } /** * <p>info.</p> * * @param inline a boolean. */ public void info(boolean inline) { info("", "", inline); } /** * <p>info.</p> * * @param prefix a {@link java.lang.String} object. * @param postfix a {@link java.lang.String} object. * @param inline a boolean. */ public void info(String prefix, String postfix, boolean inline) { StringBuilder sb = new StringBuilder(prefix); sb.append(inline ? formatAsLine() : format()); sb.append(postfix); String message = sb.toString(); if (message.isEmpty()) { return; } if (defaultLog != null) { defaultLog.info("{}", sb); } else { log.info("{}", sb); } } /** * {@inheritDoc} */ @Override public String toString() { return format(); } private String format(List<Pair<String, Object>> params) { if (params.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); sb.append('\n'); if (captionFormat != null) sb.append(captionFormat); if (headerFormat != null) sb.append(headerFormat); int i = 0; for (Pair<String, Object> param : params) { if (i++ > 0) { sb.append("\n"); } String key = param.getKey(); Object value = param.getValue(); if (value instanceof Map) { Map<?, ?> m = (Map<?, ?>) value; value = m.entrySet().stream() .map(e -> e.getKey() + ":" + e.getValue().toString()) .collect(Collectors.joining(", ")); } else if (value instanceof Collection) { Collection<?> c = (Collection<?>) value; value = StringUtils.join(c, ", "); } sb.append(String.format(rowFormat, key, value)); } sb.append('\n'); return sb.toString(); } private String formatAsLine(List<Pair<String, Object>> params) { if (params.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); int i = 0; for (Pair<String, Object> arg : params) { if (i++ > 0) { sb.append(pairDelimiter); } String key = arg.getKey(); String value = arg.getValue().toString(); if (arg.getValue() == null) { sb.append(key); if (!cmdLineStyle) { sb.append(kvDelimiter); sb.append("null"); } } else if (cmdLineStyle && key.startsWith("-") && "true".equals(value)) { if (distinctBooleanParams != null && distinctBooleanParams.contains(key)) { sb.append(key); sb.append(kvDelimiter); sb.append("true"); } else { sb.append(key); } } else if (cmdLineStyle && key.startsWith("-") && "false".equals(value)) { if (distinctBooleanParams != null && distinctBooleanParams.contains(key)) { sb.append(key); sb.append(kvDelimiter); sb.append("false"); } } else { sb.append(key); if (!value.isEmpty()) { sb.append(kvDelimiter); // quoted // @see https://github.com/cbeust/jcommander/issues/458 // JCommand no longer removing double quotes when parsing arguments if (value.contains(kvDelimiter) && !value.startsWith("\"") && !value.endsWith("\"")) { sb.append('\"').append(value).append('\"'); } else { sb.append(value); } } } } return sb.toString().trim(); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/BasicUsage.java
package ai.platon.pulsar.examples; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.dom.FeaturedDocument; import ai.platon.pulsar.persist.WebPage; import ai.platon.pulsar.skeleton.session.PulsarSession; import com.google.gson.Gson; import org.jsoup.nodes.Element; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class BasicUsage { public static void main(String[] args) throws Exception { // create a pulsar session PulsarSession session = PulsarContexts.createSession(); // the main url we are playing with String url = "https://list.jd.com/list.html?cat=652,12345,12349"; // load a page, or fetch it from the Internet if it does not exist or has expired WebPage page = session.load(url, "-expires 1d"); // submit a url to the URL pool, and it will be processed in a crawl loop session.submit(url, "-expires 1d"); // parse the page content into a Jsoup document FeaturedDocument document = session.parse(page, false); // do something with the document // ... // or, load and parse FeaturedDocument document2 = session.loadDocument(url, "-expires 1d"); // do something with the document // ... // load all pages with links specified by -outLink List<WebPage> pages = session.loadOutPages(url, "-expires 1d -itemExpires 7d -outLink a[href~=item]"); // load the portal page and submit the out links specified by the `-outLink` option to the URL pool session.submitForOutPages(url, "-expires 1d -itemExpires 7d -outLink a[href~=item]"); // load, parse and scrape fields List<Map<String, String>> fields = session.scrape(url, "-expires 1d", "li[data-sku]", Arrays.asList(".p-name em", ".p-price")); // load, parse and scrape named fields List<Map<String, String>> fields2 = session.scrape(url, "-i 1d", "li[data-sku]", Map.of("name", ".p-name em", "price", ".p-price")); System.out.println("== document"); System.out.println(document.getTitle()); System.out.println(document.selectFirstOptional("title").map(Element::text)); System.out.println("== document2"); System.out.println(document2.getTitle()); System.out.println(document2.selectFirstOptional("title").map(Element::text)); System.out.println("== pages"); System.out.println(pages.stream().map(WebPage::getUrl).collect(Collectors.toList())); Gson gson = new Gson(); System.out.println("== fields"); System.out.println(gson.toJson(fields)); System.out.println("== fields2"); System.out.println(gson.toJson(fields2)); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/ContinuousCrawler.java
package ai.platon.pulsar.examples; import ai.platon.pulsar.common.LinkExtractors; import ai.platon.pulsar.common.urls.Hyperlink; import ai.platon.pulsar.skeleton.context.PulsarContext; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.skeleton.crawl.common.url.ParsableHyperlink; import ai.platon.pulsar.dom.FeaturedDocument; import ai.platon.pulsar.persist.WebPage; import java.util.List; import java.util.stream.Collectors; public class ContinuousCrawler { private static void onParse(WebPage page, FeaturedDocument document) { // do something wonderful with the document System.out.println(document.getTitle() + "\t|\t" + document.getBaseURI()); // extract more links from the document List<Hyperlink> urls = document.selectHyperlinks("a[href~=/dp/]"); PulsarContexts.create().submitAll(urls); } public static void main(String[] args) throws InterruptedException { List<Hyperlink> urls = LinkExtractors.fromResource("seeds.txt") .stream() .map(seed -> new ParsableHyperlink(seed, ContinuousCrawler::onParse)) .collect(Collectors.toList()); PulsarContext context = PulsarContexts.create().submitAll(urls); // feel free to submit millions of urls here // ... context.await(); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/advanced/JvmHighPerformanceCrawler.java
package ai.platon.pulsar.examples.advanced; import ai.platon.pulsar.browser.common.BlockRule; import ai.platon.pulsar.common.LinkExtractors; import ai.platon.pulsar.common.NetUtil; import ai.platon.pulsar.common.config.CapabilityTypes; import ai.platon.pulsar.persist.WebPage; import ai.platon.pulsar.skeleton.PulsarSettings; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.skeleton.crawl.common.url.ListenableHyperlink; import ai.platon.pulsar.skeleton.crawl.event.JvmWebPageWebDriverEventHandler; import ai.platon.pulsar.skeleton.crawl.fetch.driver.JvmWebDriver; import ai.platon.pulsar.skeleton.session.PulsarSession; import kotlin.coroutines.Continuation; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class JvmHighPerformanceCrawler { private final PulsarSession session; public JvmHighPerformanceCrawler() throws Exception { session = PulsarContexts.getOrCreateSession(); } public void crawl() { // Crawl arguments: // -refresh: always re-fetch the page // -dropContent: do not persist page content // -interactLevel fastest: prioritize speed over data completeness String args = "-refresh -dropContent -interactLevel fastest"; // Block non-essential resources to improve load speed. // ⚠️ Be careful — blocking critical resources may break rendering or script execution. List<String> blockingUrls = new BlockRule().getBlockingUrls(); String resource = "seeds/amazon/best-sellers/leaf-categories.txt"; Iterable<String> urls = LinkExtractors.fromResource(resource); List<ListenableHyperlink> links = new ArrayList<>(); for (String url : urls) { var hyperlink = ListenableHyperlink.create(url); hyperlink.setArgs(args); var eventHandlers = hyperlink.getEventHandlers().getBrowseEventHandlers().getOnWillNavigate(); eventHandlers.addLast(new JvmWebPageWebDriverEventHandler() { @Override public Object invoke(WebPage page, JvmWebDriver driver, Continuation<? super Object> $completion) { driver.addBlockedURLsAsync(blockingUrls); return null; } }); links.add(hyperlink); } session.submitAll(links); } public static void main(String[] args) throws Exception { // Highly recommended to enable proxies, or you will be blocked by Amazon String proxyHubURL = "http://localhost:8192/api/proxies"; if (NetUtil.testHttpNetwork(proxyHubURL)) { System.setProperty(CapabilityTypes.PROXY_ROTATION_URL, proxyHubURL); } var settings = new PulsarSettings(); settings.maxBrowserContexts(2); settings.maxOpenTabs(8); settings.withSequentialBrowsers(); var crawler = new JvmHighPerformanceCrawler(); crawler.crawl(); PulsarContexts.await(); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/async/CrawlAsync.java
package ai.platon.pulsar.examples.async; import ai.platon.pulsar.common.LinkExtractors; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.dom.FeaturedDocument; import ai.platon.pulsar.persist.WebPage; import ai.platon.pulsar.skeleton.session.PulsarSession; import java.util.concurrent.CompletableFuture; class CrawlAsync { private static String url = "https://www.amazon.com/Best-Sellers/zgbs"; public static void loadAsync() throws Exception { PulsarSession session = PulsarContexts.createSession(); WebPage page = session.loadAsync(url).join(); } public static void loadAsync2() throws Exception { PulsarSession session = PulsarContexts.createSession(); FeaturedDocument document = session.loadAsync(url) .thenApply(session::parse) .join(); } public static void loadAsync3() throws Exception { PulsarSession session = PulsarContexts.createSession(); String title = session.loadAsync(url) .thenApply(session::parse) .thenApply(FeaturedDocument::guessTitle) .join(); } public static void loadAll() throws Exception { PulsarSession session = PulsarContexts.createSession(); LinkExtractors.fromResource("seeds10.txt").stream() .map(session::open).map(session::parse) .map(FeaturedDocument::guessTitle) .forEach(System.out::println); } public static void loadAllAsync2() throws Exception { PulsarSession session = PulsarContexts.createSession(); CompletableFuture<?>[] futures = LinkExtractors.fromResource("seeds10.txt").stream() .map(url -> url + " -i 1d") .map(session::loadAsync) .map(f -> f.thenApply(session::parse)) .map(f -> f.thenApply(FeaturedDocument::guessTitle)) .map(f -> f.thenAccept(System.out::println)) .toArray(CompletableFuture<?>[]::new); CompletableFuture.allOf(futures).join(); } public static void loadAllAsync3() throws Exception { PulsarSession session = PulsarContexts.createSession(); CompletableFuture<?>[] futures = session.loadAllAsync(LinkExtractors.fromResource("seeds10.txt")).stream() .map(f -> f.thenApply(session::parse)) .map(f -> f.thenApply(FeaturedDocument::guessTitle)) .map(f -> f.thenAccept(System.out::println)) .toArray(CompletableFuture<?>[]::new); CompletableFuture.allOf(futures).join(); } public static void loadAllAsync4() throws Exception { PulsarSession session = PulsarContexts.createSession(); CompletableFuture<?>[] futures = session.loadAllAsync(LinkExtractors.fromResource("seeds10.txt")).stream() .map(f -> f.thenApply(session::parse) .thenApply(FeaturedDocument::guessTitle) .thenAccept(System.out::println) ) .toArray(CompletableFuture<?>[]::new); CompletableFuture.allOf(futures).join(); } public static void main(String[] args) throws Exception { loadAll(); loadAllAsync2(); loadAllAsync3(); loadAllAsync4(); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/rpa/RPACrawler.java
package ai.platon.pulsar.examples.rpa; import ai.platon.pulsar.skeleton.common.options.LoadOptions; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.skeleton.crawl.event.JvmWebPageWebDriverEventHandler; import ai.platon.pulsar.skeleton.crawl.fetch.driver.JvmWebDriver; import ai.platon.pulsar.persist.WebPage; import ai.platon.pulsar.skeleton.session.PulsarSession; import kotlin.coroutines.Continuation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class RPACrawler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final PulsarSession session; public final Map<String, String> fieldSelectors; public RPACrawler() throws Exception { this(PulsarContexts.createSession()); } public RPACrawler(PulsarSession session) { this.session = session; fieldSelectors = new HashMap<>(Map.of( "sku-name", ".sku-name", "news", ".news", "summary", ".summary" )); } public LoadOptions options(String args) { var options = session.options(args, null); var be = options.getEventHandlers().getBrowseEventHandlers(); be.getOnWillComputeFeature().addLast(new JvmWebPageWebDriverEventHandler() { @Override public Object invoke(WebPage page, JvmWebDriver driver, Continuation<? super Object> continuation) { fieldSelectors.values().forEach(selector -> interact(selector, driver)); return null; } }); be.getOnFeatureComputed().addLast(new JvmWebPageWebDriverEventHandler() { @Override public Object invoke(WebPage page, JvmWebDriver driver, Continuation<? super Object> $completion) { logger.info("Feature computed"); return null; } }); return options; } private void interact(String selector, JvmWebDriver driver) { var delayedExecutor = CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS); var searchBoxSelector = ".form input[type=text]"; driver.existsAsync(selector).thenAccept(exists -> { if (exists) { driver.clickAsync(selector) .thenCompose(ignored -> driver.selectFirstTextOptionalAsync(selector)) .thenAcceptAsync(text -> driver.typeAsync(searchBoxSelector, text.orElse("").substring(1, 4)), delayedExecutor) .thenRun(() -> logger.info("{} clicked", selector)) .join(); } }).join(); } public static void main(String[] argv) throws Exception { var url = "https://item.jd.com/10023632209832.html"; var args = "-refresh -parse"; var session = PulsarContexts.createSession(); var crawler = new RPACrawler(session); var fields = session.scrape(url, crawler.options(args), crawler.fieldSelectors); System.out.println(fields); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/sites/BaiduCrawler.java
package ai.platon.pulsar.examples.sites; import ai.platon.pulsar.skeleton.context.PulsarContexts; import ai.platon.pulsar.skeleton.session.PulsarSession; public class BaiduCrawler { public static void main(String[] args) throws Exception { var url = "https://www.baidu.com/"; try (var session = PulsarContexts.createSession()) { session.open(url); } } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/sites
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/sites/amazon/AmazonCrawler.java
package ai.platon.pulsar.examples.sites.amazon; import ai.platon.pulsar.skeleton.context.PulsarContexts; import java.util.Map; class AmazonCrawler { public static void main(String[] argv) throws Exception { PulsarContexts.createSession().scrapeOutPages( "https://www.amazon.com/Best-Sellers/zgbs", "-refresh -outLink a[href~=/dp/]", Map.of("title", "#title", "ratings", "#acrCustomerReviewText") ); } }
0
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/sites
java-sources/ai/platon/pulsar/pulsar-examples/3.0.15/ai/platon/pulsar/examples/sites/jd/JdCrawler.java
package ai.platon.pulsar.examples.sites.jd; import ai.platon.pulsar.browser.common.BrowserSettings; import ai.platon.pulsar.skeleton.context.PulsarContexts; class JdCrawler { public static void main(String[] argv) throws Exception { BrowserSettings.withSystemDefaultBrowser(); var portalUrl = "https://list.jd.com/list.html?cat=652,12345,12349"; var args = "-i 1s -ii 5s -ol a[href~=item] -ignoreFailure"; try (var session = PulsarContexts.createSession()) { session.load(portalUrl); session.loadOutPages(portalUrl, args); } } }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/Driver.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Logger; import org.h2.engine.Constants; import org.h2.jdbc.JdbcConnection; import org.h2.message.DbException; import org.h2.upgrade.DbUpgrade; /** * The database driver. An application should not use this class directly. The * only thing the application needs to do is load the driver. This can be done * using Class.forName. To load the driver and open a database connection, use * the following code: * * <pre> * Class.forName(&quot;org.h2.Driver&quot;); * Connection conn = DriverManager.getConnection( * &quot;jdbc:h2:&tilde;/test&quot;, &quot;sa&quot;, &quot;sa&quot;); * </pre> */ public class Driver implements java.sql.Driver, JdbcDriverBackwardsCompat { private static final Driver INSTANCE = new Driver(); private static final String DEFAULT_URL = "jdbc:default:connection"; private static final ThreadLocal<Connection> DEFAULT_CONNECTION = new ThreadLocal<>(); private static volatile boolean registered; static { load(); } /** * Open a database connection. * This method should not be called by an application. * Instead, the method DriverManager.getConnection should be used. * * @param url the database URL * @param info the connection properties * @return the new connection or null if the URL is not supported */ @Override public Connection connect(String url, Properties info) throws SQLException { try { if (info == null) { info = new Properties(); } if (!acceptsURL(url)) { return null; } if (url.equals(DEFAULT_URL)) { return DEFAULT_CONNECTION.get(); } Connection c = DbUpgrade.connectOrUpgrade(url, info); if (c != null) { return c; } return new JdbcConnection(url, info); } catch (Exception e) { throw DbException.toSQLException(e); } } /** * Check if the driver understands this URL. * This method should not be called by an application. * * @param url the database URL * @return if the driver understands the URL */ @Override public boolean acceptsURL(String url) { if (url != null) { if (url.startsWith(Constants.START_URL)) { return true; } else if (url.equals(DEFAULT_URL)) { return DEFAULT_CONNECTION.get() != null; } } return false; } /** * Get the major version number of the driver. * This method should not be called by an application. * * @return the major version number */ @Override public int getMajorVersion() { return Constants.VERSION_MAJOR; } /** * Get the minor version number of the driver. * This method should not be called by an application. * * @return the minor version number */ @Override public int getMinorVersion() { return Constants.VERSION_MINOR; } /** * Get the list of supported properties. * This method should not be called by an application. * * @param url the database URL * @param info the connection properties * @return a zero length array */ @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { return new DriverPropertyInfo[0]; } /** * Check if this driver is compliant to the JDBC specification. * This method should not be called by an application. * * @return true */ @Override public boolean jdbcCompliant() { return true; } /** * [Not supported] */ @Override public Logger getParentLogger() { return null; } /** * INTERNAL */ public static synchronized Driver load() { try { if (!registered) { registered = true; DriverManager.registerDriver(INSTANCE); } } catch (SQLException e) { DbException.traceThrowable(e); } return INSTANCE; } /** * INTERNAL */ public static synchronized void unload() { try { if (registered) { registered = false; DriverManager.deregisterDriver(INSTANCE); } } catch (SQLException e) { DbException.traceThrowable(e); } } /** * INTERNAL * Sets, on a per-thread basis, the default-connection for * user-defined functions. */ public static void setDefaultConnection(Connection c) { if (c == null) { DEFAULT_CONNECTION.remove(); } else { DEFAULT_CONNECTION.set(c); } } /** * INTERNAL */ public static void setThreadContextClassLoader(Thread thread) { // Apache Tomcat: use the classloader of the driver to avoid the // following log message: // org.apache.catalina.loader.WebappClassLoader clearReferencesThreads // SEVERE: The web application appears to have started a thread named // ... but has failed to stop it. // This is very likely to create a memory leak. try { thread.setContextClassLoader(Driver.class.getClassLoader()); } catch (Throwable t) { // ignore } } }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/JdbcDriverBackwardsCompat.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2; /** * Allows us to compile on older platforms, while still implementing the methods * from the newer JDBC API. */ public interface JdbcDriverBackwardsCompat { // compatibility interface }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/Aggregate.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import java.sql.Connection; import java.sql.SQLException; /** * A user-defined aggregate function needs to implement this interface. * The class must be public and must have a public non-argument constructor. */ public interface Aggregate { /** * This method is called when the aggregate function is used. * A new object is created for each invocation. * * @param conn a connection to the database */ void init(Connection conn) throws SQLException; /** * This method must return the H2 data type, {@link org.h2.value.Value}, * of the aggregate function, given the H2 data type of the input data. * The method should check here if the number of parameters * passed is correct, and if not it should throw an exception. * * @param inputTypes the H2 data type of the parameters, * @return the H2 data type of the result * @throws SQLException if the number/type of parameters passed is incorrect */ int getInternalType(int[] inputTypes) throws SQLException; /** * This method is called once for each row. * If the aggregate function is called with multiple parameters, * those are passed as array. * * @param value the value(s) for this row */ void add(Object value) throws SQLException; /** * This method returns the computed aggregate value. * * @return the aggregated value */ Object getResult() throws SQLException; }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/AggregateFunction.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import java.sql.Connection; import java.sql.SQLException; /** * A user-defined aggregate function needs to implement this interface. * The class must be public and must have a public non-argument constructor. * <p> * Please note this interface only has limited support for data types. * If you need data types that don't have a corresponding SQL type * (for example GEOMETRY), then use the {@link Aggregate} interface. * </p> */ public interface AggregateFunction { /** * This method is called when the aggregate function is used. * A new object is created for each invocation. * * @param conn a connection to the database */ void init(Connection conn) throws SQLException; /** * This method must return the SQL type of the method, given the SQL type of * the input data. The method should check here if the number of parameters * passed is correct, and if not it should throw an exception. * * @param inputTypes the SQL type of the parameters, {@link java.sql.Types} * @return the SQL type of the result */ int getType(int[] inputTypes) throws SQLException; /** * This method is called once for each row. * If the aggregate function is called with multiple parameters, * those are passed as array. * * @param value the value(s) for this row */ void add(Object value) throws SQLException; /** * This method returns the computed aggregate value. * * @return the aggregated value */ Object getResult() throws SQLException; }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/CustomDataTypesHandler.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import org.h2.store.DataHandler; import org.h2.value.DataType; import org.h2.value.Value; /** * Custom data type handler * Provides means to plug-in custom data types support * * Please keep in mind that this feature may not possibly * provide the same ABI stability level as other features * as it exposes many of the H2 internals. You may be * required to update your code occasionally due to internal * changes in H2 if you are going to use this feature */ public interface CustomDataTypesHandler { /** * Get custom data type given its name * * @param name data type name * @return custom data type */ DataType getDataTypeByName(String name); /** * Get custom data type given its integer id * * @param type identifier of a data type * @return custom data type */ DataType getDataTypeById(int type); /** * Get order for custom data type given its integer id * * @param type identifier of a data type * @return order associated with custom data type */ int getDataTypeOrder(int type); /** * Convert the provided source value into value of given target data type * Shall implement conversions to and from custom data types. * * @param source source value * @param targetType identifier of target data type * @return converted value */ Value convert(Value source, int targetType); /** * Get custom data type class name given its integer id * * @param type identifier of a data type * @return class name */ String getDataTypeClassName(int type); /** * Get custom data type identifier given corresponding Java class * @param cls Java class object * @return type identifier */ int getTypeIdFromClass(Class<?> cls); /** * Get {@link org.h2.value.Value} object * corresponding to given data type identifier and data. * * @param type custom data type identifier * @param data underlying data type value * @param dataHandler data handler object * @return Value object */ Value getValue(int type, Object data, DataHandler dataHandler); /** * Converts {@link org.h2.value.Value} object * to the specified class. * * @param value the value to convert * @param cls the target class * @return result */ Object getObject(Value value, Class<?> cls); /** * Checks if type supports add operation * * @param type custom data type identifier * @return True, if custom data type supports add operation */ boolean supportsAdd(int type); /** * Get compatible type identifier that would not overflow * after many add operations. * * @param type identifier of a type * @return resulting type identifier */ int getAddProofType(int type); }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/DatabaseEventListener.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import java.sql.SQLException; import java.util.EventListener; /** * A class that implements this interface can get notified about exceptions * and other events. A database event listener can be registered when * connecting to a database. Example database URL: * jdbc:h2:test;DATABASE_EVENT_LISTENER='com.acme.DbListener' */ public interface DatabaseEventListener extends EventListener { /** * This state is used when scanning the database file. */ int STATE_SCAN_FILE = 0; /** * This state is used when re-creating an index. */ int STATE_CREATE_INDEX = 1; /** * This state is used when re-applying the transaction log or rolling back * uncommitted transactions. */ int STATE_RECOVER = 2; /** * This state is used during the BACKUP command. */ int STATE_BACKUP_FILE = 3; /** * This state is used after re-connecting to a database (if auto-reconnect * is enabled). */ int STATE_RECONNECTED = 4; /** * This state is used when a query starts. */ int STATE_STATEMENT_START = 5; /** * This state is used when a query ends. */ int STATE_STATEMENT_END = 6; /** * This state is used for periodic notification during long-running queries. */ int STATE_STATEMENT_PROGRESS = 7; /** * This method is called just after creating the object. * This is done when opening the database if the listener is specified * in the database URL, but may be later if the listener is set at * runtime with the SET SQL statement. * * @param url - the database URL */ void init(String url); /** * This method is called after the database has been opened. It is save to * connect to the database and execute statements at this point. */ void opened(); /** * This method is called if an exception occurred. * * @param e the exception * @param sql the SQL statement */ void exceptionThrown(SQLException e, String sql); /** * This method is called for long running events, such as recovering, * scanning a file or building an index. * <p> * More states might be added in future versions, therefore implementations * should silently ignore states that they don't understand. * </p> * * @param state the state * @param name the object name * @param x the current position * @param max the highest possible value (might be 0) */ void setProgress(int state, String name, int x, int max); /** * This method is called before the database is closed normally. It is save * to connect to the database and execute statements at this point, however * the connection must be closed before the method returns. */ void closingDatabase(); }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/ErrorCode.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; /** * This class defines the error codes used for SQL exceptions. * Error messages are formatted as follows: * <pre> * { error message (possibly translated; may include quoted data) } * { error message in English if different } * { SQL statement if applicable } * { [ error code - build number ] } * </pre> * Example: * <pre> * Syntax error in SQL statement "SELECT * FORM[*] TEST "; * SQL statement: select * form test [42000-125] * </pre> * The [*] marks the position of the syntax error * (FORM instead of FROM in this case). * The error code is 42000, and the build number is 125, * meaning version 1.2.125. */ public class ErrorCode { // 02: no data /** * The error with code <code>2000</code> is thrown when * the result set is positioned before the first or after the last row, or * not on a valid row for the given operation. * Example of wrong usage: * <pre> * ResultSet rs = stat.executeQuery("SELECT * FROM DUAL"); * rs.getString(1); * </pre> * Correct: * <pre> * ResultSet rs = stat.executeQuery("SELECT * FROM DUAL"); * rs.next(); * rs.getString(1); * </pre> */ public static final int NO_DATA_AVAILABLE = 2000; // 07: dynamic SQL error /** * The error with code <code>7001</code> is thrown when * trying to call a function with the wrong number of parameters. * Example: * <pre> * CALL ABS(1, 2) * </pre> */ public static final int INVALID_PARAMETER_COUNT_2 = 7001; // 08: connection exception /** * The error with code <code>8000</code> is thrown when * there was a problem trying to create a database lock. * See the message and cause for details. */ public static final int ERROR_OPENING_DATABASE_1 = 8000; // 21: cardinality violation /** * The error with code <code>21002</code> is thrown when the number of * columns does not match. Possible reasons are: for an INSERT or MERGE * statement, the column count does not match the table or the column list * specified. For a SELECT UNION statement, both queries return a different * number of columns. For a constraint, the number of referenced and * referencing columns does not match. Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * INSERT INTO TEST VALUES('Hello'); * </pre> */ public static final int COLUMN_COUNT_DOES_NOT_MATCH = 21002; // 22: data exception /** * The error with code <code>22001</code> is thrown when * trying to insert a value that is too long for the column. * Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR(2)); * INSERT INTO TEST VALUES(1, 'Hello'); * </pre> */ public static final int VALUE_TOO_LONG_2 = 22001; /** * The error with code <code>22003</code> is thrown when a value is out of * range when converting to another data type. Example: * <pre> * CALL CAST(1000000 AS TINYINT); * SELECT CAST(124.34 AS DECIMAL(2, 2)); * </pre> */ public static final int NUMERIC_VALUE_OUT_OF_RANGE_1 = 22003; /** * The error with code <code>22004</code> is thrown when a value is out of * range when converting to another column's data type. */ public static final int NUMERIC_VALUE_OUT_OF_RANGE_2 = 22004; /** * The error with code <code>22007</code> is thrown when * a text can not be converted to a date, time, or timestamp constant. * Examples: * <pre> * CALL DATE '2007-January-01'; * CALL TIME '14:61:00'; * CALL TIMESTAMP '2001-02-30 12:00:00'; * </pre> */ public static final int INVALID_DATETIME_CONSTANT_2 = 22007; /** * The error with code <code>22012</code> is thrown when trying to divide * a value by zero. Example: * <pre> * CALL 1/0; * </pre> */ public static final int DIVISION_BY_ZERO_1 = 22012; /** * The error with code <code>22018</code> is thrown when * trying to convert a value to a data type where the conversion is * undefined, or when an error occurred trying to convert. Example: * <pre> * CALL CAST(DATE '2001-01-01' AS BOOLEAN); * CALL CAST('CHF 99.95' AS INT); * </pre> */ public static final int DATA_CONVERSION_ERROR_1 = 22018; /** * The error with code <code>22025</code> is thrown when using an invalid * escape character sequence for LIKE or REGEXP. The default escape * character is '\'. The escape character is required when searching for * the characters '%', '_' and the escape character itself. That means if * you want to search for the text '10%', you need to use LIKE '10\%'. If * you want to search for 'C:\temp' you need to use 'C:\\temp'. The escape * character can be changed using the ESCAPE clause as in LIKE '10+%' ESCAPE * '+'. Example of wrong usage: * <pre> * CALL 'C:\temp' LIKE 'C:\temp'; * CALL '1+1' LIKE '1+1' ESCAPE '+'; * </pre> * Correct: * <pre> * CALL 'C:\temp' LIKE 'C:\\temp'; * CALL '1+1' LIKE '1++1' ESCAPE '+'; * </pre> */ public static final int LIKE_ESCAPE_ERROR_1 = 22025; /** * The error with code <code>22030</code> is thrown when * an attempt is made to INSERT or UPDATE an ENUM-typed cell, * but the value is not one of the values enumerated by the * type. * * Example: * <pre> * CREATE TABLE TEST(CASE ENUM('sensitive','insensitive')); * INSERT INTO TEST VALUES('snake'); * </pre> */ public static final int ENUM_VALUE_NOT_PERMITTED = 22030; /** * The error with code <code>22032</code> is thrown when an * attempt is made to add or modify an ENUM-typed column so * that one or more of its enumerators would be empty. * * Example: * <pre> * CREATE TABLE TEST(CASE ENUM(' ')); * </pre> */ public static final int ENUM_EMPTY = 22032; /** * The error with code <code>22033</code> is thrown when an * attempt is made to add or modify an ENUM-typed column so * that it would have duplicate values. * * Example: * <pre> * CREATE TABLE TEST(CASE ENUM('sensitive', 'sensitive')); * </pre> */ public static final int ENUM_DUPLICATE = 22033; // 23: constraint violation /** * The error with code <code>23502</code> is thrown when * trying to insert NULL into a column that does not allow NULL. * Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR NOT NULL); * INSERT INTO TEST(ID) VALUES(1); * </pre> */ public static final int NULL_NOT_ALLOWED = 23502; /** * The error with code <code>23503</code> is thrown when trying to delete * or update a row when this would violate a referential constraint, because * there is a child row that would become an orphan. Example: * <pre> * CREATE TABLE TEST(ID INT PRIMARY KEY, PARENT INT); * INSERT INTO TEST VALUES(1, 1), (2, 1); * ALTER TABLE TEST ADD CONSTRAINT TEST_ID_PARENT * FOREIGN KEY(PARENT) REFERENCES TEST(ID) ON DELETE RESTRICT; * DELETE FROM TEST WHERE ID = 1; * </pre> */ public static final int REFERENTIAL_INTEGRITY_VIOLATED_CHILD_EXISTS_1 = 23503; /** * The error with code <code>23505</code> is thrown when trying to insert * a row that would violate a unique index or primary key. Example: * <pre> * CREATE TABLE TEST(ID INT PRIMARY KEY); * INSERT INTO TEST VALUES(1); * INSERT INTO TEST VALUES(1); * </pre> */ public static final int DUPLICATE_KEY_1 = 23505; /** * The error with code <code>23506</code> is thrown when trying to insert * or update a row that would violate a referential constraint, because the * referenced row does not exist. Example: * <pre> * CREATE TABLE PARENT(ID INT PRIMARY KEY); * CREATE TABLE CHILD(P_ID INT REFERENCES PARENT(ID)); * INSERT INTO CHILD VALUES(1); * </pre> */ public static final int REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1 = 23506; /** * The error with code <code>23507</code> is thrown when * updating or deleting from a table with a foreign key constraint * that should set the default value, but there is no default value defined. * Example: * <pre> * CREATE TABLE TEST(ID INT PRIMARY KEY, PARENT INT); * INSERT INTO TEST VALUES(1, 1), (2, 1); * ALTER TABLE TEST ADD CONSTRAINT TEST_ID_PARENT * FOREIGN KEY(PARENT) REFERENCES TEST(ID) ON DELETE SET DEFAULT; * DELETE FROM TEST WHERE ID = 1; * </pre> */ public static final int NO_DEFAULT_SET_1 = 23507; /** * The error with code <code>23513</code> is thrown when * a check constraint is violated. Example: * <pre> * CREATE TABLE TEST(ID INT CHECK ID&gt;0); * INSERT INTO TEST VALUES(0); * </pre> */ public static final int CHECK_CONSTRAINT_VIOLATED_1 = 23513; /** * The error with code <code>23514</code> is thrown when * evaluation of a check constraint resulted in a error. */ public static final int CHECK_CONSTRAINT_INVALID = 23514; // 28: invalid authorization specification /** * The error with code <code>28000</code> is thrown when * there is no such user registered in the database, when the user password * does not match, or when the database encryption password does not match * (if database encryption is used). */ public static final int WRONG_USER_OR_PASSWORD = 28000; // 3B: savepoint exception /** * The error with code <code>40001</code> is thrown when * the database engine has detected a deadlock. The transaction of this * session has been rolled back to solve the problem. A deadlock occurs when * a session tries to lock a table another session has locked, while the * other session wants to lock a table the first session has locked. As an * example, session 1 has locked table A, while session 2 has locked table * B. If session 1 now tries to lock table B and session 2 tries to lock * table A, a deadlock has occurred. Deadlocks that involve more than two * sessions are also possible. To solve deadlock problems, an application * should lock tables always in the same order, such as always lock table A * before locking table B. For details, see <a * href="http://en.wikipedia.org/wiki/Deadlock">Wikipedia Deadlock</a>. */ public static final int DEADLOCK_1 = 40001; // 42: syntax error or access rule violation /** * The error with code <code>42000</code> is thrown when * trying to execute an invalid SQL statement. * Example: * <pre> * CREATE ALIAS REMAINDER FOR "IEEEremainder"; * </pre> */ public static final int SYNTAX_ERROR_1 = 42000; /** * The error with code <code>42001</code> is thrown when * trying to execute an invalid SQL statement. * Example: * <pre> * CREATE TABLE TEST(ID INT); * INSERT INTO TEST(1); * </pre> */ public static final int SYNTAX_ERROR_2 = 42001; /** * The error with code <code>42101</code> is thrown when * trying to create a table or view if an object with this name already * exists. Example: * <pre> * CREATE TABLE TEST(ID INT); * CREATE TABLE TEST(ID INT PRIMARY KEY); * </pre> */ public static final int TABLE_OR_VIEW_ALREADY_EXISTS_1 = 42101; /** * The error with code <code>42102</code> is thrown when * trying to query, modify or drop a table or view that does not exists * in this schema and database. A common cause is that the wrong * database was opened. * Example: * <pre> * SELECT * FROM ABC; * </pre> */ public static final int TABLE_OR_VIEW_NOT_FOUND_1 = 42102; /** * The error with code <code>42111</code> is thrown when * trying to create an index if an index with the same name already exists. * Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * CREATE INDEX IDX_ID ON TEST(ID); * CREATE TABLE ADDRESS(ID INT); * CREATE INDEX IDX_ID ON ADDRESS(ID); * </pre> */ public static final int INDEX_ALREADY_EXISTS_1 = 42111; /** * The error with code <code>42112</code> is thrown when * trying to drop or reference an index that does not exist. * Example: * <pre> * DROP INDEX ABC; * </pre> */ public static final int INDEX_NOT_FOUND_1 = 42112; /** * The error with code <code>42121</code> is thrown when trying to create * a table or insert into a table and use the same column name twice. * Example: * <pre> * CREATE TABLE TEST(ID INT, ID INT); * </pre> */ public static final int DUPLICATE_COLUMN_NAME_1 = 42121; /** * The error with code <code>42122</code> is thrown when * referencing an non-existing column. * Example: * <pre> * CREATE TABLE TEST(ID INT); * SELECT NAME FROM TEST; * </pre> */ public static final int COLUMN_NOT_FOUND_1 = 42122; // 0A: feature not supported // HZ: remote database access // /** * The error with code <code>50000</code> is thrown when * something unexpected occurs, for example an internal stack * overflow. For details about the problem, see the cause of the * exception in the stack trace. */ public static final int GENERAL_ERROR_1 = 50000; /** * The error with code <code>50004</code> is thrown when * creating a table with an unsupported data type, or * when the data type is unknown because parameters are used. * Example: * <pre> * CREATE TABLE TEST(ID VERYSMALLINT); * </pre> */ public static final int UNKNOWN_DATA_TYPE_1 = 50004; /** * The error with code <code>50100</code> is thrown when calling an * unsupported JDBC method or database feature. See the stack trace for * details. */ public static final int FEATURE_NOT_SUPPORTED_1 = 50100; /** * The error with code <code>50200</code> is thrown when * another connection locked an object longer than the lock timeout * set for this connection, or when a deadlock occurred. * Example: * <pre> * CREATE TABLE TEST(ID INT); * -- connection 1: * SET AUTOCOMMIT FALSE; * INSERT INTO TEST VALUES(1); * -- connection 2: * SET AUTOCOMMIT FALSE; * INSERT INTO TEST VALUES(1); * </pre> */ public static final int LOCK_TIMEOUT_1 = 50200; /** * The error with code <code>57014</code> is thrown when * a statement was canceled using Statement.cancel() or * when the query timeout has been reached. * Examples: * <pre> * stat.setQueryTimeout(1); * stat.cancel(); * </pre> */ public static final int STATEMENT_WAS_CANCELED = 57014; /** * The error with code <code>90000</code> is thrown when * a function that does not return a result set was used in the FROM clause. * Example: * <pre> * SELECT * FROM SIN(1); * </pre> */ public static final int FUNCTION_MUST_RETURN_RESULT_SET_1 = 90000; /** * The error with code <code>90001</code> is thrown when * Statement.executeUpdate() was called for a SELECT statement. * This is not allowed according to the JDBC specs. */ public static final int METHOD_NOT_ALLOWED_FOR_QUERY = 90001; /** * The error with code <code>90002</code> is thrown when * Statement.executeQuery() was called for a statement that does * not return a result set (for example, an UPDATE statement). * This is not allowed according to the JDBC specs. */ public static final int METHOD_ONLY_ALLOWED_FOR_QUERY = 90002; /** * The error with code <code>90003</code> is thrown when * trying to convert a String to a binary value. Two hex digits * per byte are required. Example of wrong usage: * <pre> * CALL X'00023'; * Hexadecimal string with odd number of characters: 00023 * </pre> * Correct: * <pre> * CALL X'000023'; * </pre> */ public static final int HEX_STRING_ODD_1 = 90003; /** * The error with code <code>90004</code> is thrown when * trying to convert a text to binary, but the expression contains * a non-hexadecimal character. * Example: * <pre> * CALL X'ABCDEFGH'; * CALL CAST('ABCDEFGH' AS BINARY); * </pre> * Conversion from text to binary is supported, but the text must * represent the hexadecimal encoded bytes. */ public static final int HEX_STRING_WRONG_1 = 90004; /** * The error with code <code>90005</code> is thrown when * trying to create a trigger and using the combination of SELECT * and FOR EACH ROW, which we do not support. */ public static final int TRIGGER_SELECT_AND_ROW_BASED_NOT_SUPPORTED = 90005; /** * The error with code <code>90006</code> is thrown when * trying to get a value from a sequence that has run out of numbers * and does not have cycling enabled. */ public static final int SEQUENCE_EXHAUSTED = 90006; /** * The error with code <code>90007</code> is thrown when * trying to call a JDBC method on an object that has been closed. */ public static final int OBJECT_CLOSED = 90007; /** * The error with code <code>90008</code> is thrown when * trying to use a value that is not valid for the given operation. * Example: * <pre> * CREATE SEQUENCE TEST INCREMENT 0; * </pre> */ public static final int INVALID_VALUE_2 = 90008; /** * The error with code <code>90009</code> is thrown when * trying to create a sequence with an invalid combination * of attributes (min value, max value, start value, etc). */ public static final int SEQUENCE_ATTRIBUTES_INVALID = 90009; /** * The error with code <code>90010</code> is thrown when * trying to format a timestamp or number using TO_CHAR * with an invalid format. */ public static final int INVALID_TO_CHAR_FORMAT = 90010; /** * The error with code <code>90011</code> is thrown when * trying to open a connection to a database using an implicit relative * path, such as "jdbc:h2:test" (in which case the database file would be * stored in the current working directory of the application). This is not * allowed because it can lead to confusion where the database file is, and * can result in multiple databases because different working directories * are used. Instead, use "jdbc:h2:~/name" (relative to the current user * home directory), use an absolute path, set the base directory (baseDir), * use "jdbc:h2:./name" (explicit relative path), or set the system property * "h2.implicitRelativePath" to "true" (to prevent this check). For Windows, * an absolute path also needs to include the drive ("C:/..."). Please see * the documentation on the supported URL format. Example: * <pre> * jdbc:h2:test * </pre> */ public static final int URL_RELATIVE_TO_CWD = 90011; /** * The error with code <code>90012</code> is thrown when * trying to execute a statement with an parameter. * Example: * <pre> * CALL SIN(?); * </pre> */ public static final int PARAMETER_NOT_SET_1 = 90012; /** * The error with code <code>90013</code> is thrown when * trying to open a database that does not exist using the flag * IFEXISTS=TRUE, or when trying to access a database object with a catalog * name that does not match the database name. Example: * <pre> * CREATE TABLE TEST(ID INT); * SELECT XYZ.PUBLIC.TEST.ID FROM TEST; * </pre> */ public static final int DATABASE_NOT_FOUND_1 = 90013; /** * The error with code <code>90014</code> is thrown when * trying to parse a date with an unsupported format string, or * when the date can not be parsed. * Example: * <pre> * CALL PARSEDATETIME('2001 January', 'yyyy mm'); * </pre> */ public static final int PARSE_ERROR_1 = 90014; /** * The error with code <code>90015</code> is thrown when * using an aggregate function with a data type that is not supported. * Example: * <pre> * SELECT SUM('Hello') FROM DUAL; * </pre> */ public static final int SUM_OR_AVG_ON_WRONG_DATATYPE_1 = 90015; /** * The error with code <code>90016</code> is thrown when * a column was used in the expression list or the order by clause of a * group or aggregate query, and that column is not in the GROUP BY clause. * Example of wrong usage: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World'); * SELECT ID, MAX(NAME) FROM TEST; * Column ID must be in the GROUP BY list. * </pre> * Correct: * <pre> * SELECT ID, MAX(NAME) FROM TEST GROUP BY ID; * </pre> */ public static final int MUST_GROUP_BY_COLUMN_1 = 90016; /** * The error with code <code>90017</code> is thrown when * trying to define a second primary key constraint for this table. * Example: * <pre> * CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR); * ALTER TABLE TEST ADD CONSTRAINT PK PRIMARY KEY(NAME); * </pre> */ public static final int SECOND_PRIMARY_KEY = 90017; /** * The error with code <code>90018</code> is thrown when * the connection was opened, but never closed. In the finalizer of the * connection, this forgotten close was detected and the connection was * closed automatically, but relying on the finalizer is not good practice * as it is not guaranteed and behavior is virtual machine dependent. The * application should close the connection. This exception only appears in * the .trace.db file. Example of wrong usage: * <pre> * Connection conn; * conn = DriverManager.getConnection(&quot;jdbc:h2:&tilde;/test&quot;); * conn = null; * The connection was not closed by the application and is * garbage collected * </pre> * Correct: * <pre> * conn.close(); * </pre> */ public static final int TRACE_CONNECTION_NOT_CLOSED = 90018; /** * The error with code <code>90019</code> is thrown when * trying to drop the current user, if there are no other admin users. * Example: * <pre> * DROP USER SA; * </pre> */ public static final int CANNOT_DROP_CURRENT_USER = 90019; /** * The error with code <code>90020</code> is thrown when trying to open a * database in embedded mode if this database is already in use in another * process (or in a different class loader). Multiple connections to the * same database are supported in the following cases: * <ul><li>In embedded mode (URL of the form jdbc:h2:~/test) if all * connections are opened within the same process and class loader. * </li><li>In server and cluster mode (URL of the form * jdbc:h2:tcp://localhost/test) using remote connections. * </li></ul> * The mixed mode is also supported. This mode requires to start a server * in the same process where the database is open in embedded mode. */ public static final int DATABASE_ALREADY_OPEN_1 = 90020; /** * The error with code <code>90021</code> is thrown when * trying to change a specific database property that conflicts with other * database properties. */ public static final int UNSUPPORTED_SETTING_COMBINATION = 90021; /** * The error with code <code>90022</code> is thrown when * trying to call a unknown function. * Example: * <pre> * CALL SPECIAL_SIN(10); * </pre> */ public static final int FUNCTION_NOT_FOUND_1 = 90022; /** * The error with code <code>90023</code> is thrown when * trying to set a primary key on a nullable column. * Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * ALTER TABLE TEST ADD CONSTRAINT PK PRIMARY KEY(ID); * </pre> */ public static final int COLUMN_MUST_NOT_BE_NULLABLE_1 = 90023; /** * The error with code <code>90024</code> is thrown when * a file could not be renamed. */ public static final int FILE_RENAME_FAILED_2 = 90024; /** * The error with code <code>90025</code> is thrown when * a file could not be deleted, because it is still in use * (only in Windows), or because an error occurred when deleting. */ public static final int FILE_DELETE_FAILED_1 = 90025; /** * The error with code <code>90026</code> is thrown when * an object could not be serialized. */ public static final int SERIALIZATION_FAILED_1 = 90026; /** * The error with code <code>90027</code> is thrown when * an object could not be de-serialized. */ public static final int DESERIALIZATION_FAILED_1 = 90027; /** * The error with code <code>90028</code> is thrown when * an input / output error occurred. For more information, see the root * cause of the exception. */ public static final int IO_EXCEPTION_1 = 90028; /** * The error with code <code>90029</code> is thrown when * calling ResultSet.deleteRow(), insertRow(), or updateRow() * when the current row is not updatable. * Example: * <pre> * ResultSet rs = stat.executeQuery("SELECT * FROM TEST"); * rs.next(); * rs.insertRow(); * </pre> */ public static final int NOT_ON_UPDATABLE_ROW = 90029; /** * The error with code <code>90030</code> is thrown when * the database engine has detected a checksum mismatch in the data * or index. To solve this problem, restore a backup or use the * Recovery tool (org.h2.tools.Recover). */ public static final int FILE_CORRUPTED_1 = 90030; /** * The error with code <code>90031</code> is thrown when * an input / output error occurred. For more information, see the root * cause of the exception. */ public static final int IO_EXCEPTION_2 = 90031; /** * The error with code <code>90032</code> is thrown when * trying to drop or alter a user that does not exist. * Example: * <pre> * DROP USER TEST_USER; * </pre> */ public static final int USER_NOT_FOUND_1 = 90032; /** * The error with code <code>90033</code> is thrown when * trying to create a user or role if a user with this name already exists. * Example: * <pre> * CREATE USER TEST_USER; * CREATE USER TEST_USER; * </pre> */ public static final int USER_ALREADY_EXISTS_1 = 90033; /** * The error with code <code>90034</code> is thrown when * writing to the trace file failed, for example because the there * is an I/O exception. This message is printed to System.out, * but only once. */ public static final int TRACE_FILE_ERROR_2 = 90034; /** * The error with code <code>90035</code> is thrown when * trying to create a sequence if a sequence with this name already * exists. * Example: * <pre> * CREATE SEQUENCE TEST_SEQ; * CREATE SEQUENCE TEST_SEQ; * </pre> */ public static final int SEQUENCE_ALREADY_EXISTS_1 = 90035; /** * The error with code <code>90036</code> is thrown when * trying to access a sequence that does not exist. * Example: * <pre> * SELECT NEXT VALUE FOR SEQUENCE XYZ; * </pre> */ public static final int SEQUENCE_NOT_FOUND_1 = 90036; /** * The error with code <code>90037</code> is thrown when * trying to drop or alter a view that does not exist. * Example: * <pre> * DROP VIEW XYZ; * </pre> */ public static final int VIEW_NOT_FOUND_1 = 90037; /** * The error with code <code>90038</code> is thrown when * trying to create a view if a view with this name already * exists. * Example: * <pre> * CREATE VIEW DUMMY AS SELECT * FROM DUAL; * CREATE VIEW DUMMY AS SELECT * FROM DUAL; * </pre> */ public static final int VIEW_ALREADY_EXISTS_1 = 90038; /** * The error with code <code>90039</code> is thrown when * trying to access a CLOB or BLOB object that timed out. * See the database setting LOB_TIMEOUT. */ public static final int LOB_CLOSED_ON_TIMEOUT_1 = 90039; /** * The error with code <code>90040</code> is thrown when * a user that is not administrator tries to execute a statement * that requires admin privileges. */ public static final int ADMIN_RIGHTS_REQUIRED = 90040; /** * The error with code <code>90041</code> is thrown when * trying to create a trigger and there is already a trigger with that name. * <pre> * CREATE TABLE TEST(ID INT); * CREATE TRIGGER TRIGGER_A AFTER INSERT ON TEST * CALL "org.h2.samples.TriggerSample$MyTrigger"; * CREATE TRIGGER TRIGGER_A AFTER INSERT ON TEST * CALL "org.h2.samples.TriggerSample$MyTrigger"; * </pre> */ public static final int TRIGGER_ALREADY_EXISTS_1 = 90041; /** * The error with code <code>90042</code> is thrown when * trying to drop a trigger that does not exist. * Example: * <pre> * DROP TRIGGER TRIGGER_XYZ; * </pre> */ public static final int TRIGGER_NOT_FOUND_1 = 90042; /** * The error with code <code>90043</code> is thrown when * there is an error initializing the trigger, for example because the * class does not implement the Trigger interface. * See the root cause for details. * Example: * <pre> * CREATE TABLE TEST(ID INT); * CREATE TRIGGER TRIGGER_A AFTER INSERT ON TEST * CALL "java.lang.String"; * </pre> */ public static final int ERROR_CREATING_TRIGGER_OBJECT_3 = 90043; /** * The error with code <code>90044</code> is thrown when * an exception or error occurred while calling the triggers fire method. * See the root cause for details. */ public static final int ERROR_EXECUTING_TRIGGER_3 = 90044; /** * The error with code <code>90045</code> is thrown when trying to create a * constraint if an object with this name already exists. Example: * <pre> * CREATE TABLE TEST(ID INT NOT NULL); * ALTER TABLE TEST ADD CONSTRAINT PK PRIMARY KEY(ID); * ALTER TABLE TEST ADD CONSTRAINT PK PRIMARY KEY(ID); * </pre> */ public static final int CONSTRAINT_ALREADY_EXISTS_1 = 90045; /** * The error with code <code>90046</code> is thrown when * trying to open a connection to a database using an unsupported URL * format. Please see the documentation on the supported URL format and * examples. Example: * <pre> * jdbc:h2:;; * </pre> */ public static final int URL_FORMAT_ERROR_2 = 90046; /** * The error with code <code>90047</code> is thrown when * trying to connect to a TCP server with an incompatible client. */ public static final int DRIVER_VERSION_ERROR_2 = 90047; /** * The error with code <code>90048</code> is thrown when * the file header of a database files (*.db) does not match the * expected version, or if it is corrupted. */ public static final int FILE_VERSION_ERROR_1 = 90048; /** * The error with code <code>90049</code> is thrown when * trying to open an encrypted database with the wrong file encryption * password or algorithm. */ public static final int FILE_ENCRYPTION_ERROR_1 = 90049; /** * The error with code <code>90050</code> is thrown when trying to open an * encrypted database, but not separating the file password from the user * password. The file password is specified in the password field, before * the user password. A single space needs to be added between the file * password and the user password; the file password itself may not contain * spaces. File passwords (as well as user passwords) are case sensitive. * Example of wrong usage: * <pre> * String url = &quot;jdbc:h2:&tilde;/test;CIPHER=AES&quot;; * String passwords = &quot;filePasswordUserPassword&quot;; * DriverManager.getConnection(url, &quot;sa&quot;, pwds); * </pre> * Correct: * <pre> * String url = &quot;jdbc:h2:&tilde;/test;CIPHER=AES&quot;; * String passwords = &quot;filePassword userPassword&quot;; * DriverManager.getConnection(url, &quot;sa&quot;, pwds); * </pre> */ public static final int WRONG_PASSWORD_FORMAT = 90050; /** * The error with code <code>90051</code> is thrown when * trying to use a scale that is > precision. * Example: * <pre> * CREATE TABLE TABLE1 ( FAIL NUMBER(6,24) ); * </pre> */ public static final int INVALID_VALUE_SCALE_PRECISION = 90051; /** * The error with code <code>90052</code> is thrown when * a subquery that is used as a value contains more than one column. * Example of wrong usage: * <pre> * CREATE TABLE TEST(ID INT); * INSERT INTO TEST VALUES(1), (2); * SELECT * FROM TEST WHERE ID IN (SELECT 1, 2 FROM DUAL); * </pre> * Correct: * <pre> * CREATE TABLE TEST(ID INT); * INSERT INTO TEST VALUES(1), (2); * SELECT * FROM TEST WHERE ID IN (1, 2); * </pre> */ public static final int SUBQUERY_IS_NOT_SINGLE_COLUMN = 90052; /** * The error with code <code>90053</code> is thrown when * a subquery that is used as a value contains more than one row. * Example: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * INSERT INTO TEST VALUES(1, 'Hello'), (1, 'World'); * SELECT X, (SELECT NAME FROM TEST WHERE ID=X) FROM DUAL; * </pre> */ public static final int SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW = 90053; /** * The error with code <code>90054</code> is thrown when * an aggregate function is used where it is not allowed. * Example: * <pre> * CREATE TABLE TEST(ID INT); * INSERT INTO TEST VALUES(1), (2); * SELECT MAX(ID) FROM TEST WHERE ID = MAX(ID) GROUP BY ID; * </pre> */ public static final int INVALID_USE_OF_AGGREGATE_FUNCTION_1 = 90054; /** * The error with code <code>90055</code> is thrown when * trying to open a database with an unsupported cipher algorithm. * Supported is AES. * Example: * <pre> * jdbc:h2:~/test;CIPHER=DES * </pre> */ public static final int UNSUPPORTED_CIPHER = 90055; /** * The error with code <code>90056</code> is thrown when trying to format a * timestamp using TO_DATE and TO_TIMESTAMP with an invalid format. */ public static final int INVALID_TO_DATE_FORMAT = 90056; /** * The error with code <code>90057</code> is thrown when * trying to drop a constraint that does not exist. * Example: * <pre> * CREATE TABLE TEST(ID INT); * ALTER TABLE TEST DROP CONSTRAINT CID; * </pre> */ public static final int CONSTRAINT_NOT_FOUND_1 = 90057; /** * The error with code <code>90058</code> is thrown when trying to call * commit or rollback inside a trigger, or when trying to call a method * inside a trigger that implicitly commits the current transaction, if an * object is locked. This is not because it would release the lock too * early. */ public static final int COMMIT_ROLLBACK_NOT_ALLOWED = 90058; /** * The error with code <code>90059</code> is thrown when * a query contains a column that could belong to multiple tables. * Example: * <pre> * CREATE TABLE PARENT(ID INT, NAME VARCHAR); * CREATE TABLE CHILD(PID INT, NAME VARCHAR); * SELECT ID, NAME FROM PARENT P, CHILD C WHERE P.ID = C.PID; * </pre> */ public static final int AMBIGUOUS_COLUMN_NAME_1 = 90059; /** * The error with code <code>90060</code> is thrown when * trying to use a file locking mechanism that is not supported. * Currently only FILE (the default) and SOCKET are supported * Example: * <pre> * jdbc:h2:~/test;FILE_LOCK=LDAP * </pre> */ public static final int UNSUPPORTED_LOCK_METHOD_1 = 90060; /** * The error with code <code>90061</code> is thrown when * trying to start a server if a server is already running at the same port. * It could also be a firewall problem. To find out if another server is * already running, run the following command on Windows: * <pre> * netstat -ano * </pre> * The column PID is the process id as listed in the Task Manager. * For Linux, use: * <pre> * netstat -npl * </pre> */ public static final int EXCEPTION_OPENING_PORT_2 = 90061; /** * The error with code <code>90062</code> is thrown when * a directory or file could not be created. This can occur when * trying to create a directory if a file with the same name already * exists, or vice versa. * */ public static final int FILE_CREATION_FAILED_1 = 90062; /** * The error with code <code>90063</code> is thrown when * trying to rollback to a savepoint that is not defined. * Example: * <pre> * ROLLBACK TO SAVEPOINT S_UNKNOWN; * </pre> */ public static final int SAVEPOINT_IS_INVALID_1 = 90063; /** * The error with code <code>90064</code> is thrown when * Savepoint.getSavepointName() is called on an unnamed savepoint. * Example: * <pre> * Savepoint sp = conn.setSavepoint(); * sp.getSavepointName(); * </pre> */ public static final int SAVEPOINT_IS_UNNAMED = 90064; /** * The error with code <code>90065</code> is thrown when * Savepoint.getSavepointId() is called on a named savepoint. * Example: * <pre> * Savepoint sp = conn.setSavepoint("Joe"); * sp.getSavepointId(); * </pre> */ public static final int SAVEPOINT_IS_NAMED = 90065; /** * The error with code <code>90066</code> is thrown when * the same property appears twice in the database URL or in * the connection properties. * Example: * <pre> * jdbc:h2:~/test;LOCK_TIMEOUT=0;LOCK_TIMEOUT=1 * </pre> */ public static final int DUPLICATE_PROPERTY_1 = 90066; /** * The error with code <code>90067</code> is thrown when the client could * not connect to the database, or if the connection was lost. Possible * reasons are: the database server is not running at the given port, the * connection was closed due to a shutdown, or the server was stopped. Other * possible causes are: the server is not an H2 server, or the network * connection is broken. */ public static final int CONNECTION_BROKEN_1 = 90067; /** * The error with code <code>90068</code> is thrown when the given * expression that is used in the ORDER BY is not in the result list. This * is required for distinct queries, otherwise the result would be * ambiguous. * Example of wrong usage: * <pre> * CREATE TABLE TEST(ID INT, NAME VARCHAR); * INSERT INTO TEST VALUES(2, 'Hello'), (1, 'Hello'); * SELECT DISTINCT NAME FROM TEST ORDER BY ID; * Order by expression ID must be in the result list in this case * </pre> * Correct: * <pre> * SELECT DISTINCT ID, NAME FROM TEST ORDER BY ID; * </pre> */ public static final int ORDER_BY_NOT_IN_RESULT = 90068; /** * The error with code <code>90069</code> is thrown when * trying to create a role if an object with this name already exists. * Example: * <pre> * CREATE ROLE TEST_ROLE; * CREATE ROLE TEST_ROLE; * </pre> */ public static final int ROLE_ALREADY_EXISTS_1 = 90069; /** * The error with code <code>90070</code> is thrown when * trying to drop or grant a role that does not exists. * Example: * <pre> * DROP ROLE TEST_ROLE_2; * </pre> */ public static final int ROLE_NOT_FOUND_1 = 90070; /** * The error with code <code>90071</code> is thrown when * trying to grant or revoke if no role or user with that name exists. * Example: * <pre> * GRANT SELECT ON TEST TO UNKNOWN; * </pre> */ public static final int USER_OR_ROLE_NOT_FOUND_1 = 90071; /** * The error with code <code>90072</code> is thrown when * trying to grant or revoke both roles and rights at the same time. * Example: * <pre> * GRANT SELECT, TEST_ROLE ON TEST TO SA; * </pre> */ public static final int ROLES_AND_RIGHT_CANNOT_BE_MIXED = 90072; /** * The error with code <code>90073</code> is thrown when trying to create * an alias for a Java method, if two methods exists in this class that have * this name and the same number of parameters. * Example of wrong usage: * <pre> * CREATE ALIAS GET_LONG FOR * "java.lang.Long.getLong"; * </pre> * Correct: * <pre> * CREATE ALIAS GET_LONG FOR * "java.lang.Long.getLong(java.lang.String, java.lang.Long)"; * </pre> */ public static final int METHODS_MUST_HAVE_DIFFERENT_PARAMETER_COUNTS_2 = 90073; /** * The error with code <code>90074</code> is thrown when * trying to grant a role that has already been granted. * Example: * <pre> * CREATE ROLE TEST_A; * CREATE ROLE TEST_B; * GRANT TEST_A TO TEST_B; * GRANT TEST_B TO TEST_A; * </pre> */ public static final int ROLE_ALREADY_GRANTED_1 = 90074; /** * The error with code <code>90075</code> is thrown when * trying to alter a table and allow null for a column that is part of a * primary key or hash index. * Example: * <pre> * CREATE TABLE TEST(ID INT PRIMARY KEY); * ALTER TABLE TEST ALTER COLUMN ID NULL; * </pre> */ public static final int COLUMN_IS_PART_OF_INDEX_1 = 90075; /** * The error with code <code>90076</code> is thrown when * trying to create a function alias for a system function or for a function * that is already defined. * Example: * <pre> * CREATE ALIAS SQRT FOR "java.lang.Math.sqrt" * </pre> */ public static final int FUNCTION_ALIAS_ALREADY_EXISTS_1 = 90076; /** * The error with code <code>90077</code> is thrown when * trying to drop a system function or a function alias that does not exist. * Example: * <pre> * DROP ALIAS SQRT; * </pre> */ public static final int FUNCTION_ALIAS_NOT_FOUND_1 = 90077; /** * The error with code <code>90078</code> is thrown when * trying to create a schema if an object with this name already exists. * Example: * <pre> * CREATE SCHEMA TEST_SCHEMA; * CREATE SCHEMA TEST_SCHEMA; * </pre> */ public static final int SCHEMA_ALREADY_EXISTS_1 = 90078; /** * The error with code <code>90079</code> is thrown when * trying to drop a schema that does not exist. * Example: * <pre> * DROP SCHEMA UNKNOWN; * </pre> */ public static final int SCHEMA_NOT_FOUND_1 = 90079; /** * The error with code <code>90080</code> is thrown when * trying to rename a object to a different schema, or when trying to * create a related object in another schema. * For CREATE LINKED TABLE, it is thrown when multiple tables with that * name exist in different schemas. * Example: * <pre> * CREATE SCHEMA TEST_SCHEMA; * CREATE TABLE TEST(ID INT); * CREATE INDEX TEST_ID ON TEST(ID); * ALTER INDEX TEST_ID RENAME TO TEST_SCHEMA.IDX_TEST_ID; * </pre> */ public static final int SCHEMA_NAME_MUST_MATCH = 90080; /** * The error with code <code>90081</code> is thrown when * trying to alter a column to not allow NULL, if there * is already data in the table where this column is NULL. * Example: * <pre> * CREATE TABLE TEST(ID INT); * INSERT INTO TEST VALUES(NULL); * ALTER TABLE TEST ALTER COLUMN ID VARCHAR NOT NULL; * </pre> */ public static final int COLUMN_CONTAINS_NULL_VALUES_1 = 90081; /** * The error with code <code>90082</code> is thrown when * trying to drop a system generated sequence. */ public static final int SEQUENCE_BELONGS_TO_A_TABLE_1 = 90082; /** * The error with code <code>90083</code> is thrown when * trying to drop a column that is part of a constraint. * Example: * <pre> * CREATE TABLE TEST(ID INT, PID INT REFERENCES(ID)); * ALTER TABLE TEST DROP COLUMN PID; * </pre> */ public static final int COLUMN_IS_REFERENCED_1 = 90083; /** * The error with code <code>90084</code> is thrown when * trying to drop the last column of a table. * Example: * <pre> * CREATE TABLE TEST(ID INT); * ALTER TABLE TEST DROP COLUMN ID; * </pre> */ public static final int CANNOT_DROP_LAST_COLUMN = 90084; /** * The error with code <code>90085</code> is thrown when * trying to manually drop an index that was generated by the system * because of a unique or referential constraint. To find out what * constraint causes the problem, run: * <pre> * SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS * WHERE UNIQUE_INDEX_NAME = '&lt;index name&gt;'; * </pre> * Example of wrong usage: * <pre> * CREATE TABLE TEST(ID INT, CONSTRAINT UID UNIQUE(ID)); * DROP INDEX UID_INDEX_0; * Index UID_INDEX_0 belongs to constraint UID * </pre> * Correct: * <pre> * ALTER TABLE TEST DROP CONSTRAINT UID; * </pre> */ public static final int INDEX_BELONGS_TO_CONSTRAINT_2 = 90085; /** * The error with code <code>90086</code> is thrown when * a class can not be loaded because it is not in the classpath * or because a related class is not in the classpath. * Example: * <pre> * CREATE ALIAS TEST FOR "java.lang.invalid.Math.sqrt"; * </pre> */ public static final int CLASS_NOT_FOUND_1 = 90086; /** * The error with code <code>90087</code> is thrown when * a method with matching number of arguments was not found in the class. * Example: * <pre> * CREATE ALIAS TO_BINARY FOR "java.lang.Long.toBinaryString(long)"; * CALL TO_BINARY(10, 2); * </pre> */ public static final int METHOD_NOT_FOUND_1 = 90087; /** * The error with code <code>90088</code> is thrown when * trying to switch to an unknown mode. * Example: * <pre> * SET MODE UNKNOWN; * </pre> */ public static final int UNKNOWN_MODE_1 = 90088; /** * The error with code <code>90089</code> is thrown when * trying to change the collation while there was already data in * the database. The collation of the database must be set when the * database is empty. * Example of wrong usage: * <pre> * CREATE TABLE TEST(NAME VARCHAR PRIMARY KEY); * INSERT INTO TEST VALUES('Hello', 'World'); * SET COLLATION DE; * Collation cannot be changed because there is a data table: PUBLIC.TEST * </pre> * Correct: * <pre> * SET COLLATION DE; * CREATE TABLE TEST(NAME VARCHAR PRIMARY KEY); * INSERT INTO TEST VALUES('Hello', 'World'); * </pre> */ public static final int COLLATION_CHANGE_WITH_DATA_TABLE_1 = 90089; /** * The error with code <code>90090</code> is thrown when * trying to drop a schema that may not be dropped (the schema PUBLIC * and the schema INFORMATION_SCHEMA). * Example: * <pre> * DROP SCHEMA PUBLIC; * </pre> */ public static final int SCHEMA_CAN_NOT_BE_DROPPED_1 = 90090; /** * The error with code <code>90091</code> is thrown when * trying to drop the role PUBLIC. * Example: * <pre> * DROP ROLE PUBLIC; * </pre> */ public static final int ROLE_CAN_NOT_BE_DROPPED_1 = 90091; /** * The error with code <code>90093</code> is thrown when * trying to connect to a clustered database that runs in standalone * mode. This can happen if clustering is not enabled on the database, * or if one of the clients disabled clustering because it can not see * the other cluster node. */ public static final int CLUSTER_ERROR_DATABASE_RUNS_ALONE = 90093; /** * The error with code <code>90094</code> is thrown when * trying to connect to a clustered database that runs together with a * different cluster node setting than what is used when trying to connect. */ public static final int CLUSTER_ERROR_DATABASE_RUNS_CLUSTERED_1 = 90094; /** * The error with code <code>90095</code> is thrown when * calling the method STRINGDECODE with an invalid escape sequence. * Only Java style escape sequences and Java properties file escape * sequences are supported. * Example: * <pre> * CALL STRINGDECODE('\i'); * </pre> */ public static final int STRING_FORMAT_ERROR_1 = 90095; /** * The error with code <code>90096</code> is thrown when * trying to perform an operation with a non-admin user if the * user does not have enough rights. */ public static final int NOT_ENOUGH_RIGHTS_FOR_1 = 90096; /** * The error with code <code>90097</code> is thrown when * trying to delete or update a database if it is open in read-only mode. * Example: * <pre> * jdbc:h2:~/test;ACCESS_MODE_DATA=R * CREATE TABLE TEST(ID INT); * </pre> */ public static final int DATABASE_IS_READ_ONLY = 90097; /** * The error with code <code>90098</code> is thrown when the database has * been closed, for example because the system ran out of memory or because * the self-destruction counter has reached zero. This counter is only used * for recovery testing, and not set in normal operation. */ public static final int DATABASE_IS_CLOSED = 90098; /** * The error with code <code>90099</code> is thrown when an error occurred * trying to initialize the database event listener. Example: * <pre> * jdbc:h2:&tilde;/test;DATABASE_EVENT_LISTENER='java.lang.String' * </pre> */ public static final int ERROR_SETTING_DATABASE_EVENT_LISTENER_2 = 90099; /** * The error with code <code>90101</code> is thrown when * the XA API detected unsupported transaction names. This can happen * when mixing application generated transaction names and transaction names * generated by this databases XAConnection API. */ public static final int WRONG_XID_FORMAT_1 = 90101; /** * The error with code <code>90102</code> is thrown when * trying to use unsupported options for the given compression algorithm. * Example of wrong usage: * <pre> * CALL COMPRESS(STRINGTOUTF8(SPACE(100)), 'DEFLATE l 10'); * </pre> * Correct: * <pre> * CALL COMPRESS(STRINGTOUTF8(SPACE(100)), 'DEFLATE l 9'); * </pre> */ public static final int UNSUPPORTED_COMPRESSION_OPTIONS_1 = 90102; /** * The error with code <code>90103</code> is thrown when * trying to use an unsupported compression algorithm. * Example: * <pre> * CALL COMPRESS(STRINGTOUTF8(SPACE(100)), 'BZIP'); * </pre> */ public static final int UNSUPPORTED_COMPRESSION_ALGORITHM_1 = 90103; /** * The error with code <code>90104</code> is thrown when * the data can not be de-compressed. * Example: * <pre> * CALL EXPAND(X'00FF'); * </pre> */ public static final int COMPRESSION_ERROR = 90104; /** * The error with code <code>90105</code> is thrown when * an exception occurred in a user-defined method. * Example: * <pre> * CREATE ALIAS SYS_PROP FOR "java.lang.System.getProperty"; * CALL SYS_PROP(NULL); * </pre> */ public static final int EXCEPTION_IN_FUNCTION_1 = 90105; /** * The error with code <code>90106</code> is thrown when * trying to truncate a table that can not be truncated. * Tables with referential integrity constraints can not be truncated. * Also, system tables and view can not be truncated. * Example: * <pre> * TRUNCATE TABLE INFORMATION_SCHEMA.SETTINGS; * </pre> */ public static final int CANNOT_TRUNCATE_1 = 90106; /** * The error with code <code>90107</code> is thrown when * trying to drop an object because another object would become invalid. * Example: * <pre> * CREATE TABLE COUNT(X INT); * CREATE TABLE ITEMS(ID INT DEFAULT SELECT MAX(X)+1 FROM COUNT); * DROP TABLE COUNT; * </pre> */ public static final int CANNOT_DROP_2 = 90107; /** * The error with code <code>90108</code> is thrown when not enough heap * memory was available. A possible solutions is to increase the memory size * using <code>java -Xmx128m ...</code>. Another solution is to reduce * the cache size. */ public static final int OUT_OF_MEMORY = 90108; /** * The error with code <code>90109</code> is thrown when * trying to run a query against an invalid view. * Example: * <pre> * CREATE FORCE VIEW TEST_VIEW AS SELECT * FROM TEST; * SELECT * FROM TEST_VIEW; * </pre> */ public static final int VIEW_IS_INVALID_2 = 90109; /** * The error with code <code>90111</code> is thrown when * an exception occurred while accessing a linked table. */ public static final int ERROR_ACCESSING_LINKED_TABLE_2 = 90111; /** * The error with code <code>90112</code> is thrown when a row was deleted * twice while locking was disabled. This is an intern exception that should * never be thrown to the application, because such deleted should be * detected and the resulting exception ignored inside the database engine. * <pre> * Row not found when trying to delete from index UID_INDEX_0 * </pre> */ public static final int ROW_NOT_FOUND_WHEN_DELETING_1 = 90112; /** * The error with code <code>90113</code> is thrown when * the database URL contains unsupported settings. * Example: * <pre> * jdbc:h2:~/test;UNKNOWN=TRUE * </pre> */ public static final int UNSUPPORTED_SETTING_1 = 90113; /** * The error with code <code>90114</code> is thrown when * trying to create a constant if a constant with this name already exists. * Example: * <pre> * CREATE CONSTANT TEST VALUE 1; * CREATE CONSTANT TEST VALUE 1; * </pre> */ public static final int CONSTANT_ALREADY_EXISTS_1 = 90114; /** * The error with code <code>90115</code> is thrown when * trying to drop a constant that does not exists. * Example: * <pre> * DROP CONSTANT UNKNOWN; * </pre> */ public static final int CONSTANT_NOT_FOUND_1 = 90115; /** * The error with code <code>90116</code> is thrown when * trying use a literal in a SQL statement if literals are disabled. * If literals are disabled, use PreparedStatement and parameters instead * of literals in the SQL statement. * Example: * <pre> * SET ALLOW_LITERALS NONE; * CALL 1+1; * </pre> */ public static final int LITERALS_ARE_NOT_ALLOWED = 90116; /** * The error with code <code>90117</code> is thrown when * trying to connect to a TCP server from another machine, if remote * connections are not allowed. To allow remote connections, * start the TCP server using the option -tcpAllowOthers as in: * <pre> * java org.h2.tools.Server -tcp -tcpAllowOthers * </pre> * Or, when starting the server from an application, use: * <pre> * Server server = Server.createTcpServer("-tcpAllowOthers"); * server.start(); * </pre> */ public static final int REMOTE_CONNECTION_NOT_ALLOWED = 90117; /** * The error with code <code>90118</code> is thrown when * trying to drop a table can not be dropped. * Example: * <pre> * DROP TABLE INFORMATION_SCHEMA.SETTINGS; * </pre> */ public static final int CANNOT_DROP_TABLE_1 = 90118; /** * The error with code <code>90119</code> is thrown when * trying to create a domain if an object with this name already exists, * or when trying to overload a built-in data type. * Example: * <pre> * CREATE DOMAIN INTEGER AS VARCHAR; * CREATE DOMAIN EMAIL AS VARCHAR CHECK LOCATE('@', VALUE) > 0; * CREATE DOMAIN EMAIL AS VARCHAR CHECK LOCATE('@', VALUE) > 0; * </pre> */ public static final int USER_DATA_TYPE_ALREADY_EXISTS_1 = 90119; /** * The error with code <code>90120</code> is thrown when * trying to drop a domain that doesn't exist. * Example: * <pre> * DROP DOMAIN UNKNOWN; * </pre> */ public static final int USER_DATA_TYPE_NOT_FOUND_1 = 90120; /** * The error with code <code>90121</code> is thrown when * a database operation is started while the virtual machine exits * (for example in a shutdown hook), or when the session is closed. */ public static final int DATABASE_CALLED_AT_SHUTDOWN = 90121; /** * The error with code <code>90123</code> is thrown when * trying mix regular parameters and indexed parameters in the same * statement. Example: * <pre> * SELECT ?, ?1 FROM DUAL; * </pre> */ public static final int CANNOT_MIX_INDEXED_AND_UNINDEXED_PARAMS = 90123; /** * The error with code <code>90124</code> is thrown when * trying to access a file that doesn't exist. This can occur when trying to * read a lob if the lob file has been deleted by another application. */ public static final int FILE_NOT_FOUND_1 = 90124; /** * The error with code <code>90125</code> is thrown when * PreparedStatement.setBigDecimal is called with object that extends the * class BigDecimal, and the system property h2.allowBigDecimalExtensions is * not set. Using extensions of BigDecimal is dangerous because the database * relies on the behavior of BigDecimal. Example of wrong usage: * <pre> * BigDecimal bd = new MyDecimal("$10.3"); * prep.setBigDecimal(1, bd); * Invalid class, expected java.math.BigDecimal but got MyDecimal * </pre> * Correct: * <pre> * BigDecimal bd = new BigDecimal(&quot;10.3&quot;); * prep.setBigDecimal(1, bd); * </pre> */ public static final int INVALID_CLASS_2 = 90125; /** * The error with code <code>90126</code> is thrown when * trying to call the BACKUP statement for an in-memory database. * Example: * <pre> * jdbc:h2:mem: * BACKUP TO 'test.zip'; * </pre> */ public static final int DATABASE_IS_NOT_PERSISTENT = 90126; /** * The error with code <code>90127</code> is thrown when * trying to update or delete a row in a result set if the result set is * not updatable. Result sets are only updatable if: * the statement was created with updatable concurrency; * all columns of the result set are from the same table; * the table is a data table (not a system table or view); * all columns of the primary key or any unique index are included; * all columns of the result set are columns of that table. */ public static final int RESULT_SET_NOT_UPDATABLE = 90127; /** * The error with code <code>90128</code> is thrown when * trying to call a method of the ResultSet that is only supported * for scrollable result sets, and the result set is not scrollable. * Example: * <pre> * rs.first(); * </pre> */ public static final int RESULT_SET_NOT_SCROLLABLE = 90128; /** * The error with code <code>90129</code> is thrown when * trying to commit a transaction that doesn't exist. * Example: * <pre> * PREPARE COMMIT ABC; * COMMIT TRANSACTION TEST; * </pre> */ public static final int TRANSACTION_NOT_FOUND_1 = 90129; /** * The error with code <code>90130</code> is thrown when * an execute method of PreparedStatement was called with a SQL statement. * This is not allowed according to the JDBC specification. Instead, use * an execute method of Statement. * Example of wrong usage: * <pre> * PreparedStatement prep = conn.prepareStatement("SELECT * FROM TEST"); * prep.execute("DELETE FROM TEST"); * </pre> * Correct: * <pre> * Statement stat = conn.createStatement(); * stat.execute("DELETE FROM TEST"); * </pre> */ public static final int METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT = 90130; /** * The error with code <code>90131</code> is thrown when using multi version * concurrency control, and trying to update the same row from within two * connections at the same time, or trying to insert two rows with the same * key from two connections. Example: * <pre> * jdbc:h2:~/test;MVCC=TRUE * Session 1: * CREATE TABLE TEST(ID INT); * INSERT INTO TEST VALUES(1); * SET AUTOCOMMIT FALSE; * UPDATE TEST SET ID = 2; * Session 2: * SET AUTOCOMMIT FALSE; * UPDATE TEST SET ID = 3; * </pre> */ public static final int CONCURRENT_UPDATE_1 = 90131; /** * The error with code <code>90132</code> is thrown when * trying to drop a user-defined aggregate function that doesn't exist. * Example: * <pre> * DROP AGGREGATE UNKNOWN; * </pre> */ public static final int AGGREGATE_NOT_FOUND_1 = 90132; /** * The error with code <code>90133</code> is thrown when * trying to change a specific database property while the database is * already open. The MVCC property needs to be set in the first connection * (in the connection opening the database) and can not be changed later on. */ public static final int CANNOT_CHANGE_SETTING_WHEN_OPEN_1 = 90133; /** * The error with code <code>90134</code> is thrown when * trying to load a Java class that is not part of the allowed classes. By * default, all classes are allowed, but this can be changed using the * system property h2.allowedClasses. */ public static final int ACCESS_DENIED_TO_CLASS_1 = 90134; /** * The error with code <code>90135</code> is thrown when * trying to open a connection to a database that is currently open * in exclusive mode. The exclusive mode is set using: * <pre> * SET EXCLUSIVE TRUE; * </pre> */ public static final int DATABASE_IS_IN_EXCLUSIVE_MODE = 90135; /** * The error with code <code>90136</code> is thrown when * executing a query that used an unsupported outer join condition. * Example: * <pre> * SELECT * FROM DUAL A LEFT JOIN DUAL B ON B.X=(SELECT MAX(X) FROM DUAL); * </pre> */ public static final int UNSUPPORTED_OUTER_JOIN_CONDITION_1 = 90136; /** * The error with code <code>90137</code> is thrown when * trying to assign a value to something that is not a variable. * <pre> * SELECT AMOUNT, SET(@V, IFNULL(@V, 0)+AMOUNT) FROM TEST; * </pre> */ public static final int CAN_ONLY_ASSIGN_TO_VARIABLE_1 = 90137; /** * The error with code <code>90138</code> is thrown when * * trying to open a persistent database using an incorrect database name. * The name of a persistent database contains the path and file name prefix * where the data is stored. The file name part of a database name must be * at least two characters. * * Example of wrong usage: * <pre> * DriverManager.getConnection("jdbc:h2:~/t"); * DriverManager.getConnection("jdbc:h2:~/test/"); * </pre> * Correct: * <pre> * DriverManager.getConnection("jdbc:h2:~/te"); * DriverManager.getConnection("jdbc:h2:~/test/te"); * </pre> */ public static final int INVALID_DATABASE_NAME_1 = 90138; /** * The error with code <code>90139</code> is thrown when * the specified public static Java method was not found in the class. * Example: * <pre> * CREATE ALIAS TEST FOR "java.lang.Math.test"; * </pre> */ public static final int PUBLIC_STATIC_JAVA_METHOD_NOT_FOUND_1 = 90139; /** * The error with code <code>90140</code> is thrown when trying to update or * delete a row in a result set if the statement was not created with * updatable concurrency. Result sets are only updatable if the statement * was created with updatable concurrency, and if the result set contains * all columns of the primary key or of a unique index of a table. */ public static final int RESULT_SET_READONLY = 90140; /** * The error with code <code>90141</code> is thrown when * trying to change the java object serializer while there was already data * in the database. The serializer of the database must be set when the * database is empty. */ public static final int JAVA_OBJECT_SERIALIZER_CHANGE_WITH_DATA_TABLE = 90141; /** * The error with code <code>90142</code> is thrown when * trying to set zero for step size. */ public static final int STEP_SIZE_MUST_NOT_BE_ZERO = 90142; /** * The error with code <code>90143</code> is thrown when * trying to fetch a row from the primary index and the row is not there. * Can happen in MULTI_THREADED=1 case. */ public static final int ROW_NOT_FOUND_IN_PRIMARY_INDEX = 90143; // next are 90110, 90122, 90144 private ErrorCode() { // utility class } /** * INTERNAL */ public static boolean isCommon(int errorCode) { // this list is sorted alphabetically switch (errorCode) { case DATA_CONVERSION_ERROR_1: case DUPLICATE_KEY_1: case FUNCTION_ALIAS_ALREADY_EXISTS_1: case LOCK_TIMEOUT_1: case NULL_NOT_ALLOWED: case NO_DATA_AVAILABLE: case NUMERIC_VALUE_OUT_OF_RANGE_1: case OBJECT_CLOSED: case REFERENTIAL_INTEGRITY_VIOLATED_CHILD_EXISTS_1: case REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1: case SYNTAX_ERROR_1: case SYNTAX_ERROR_2: case TABLE_OR_VIEW_ALREADY_EXISTS_1: case TABLE_OR_VIEW_NOT_FOUND_1: case VALUE_TOO_LONG_2: return true; } return false; } /** * INTERNAL */ public static String getState(int errorCode) { // To convert SQLState to error code, replace // 21S: 210, 42S: 421, HY: 50, C: 1, T: 2 switch (errorCode) { // 02: no data case NO_DATA_AVAILABLE: return "02000"; // 07: dynamic SQL error case INVALID_PARAMETER_COUNT_2: return "07001"; // 08: connection exception case ERROR_OPENING_DATABASE_1: return "08000"; // 21: cardinality violation case COLUMN_COUNT_DOES_NOT_MATCH: return "21S02"; // 42: syntax error or access rule violation case TABLE_OR_VIEW_ALREADY_EXISTS_1: return "42S01"; case TABLE_OR_VIEW_NOT_FOUND_1: return "42S02"; case INDEX_ALREADY_EXISTS_1: return "42S11"; case INDEX_NOT_FOUND_1: return "42S12"; case DUPLICATE_COLUMN_NAME_1: return "42S21"; case COLUMN_NOT_FOUND_1: return "42S22"; // 0A: feature not supported // HZ: remote database access // HY case GENERAL_ERROR_1: return "HY000"; case UNKNOWN_DATA_TYPE_1: return "HY004"; case FEATURE_NOT_SUPPORTED_1: return "HYC00"; case LOCK_TIMEOUT_1: return "HYT00"; default: return "" + errorCode; } } }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/JavaObjectSerializer.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; /** * Custom serialization mechanism for java objects being stored in column of * type OTHER. * * @author Sergi Vladykin */ public interface JavaObjectSerializer { /** * Serialize object to byte array. * * @param obj the object to serialize * @return the byte array of the serialized object */ byte[] serialize(Object obj) throws Exception; /** * Deserialize object from byte array. * * @param bytes the byte array of the serialized object * @return the object */ Object deserialize(byte[] bytes) throws Exception; }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/TableEngine.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import org.h2.table.Table; import org.h2.command.ddl.CreateTableData; /** * A class that implements this interface can create custom table * implementations. * * @author Sergi Vladykin */ public interface TableEngine { /** * Create new table. * * @param data the data to construct the table * @return the created table */ Table createTable(CreateTableData data); }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/TimestampWithTimeZone.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import java.io.Serializable; import org.h2.util.DateTimeUtils; /** * How we expose "TIMESTAMP WITH TIME ZONE" in our ResultSets. */ public class TimestampWithTimeZone implements Serializable, Cloneable { /** * The serial version UID. */ private static final long serialVersionUID = 4413229090646777107L; /** * A bit field with bits for the year, month, and day (see DateTimeUtils for * encoding) */ private final long dateValue; /** * The nanoseconds since midnight. */ private final long timeNanos; /** * Time zone offset from UTC in minutes, range of -12hours to +12hours */ private final short timeZoneOffsetMins; public TimestampWithTimeZone(long dateValue, long timeNanos, short timeZoneOffsetMins) { this.dateValue = dateValue; this.timeNanos = timeNanos; this.timeZoneOffsetMins = timeZoneOffsetMins; } /** * @return the year-month-day bit field */ public long getYMD() { return dateValue; } /** * Gets the year. * * <p>The year is in the specified time zone and not UTC. So for * {@code 2015-12-31 19:00:00.00-10:00} the value returned * will be {@code 2015} even though in UTC the year is {@code 2016}.</p> * * @return the year */ public int getYear() { return DateTimeUtils.yearFromDateValue(dateValue); } /** * Gets the month 1-based. * * <p>The month is in the specified time zone and not UTC. So for * {@code 2015-12-31 19:00:00.00-10:00} the value returned * is {@code 12} even though in UTC the month is {@code 1}.</p> * * @return the month */ public int getMonth() { return DateTimeUtils.monthFromDateValue(dateValue); } /** * Gets the day of month 1-based. * * <p>The day of month is in the specified time zone and not UTC. So for * {@code 2015-12-31 19:00:00.00-10:00} the value returned * is {@code 31} even though in UTC the day of month is {@code 1}.</p> * * @return the day of month */ public int getDay() { return DateTimeUtils.dayFromDateValue(dateValue); } /** * Gets the nanoseconds since midnight. * * <p>The nanoseconds are relative to midnight in the specified * time zone. So for {@code 2016-09-24 00:00:00.000000001-00:01} the * value returned is {@code 1} even though {@code 60000000001} * nanoseconds have passed since midnight in UTC.</p> * * @return the nanoseconds since midnight */ public long getNanosSinceMidnight() { return timeNanos; } /** * The time zone offset in minutes. * * @return the offset */ public short getTimeZoneOffsetMins() { return timeZoneOffsetMins; } @Override public String toString() { return DateTimeUtils.timestampTimeZoneToString(dateValue, timeNanos, timeZoneOffsetMins); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (dateValue ^ (dateValue >>> 32)); result = prime * result + (int) (timeNanos ^ (timeNanos >>> 32)); result = prime * result + timeZoneOffsetMins; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimestampWithTimeZone other = (TimestampWithTimeZone) obj; if (dateValue != other.dateValue) { return false; } if (timeNanos != other.timeNanos) { return false; } if (timeZoneOffsetMins != other.timeZoneOffsetMins) { return false; } return true; } }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/api/Trigger.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import java.sql.Connection; import java.sql.SQLException; /** * A class that implements this interface can be used as a trigger. */ public interface Trigger { /** * The trigger is called for INSERT statements. */ int INSERT = 1; /** * The trigger is called for UPDATE statements. */ int UPDATE = 2; /** * The trigger is called for DELETE statements. */ int DELETE = 4; /** * The trigger is called for SELECT statements. */ int SELECT = 8; /** * This method is called by the database engine once when initializing the * trigger. It is called when the trigger is created, as well as when the * database is opened. The type of operation is a bit field with the * appropriate flags set. As an example, if the trigger is of type INSERT * and UPDATE, then the parameter type is set to (INSERT | UPDATE). * * @param conn a connection to the database (a system connection) * @param schemaName the name of the schema * @param triggerName the name of the trigger used in the CREATE TRIGGER * statement * @param tableName the name of the table * @param before whether the fire method is called before or after the * operation is performed * @param type the operation type: INSERT, UPDATE, DELETE, SELECT, or a * combination (this parameter is a bit field) */ void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before, int type) throws SQLException; /** * This method is called for each triggered action. The method is called * immediately when the operation occurred (before it is committed). A * transaction rollback will also rollback the operations that were done * within the trigger, if the operations occurred within the same database. * If the trigger changes state outside the database, a rollback trigger * should be used. * <p> * The row arrays contain all columns of the table, in the same order * as defined in the table. * </p> * <p> * The trigger itself may change the data in the newRow array. * </p> * * @param conn a connection to the database * @param oldRow the old row, or null if no old row is available (for * INSERT) * @param newRow the new row, or null if no new row is available (for * DELETE) * @throws SQLException if the operation must be undone */ void fire(Connection conn, Object[] oldRow, Object[] newRow) throws SQLException; /** * This method is called when the database is closed. * If the method throws an exception, it will be logged, but * closing the database will continue. */ void close() throws SQLException; /** * This method is called when the trigger is dropped. */ void remove() throws SQLException; }
0
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/Bnf.java
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.bnf; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import org.h2.bnf.context.DbContextRule; import org.h2.tools.Csv; import org.h2.util.New; import org.h2.util.StringUtils; import org.h2.util.Utils; /** * This class can read a file that is similar to BNF (Backus-Naur form). * It is made specially to support SQL grammar. */ public class Bnf { /** * The rule map. The key is lowercase, and all spaces * are replaces with underscore. */ private final HashMap<String, RuleHead> ruleMap = new HashMap<>(); private String syntax; private String currentToken; private String[] tokens; private char firstChar; private int index; private Rule lastRepeat; private ArrayList<RuleHead> statements; private String currentTopic; /** * Create an instance using the grammar specified in the CSV file. * * @param csv if not specified, the help.csv is used * @return a new instance */ public static Bnf getInstance(Reader csv) throws SQLException, IOException { Bnf bnf = new Bnf(); if (csv == null) { byte[] data = Utils.getResource("/org/h2/res/help.csv"); csv = new InputStreamReader(new ByteArrayInputStream(data)); } bnf.parse(csv); return bnf; } /** * Add an alias for a rule. * * @param name for example "procedure" * @param replacement for example "@func@" */ public void addAlias(String name, String replacement) { RuleHead head = ruleMap.get(replacement); ruleMap.put(name, head); } private void addFixedRule(String name, int fixedType) { Rule rule = new RuleFixed(fixedType); addRule(name, "Fixed", rule); } private RuleHead addRule(String topic, String section, Rule rule) { RuleHead head = new RuleHead(section, topic, rule); String key = StringUtils.toLowerEnglish(topic.trim().replace(' ', '_')); if (ruleMap.get(key) != null) { throw new AssertionError("already exists: " + topic); } ruleMap.put(key, head); return head; } private void parse(Reader reader) throws SQLException, IOException { Rule functions = null; statements = New.arrayList(); Csv csv = new Csv(); csv.setLineCommentCharacter('#'); ResultSet rs = csv.read(reader, null); while (rs.next()) { String section = rs.getString("SECTION").trim(); if (section.startsWith("System")) { continue; } String topic = rs.getString("TOPIC"); syntax = rs.getString("SYNTAX").trim(); currentTopic = section; tokens = tokenize(); index = 0; Rule rule = parseRule(); if (section.startsWith("Command")) { rule = new RuleList(rule, new RuleElement(";\n\n", currentTopic), false); } RuleHead head = addRule(topic, section, rule); if (section.startsWith("Function")) { if (functions == null) { functions = rule; } else { functions = new RuleList(rule, functions, true); } } else if (section.startsWith("Commands")) { statements.add(head); } } addRule("@func@", "Function", functions); addFixedRule("@ymd@", RuleFixed.YMD); addFixedRule("@hms@", RuleFixed.HMS); addFixedRule("@nanos@", RuleFixed.NANOS); addFixedRule("anything_except_single_quote", RuleFixed.ANY_EXCEPT_SINGLE_QUOTE); addFixedRule("anything_except_double_quote", RuleFixed.ANY_EXCEPT_DOUBLE_QUOTE); addFixedRule("anything_until_end_of_line", RuleFixed.ANY_UNTIL_EOL); addFixedRule("anything_until_end_comment", RuleFixed.ANY_UNTIL_END); addFixedRule("anything_except_two_dollar_signs", RuleFixed.ANY_EXCEPT_2_DOLLAR); addFixedRule("anything", RuleFixed.ANY_WORD); addFixedRule("@hex_start@", RuleFixed.HEX_START); addFixedRule("@concat@", RuleFixed.CONCAT); addFixedRule("@az_@", RuleFixed.AZ_UNDERSCORE); addFixedRule("@af@", RuleFixed.AF); addFixedRule("@digit@", RuleFixed.DIGIT); addFixedRule("@open_bracket@", RuleFixed.OPEN_BRACKET); addFixedRule("@close_bracket@", RuleFixed.CLOSE_BRACKET); } /** * Parse the syntax and let the rule call the visitor. * * @param visitor the visitor * @param s the syntax to parse */ public void visit(BnfVisitor visitor, String s) { this.syntax = s; tokens = tokenize(); index = 0; Rule rule = parseRule(); rule.setLinks(ruleMap); rule.accept(visitor); } /** * Check whether the statement starts with a whitespace. * * @param s the statement * @return if the statement is not empty and starts with a whitespace */ public static boolean startWithSpace(String s) { return s.length() > 0 && Character.isWhitespace(s.charAt(0)); } /** * Convert convert ruleLink to rule_link. * * @param token the token * @return the rule map key */ public static String getRuleMapKey(String token) { StringBuilder buff = new StringBuilder(); for (char ch : token.toCharArray()) { if (Character.isUpperCase(ch)) { buff.append('_').append(Character.toLowerCase(ch)); } else { buff.append(ch); } } return buff.toString(); } /** * Get the rule head for the given title. * * @param title the title * @return the rule head, or null */ public RuleHead getRuleHead(String title) { return ruleMap.get(title); } private Rule parseRule() { read(); return parseOr(); } private Rule parseOr() { Rule r = parseList(); if (firstChar == '|') { read(); r = new RuleList(r, parseOr(), true); } lastRepeat = r; return r; } private Rule parseList() { Rule r = parseToken(); if (firstChar != '|' && firstChar != ']' && firstChar != '}' && firstChar != 0) { r = new RuleList(r, parseList(), false); } lastRepeat = r; return r; } private Rule parseToken() { Rule r; if ((firstChar >= 'A' && firstChar <= 'Z') || (firstChar >= 'a' && firstChar <= 'z')) { // r = new RuleElement(currentToken+ " syntax:" + syntax); r = new RuleElement(currentToken, currentTopic); } else if (firstChar == '[') { read(); Rule r2 = parseOr(); r = new RuleOptional(r2); if (firstChar != ']') { throw new AssertionError("expected ], got " + currentToken + " syntax:" + syntax); } } else if (firstChar == '{') { read(); r = parseOr(); if (firstChar != '}') { throw new AssertionError("expected }, got " + currentToken + " syntax:" + syntax); } } else if ("@commaDots@".equals(currentToken)) { r = new RuleList(new RuleElement(",", currentTopic), lastRepeat, false); r = new RuleRepeat(r, true); } else if ("@dots@".equals(currentToken)) { r = new RuleRepeat(lastRepeat, false); } else { r = new RuleElement(currentToken, currentTopic); } lastRepeat = r; read(); return r; } private void read() { if (index < tokens.length) { currentToken = tokens[index++]; firstChar = currentToken.charAt(0); } else { currentToken = ""; firstChar = 0; } } private String[] tokenize() { ArrayList<String> list = New.arrayList(); syntax = StringUtils.replaceAll(syntax, "yyyy-MM-dd", "@ymd@"); syntax = StringUtils.replaceAll(syntax, "hh:mm:ss", "@hms@"); syntax = StringUtils.replaceAll(syntax, "nnnnnnnnn", "@nanos@"); syntax = StringUtils.replaceAll(syntax, "function", "@func@"); syntax = StringUtils.replaceAll(syntax, "0x", "@hexStart@"); syntax = StringUtils.replaceAll(syntax, ",...", "@commaDots@"); syntax = StringUtils.replaceAll(syntax, "...", "@dots@"); syntax = StringUtils.replaceAll(syntax, "||", "@concat@"); syntax = StringUtils.replaceAll(syntax, "a-z|_", "@az_@"); syntax = StringUtils.replaceAll(syntax, "A-Z|_", "@az_@"); syntax = StringUtils.replaceAll(syntax, "A-F", "@af@"); syntax = StringUtils.replaceAll(syntax, "0-9", "@digit@"); syntax = StringUtils.replaceAll(syntax, "'['", "@openBracket@"); syntax = StringUtils.replaceAll(syntax, "']'", "@closeBracket@"); StringTokenizer tokenizer = getTokenizer(syntax); while (tokenizer.hasMoreTokens()) { String s = tokenizer.nextToken(); // avoid duplicate strings s = StringUtils.cache(s); if (s.length() == 1) { if (" \r\n".indexOf(s.charAt(0)) >= 0) { continue; } } list.add(s); } return list.toArray(new String[0]); } /** * Get the list of tokens that can follow. * This is the main autocomplete method. * The returned map for the query 'S' may look like this: * <pre> * key: 1#SELECT, value: ELECT * key: 1#SET, value: ET * </pre> * * @param query the start of the statement * @return the map of possible token types / tokens */ public HashMap<String, String> getNextTokenList(String query) { Sentence sentence = new Sentence(); sentence.setQuery(query); try { for (RuleHead head : statements) { if (!head.getSection().startsWith("Commands")) { continue; } sentence.start(); if (head.getRule().autoComplete(sentence)) { break; } } } catch (IllegalStateException e) { // ignore } return sentence.getNext(); } /** * Cross-link all statements with each other. * This method is called after updating the topics. */ public void linkStatements() { for (RuleHead r : ruleMap.values()) { r.getRule().setLinks(ruleMap); } } /** * Update a topic with a context specific rule. * This is used for autocomplete support. * * @param topic the topic * @param rule the database context rule */ public void updateTopic(String topic, DbContextRule rule) { topic = StringUtils.toLowerEnglish(topic); RuleHead head = ruleMap.get(topic); if (head == null) { head = new RuleHead("db", topic, rule); ruleMap.put(topic, head); statements.add(head); } else { head.setRule(rule); } } /** * Get the list of possible statements. * * @return the list of statements */ public ArrayList<RuleHead> getStatements() { return statements; } /** * Get the tokenizer for the given syntax. * * @param s the syntax * @return the tokenizer */ public static StringTokenizer getTokenizer(String s) { return new StringTokenizer(s, " [](){}|.,\r\n<>:-+*/=\"!'$", true); } }