index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/RhinoManagerCallback.java
|
/*
Copyright 2018-2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public interface RhinoManagerCallback {
void invoke(RhinoInference inference);
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/RhinoManagerErrorCallback.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public interface RhinoManagerErrorCallback {
void invoke(RhinoException error);
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/RhinoNative.java
|
/*
Copyright 2022-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
class RhinoNative {
static native int getFrameLength();
static native int getSampleRate();
static native String getVersion();
static native void setSdk(String sdk);
static native long init(
String accessKey,
String modelPath,
String contextPath,
float sensitivity,
float endpointDurationSec,
boolean requireEndpoint) throws RhinoException;
static native void delete(long object);
static native boolean process(long object, short[] pcm) throws RhinoException;
static native void reset(long object) throws RhinoException;
static native RhinoInference getInference(long object) throws RhinoException;
static native String getContextInfo(long object) throws RhinoException;
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoActivationException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoActivationException extends RhinoException {
public RhinoActivationException(Throwable cause) {
super(cause);
}
public RhinoActivationException(String message) {
super(message);
}
public RhinoActivationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoActivationLimitException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoActivationLimitException extends RhinoException {
public RhinoActivationLimitException(Throwable cause) {
super(cause);
}
public RhinoActivationLimitException(String message) {
super(message);
}
public RhinoActivationLimitException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoActivationRefusedException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoActivationRefusedException extends RhinoException {
public RhinoActivationRefusedException(Throwable cause) {
super(cause);
}
public RhinoActivationRefusedException(String message) {
super(message);
}
public RhinoActivationRefusedException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoActivationThrottledException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoActivationThrottledException extends RhinoException {
public RhinoActivationThrottledException(Throwable cause) {
super(cause);
}
public RhinoActivationThrottledException(String message) {
super(message);
}
public RhinoActivationThrottledException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoException extends Exception {
private final String message;
private final String[] messageStack;
public RhinoException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public RhinoException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public RhinoException(String message, String[] messageStack) {
super(message);
this.message = message;
this.messageStack = messageStack;
}
public String[] getMessageStack() {
return this.messageStack;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(message);
if (messageStack != null) {
if (messageStack.length > 0) {
sb.append(":");
for (int i = 0; i < messageStack.length; i++) {
sb.append(String.format("\n [%d] %s", i, messageStack[i]));
}
}
}
return sb.toString();
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoIOException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoIOException extends RhinoException {
public RhinoIOException(Throwable cause) {
super(cause);
}
public RhinoIOException(String message) {
super(message);
}
public RhinoIOException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoInvalidArgumentException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoInvalidArgumentException extends RhinoException {
public RhinoInvalidArgumentException(Throwable cause) {
super(cause);
}
public RhinoInvalidArgumentException(String message) {
super(message);
}
public RhinoInvalidArgumentException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoInvalidStateException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoInvalidStateException extends RhinoException {
public RhinoInvalidStateException(Throwable cause) {
super(cause);
}
public RhinoInvalidStateException(String message) {
super(message);
}
public RhinoInvalidStateException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoKeyException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoKeyException extends RhinoException {
public RhinoKeyException(Throwable cause) {
super(cause);
}
public RhinoKeyException(String message) {
super(message);
}
public RhinoKeyException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoMemoryException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoMemoryException extends RhinoException {
public RhinoMemoryException(Throwable cause) {
super(cause);
}
public RhinoMemoryException(String message) {
super(message);
}
public RhinoMemoryException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoRuntimeException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoRuntimeException extends RhinoException {
public RhinoRuntimeException(Throwable cause) {
super(cause);
}
public RhinoRuntimeException(String message) {
super(message);
}
public RhinoRuntimeException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/exception/RhinoStopIterationException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
public class RhinoStopIterationException extends RhinoException {
public RhinoStopIterationException(Throwable cause) {
super(cause);
}
public RhinoStopIterationException(String message) {
super(message);
}
public RhinoStopIterationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice/rhino/Rhino.java
|
/*
Copyright 2018-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
import java.io.File;
/**
* Java binding for Rhino Speech-to-Intent engine. It directly infers the user's intent from
* spoken commands in real-time. Rhino processes incoming audio in consecutive frames and indicates
* if the inference is finalized. When finalized, the inferred intent can be retrieved as structured
* data in the form of an intent string and pairs of slots and values. The number of samples per
* frame can be attained by calling {@link #getFrameLength()} . The incoming audio needs to have a
* sample rate equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Rhino operates on
* single-channel audio.
*/
public class Rhino {
public static final String LIBRARY_PATH;
public static final String MODEL_PATH;
private static String sdk = "java";
static {
LIBRARY_PATH = Utils.getPackagedLibraryPath();
MODEL_PATH = Utils.getPackagedModelPath();
}
private long handle;
private boolean isFinalized;
public static void setSdk(String sdk) {
Rhino.sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
* @param libraryPath Absolute path to the native Rhino library.
* @param modelPath Absolute path to the file containing model parameters.
* @param contextPath Absolute path to file containing context parameters. A context represents
* the set of expressions (spoken commands), intents, and intent arguments
* (slots) within a domain of interest.
* @param sensitivity Inference sensitivity. It should be a number within [0, 1]. A higher
* sensitivity value results in fewer misses at the cost of (potentially)
* increasing the erroneous inference rate.
* @param endpointDurationSec Endpoint duration in seconds. An endpoint is a chunk of silence at the end of an
* utterance that marks the end of spoken command. It should be a positive
* number within [0.5, 5]. A lower endpoint duration reduces delay and improves
* responsiveness. A higher endpoint duration assures Rhino doesn't return inference
* preemptively in case the user pauses before finishing the request.
* @param requireEndpoint If set to `true`, Rhino requires an endpoint (a chunk of silence) after the
* spoken command. If set to `false`, Rhino tries to detect silence, but if it
* cannot, it still will provide inference regardless. Set to `false` only if
* operating in an environment with overlapping speech (e.g. people talking in
* the background).
* @throws RhinoException If there is an error while initializing Rhino.
*/
public Rhino(
String accessKey,
String libraryPath,
String modelPath,
String contextPath,
float sensitivity,
float endpointDurationSec,
boolean requireEndpoint) throws RhinoException {
try {
System.load(libraryPath);
} catch (Exception exception) {
throw new RhinoException(exception);
}
RhinoNative.setSdk(Rhino.sdk);
handle = RhinoNative.init(
accessKey,
modelPath,
contextPath,
sensitivity,
endpointDurationSec,
requireEndpoint);
}
/**
* Releases resources acquired by Rhino.
*/
public void delete() {
if (handle != 0) {
RhinoNative.delete(handle);
handle = 0;
}
}
/**
* Processes a frame of audio and emits a flag indicating if the inference is finalized. When
* finalized, {@link #getInference()} should be called to retrieve the intent and slots, if the
* spoken command is considered valid.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by
* calling {@link #getFrameLength()}. The incoming audio needs to have a sample rate
* equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Furthermore,
* Rhino operates on single channel audio.
* @return Flag indicating whether the engine has finalized intent extraction.
* @throws RhinoException if there is an error while processing the audio frame.
*/
public boolean process(short[] pcm) throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino process after delete.");
}
if (pcm == null) {
throw new RhinoInvalidArgumentException("Passed null frame to Rhino process.");
}
if (pcm.length != getFrameLength()) {
throw new RhinoInvalidArgumentException(
String.format("Rhino process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
isFinalized = RhinoNative.process(handle, pcm);
return isFinalized;
}
/**
* Resets the internal state of Rhino. It should be called before the engine can be used to infer intent from a new
* stream of audio.
*
* @throws RhinoException if reset fails.
*/
public void reset() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino reset after delete.");
}
RhinoNative.reset(handle);
}
/**
* Gets inference result from Rhino. If the spoken command was understood, it includes the
* specific intent name that was inferred, and (if applicable) slot keys and specific slot
* values. Should only be called after the process function returns true, otherwise Rhino has
* not yet reached an inference conclusion.
*
* @return The result of inference as a {@link RhinoInference} object.
* @throws RhinoException if inference retrieval fails.
*/
public RhinoInference getInference() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino getInference after delete.");
}
if (!isFinalized) {
throw new RhinoInvalidStateException("getInference called before Rhino had finalized. " +
"Call getInference only after process has returned true");
}
return RhinoNative.getInference(handle);
}
/**
* Getter for context information.
*
* @return Context information.
*/
public String getContextInformation() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino getContextInformation after delete.");
}
return RhinoNative.getContextInfo(handle);
}
/**
* Getter for number of audio samples per frame.
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return RhinoNative.getFrameLength();
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return RhinoNative.getSampleRate();
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return RhinoNative.getVersion();
}
/**
* Builder for creating an instance of Rhino with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String libraryPath = null;
private String modelPath = null;
private String contextPath = null;
private float sensitivity = 0.5f;
private float endpointDuration = 1.0f;
private boolean requireEndpoint = false;
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Builder setLibraryPath(String libraryPath) {
this.libraryPath = libraryPath;
return this;
}
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
public Builder setSensitivity(float sensitivity) {
this.sensitivity = sensitivity;
return this;
}
public Builder setEndpointDuration(float endpointDuration) {
this.endpointDuration = endpointDuration;
return this;
}
public Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
/**
* Validates properties and creates an instance of the Rhino Speech-to-Intent engine.
*
* @return An instance of Rhino wake word engine
* @throws RhinoException if there is an error while initializing Rhino.
*/
public Rhino build() throws RhinoException {
if (!Utils.isEnvironmentSupported()) {
throw new RhinoRuntimeException("Could not initialize Rhino. " +
"Execution environment not currently supported by Rhino Java.");
}
if (accessKey == null) {
throw new RhinoInvalidArgumentException("AccessKey is required for Rhino initialization.");
}
if (libraryPath == null) {
if (Utils.isResourcesAvailable()) {
libraryPath = LIBRARY_PATH;
} else {
throw new RhinoInvalidArgumentException("Default library unavailable. Please " +
"provide a native Rhino library path (-l <library_path>).");
}
if (!new File(libraryPath).exists()) {
throw new RhinoIOException(String.format("Couldn't find library file at " +
"'%s'", libraryPath));
}
}
if (modelPath == null) {
if (Utils.isResourcesAvailable()) {
modelPath = MODEL_PATH;
} else {
throw new RhinoInvalidArgumentException("Default model unavailable. Please provide a " +
"valid Rhino model path (-m <model_path>).");
}
if (!new File(modelPath).exists()) {
throw new RhinoIOException(String.format("Couldn't find model file at " +
"'%s'", modelPath));
}
}
if (contextPath == null) {
throw new RhinoInvalidArgumentException("No context file provided");
}
if (!new File(contextPath).exists()) {
throw new RhinoIOException(String.format("Couldn't find context file at " +
"'%s'", contextPath));
}
if (sensitivity < 0 || sensitivity > 1) {
throw new RhinoInvalidArgumentException("Sensitivity value should be within [0, 1].");
}
if (endpointDuration < 0.5 || endpointDuration > 5.0) {
throw new RhinoInvalidArgumentException("Endpoint duration value should be within [0.5, 5.0].");
}
return new Rhino(
accessKey,
libraryPath,
modelPath,
contextPath,
sensitivity,
endpointDuration,
requireEndpoint);
}
}
}
|
0
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice/rhino/RhinoInference.java
|
/*
Copyright 2018-2020 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
import java.util.Map;
/**
* Class that contains inference results returned from Rhino.
*/
public class RhinoInference {
private final boolean isUnderstood;
private final String intent;
private final Map<String, String> slots;
RhinoInference(boolean isUnderstood, String intent, Map<String, String> slots) {
this.isUnderstood = isUnderstood;
this.intent = intent;
this.slots = slots;
}
public boolean getIsUnderstood() {
return isUnderstood;
}
public String getIntent() {
return intent;
}
public Map<String, String> getSlots() {
return slots;
}
}
|
0
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice/rhino/RhinoNative.java
|
/*
Copyright 2022-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
class RhinoNative {
static native String getVersion();
static native int getFrameLength();
static native int getSampleRate();
static native void setSdk(String sdk);
static native long init(
String accessKey,
String modelPath,
String contextPath,
float sensitivity,
float endpointDurationSec,
boolean requireEndpoint) throws RhinoException;
static native void delete(long object);
static native boolean process(long object, short[] pcm) throws RhinoException;
static native void reset(long object) throws RhinoException;
static native RhinoInference getInference(long object) throws RhinoException;
static native String getContextInfo(long object) throws RhinoException;
}
|
0
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice
|
java-sources/ai/picovoice/rhino-java/3.0.4/ai/picovoice/rhino/Utils.java
|
/*
Copyright 2018-2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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.picovoice.rhino;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;
class Utils {
private static final Path RESOURCE_DIRECTORY;
private static final String ENVIRONMENT_NAME;
private static final String ARCHITECTURE;
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
static {
RESOURCE_DIRECTORY = getResourceDirectory();
ENVIRONMENT_NAME = getEnvironmentName();
ARCHITECTURE = getArchitecture();
}
public static boolean isResourcesAvailable() {
return RESOURCE_DIRECTORY != null;
}
public static boolean isEnvironmentSupported() {
return ENVIRONMENT_NAME != null;
}
private static Path getResourceDirectory() throws RuntimeException {
// location of resources, either a JAR file or a directory
final URL resourceURL = Rhino.class.getProtectionDomain().getCodeSource().getLocation();
Path resourcePath;
try {
resourcePath = Paths.get(resourceURL.toURI());
} catch (URISyntaxException e) {
resourcePath = Paths.get(resourceURL.getPath());
}
if (resourcePath.toString().endsWith(".jar")) {
try {
resourcePath = extractResources(resourcePath);
} catch (IOException e) {
throw new RuntimeException("Failed to extract resources from Rhino JAR.");
}
}
return resourcePath.resolve("rhino");
}
private static Path extractResources(Path jarPath) throws IOException {
// use jar name to create versioned extraction directory
String extractionDirName = jarPath.getFileName().toString().replace(".jar", "");
// extract jar resources to temp directory
String systemTempDir = System.getProperty("java.io.tmpdir");
Path resourceDirectoryPath = new File(systemTempDir, extractionDirName).toPath();
// try to create tmp dir for extraction
if (!Files.exists(resourceDirectoryPath)) {
try {
Files.createDirectory(resourceDirectoryPath);
} catch (IOException e) {
logger.severe("Failed to create extraction directory at " + jarPath.toString());
e.printStackTrace();
// default extraction directly to tmp
resourceDirectoryPath = new File(systemTempDir).toPath();
}
}
// read jar file entries
JarFile jf = new JarFile(jarPath.toFile());
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String jarEntryName = jarEntry.getName();
if (jarEntryName.startsWith("rhino")) {
// copy contents into resource directory
if (jarEntry.isDirectory()) {
Path dstPath = resourceDirectoryPath.resolve(jarEntryName);
if (!dstPath.toFile().exists()) {
Files.createDirectory(dstPath);
}
} else {
Path file = resourceDirectoryPath.resolve(jarEntryName);
try (InputStream is = jf.getInputStream(jarEntry)) {
Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
return resourceDirectoryPath;
}
public static String getEnvironmentName() throws RuntimeException {
String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (os.contains("mac") || os.contains("darwin")) {
return "mac";
} else if (os.contains("win")) {
return "windows";
} else if (os.contains("linux")) {
String arch = System.getProperty("os.arch");
if (arch.equals("arm") || arch.equals("aarch64")) {
String cpuPart = getCpuPart();
switch (cpuPart) {
case "0xd03":
case "0xd08":
case "0xd0b":
return "raspberry-pi";
default:
throw new RuntimeException(String.format("Execution environment not supported. " +
"Rhino Java does not support CPU Part (%s).", cpuPart));
}
}
return "linux";
} else {
throw new RuntimeException("Execution environment not supported. " +
"Rhino Java is supported on MacOS, Linux and Windows");
}
}
private static String getArchitecture() throws RuntimeException {
String arch = System.getProperty("os.arch");
boolean isArm = arch.equals("arm") || arch.equals("aarch64");
boolean isX86_64 = arch.equals("amd64") || arch.equals("x86_64");
if (ENVIRONMENT_NAME.equals("mac")) {
if (isArm) {
return "arm64";
} else if (isX86_64) {
return "x86_64";
}
} else if (ENVIRONMENT_NAME.equals("windows")) {
if (isX86_64) {
return "amd64";
} else if (isArm) {
return "arm64";
}
} else if (ENVIRONMENT_NAME.equals("linux")) {
if (isX86_64) {
return "x86_64";
}
} else if (isArm) { // RPI
String cpuPart = getCpuPart();
String archInfo = (arch.equals("aarch64")) ? "-aarch64" : "";
switch (cpuPart) {
case "0xd03":
return "cortex-a53" + archInfo;
case "0xd08":
return "cortex-a72" + archInfo;
case "0xd0b":
return "cortex-a76" + archInfo;
default:
throw new RuntimeException(
String.format("Environment (%s) with CPU Part (%s) is not supported by Porcupine.",
ENVIRONMENT_NAME,
cpuPart)
);
}
}
throw new RuntimeException(
String.format("Environment (%s) with architecture (%s) is not supported by Porcupine.",
ENVIRONMENT_NAME,
arch)
);
}
private static String getCpuPart() throws RuntimeException {
try {
return Files.lines(Paths.get("/proc/cpuinfo"))
.filter(line -> line.startsWith("CPU part"))
.map(line -> line.substring(line.lastIndexOf(" ") + 1))
.findFirst()
.orElse("");
} catch (IOException e) {
throw new RuntimeException("Rhino failed to get get CPU information.");
}
}
public static String getPackagedModelPath() {
return RESOURCE_DIRECTORY.resolve("lib/common/rhino_params.pv").toString();
}
public static String getPackagedLibraryPath() {
switch (ENVIRONMENT_NAME) {
case "windows":
return RESOURCE_DIRECTORY.resolve("lib/java/windows")
.resolve(ARCHITECTURE)
.resolve("pv_rhino_jni.dll").toString();
case "mac":
return RESOURCE_DIRECTORY.resolve("lib/java/mac")
.resolve(ARCHITECTURE)
.resolve("libpv_rhino_jni.dylib").toString();
case "raspberry-pi":
case "linux":
return RESOURCE_DIRECTORY.resolve("lib/java")
.resolve(ENVIRONMENT_NAME)
.resolve(ARCHITECTURE)
.resolve("libpv_rhino_jni.so").toString();
default:
return null;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/gora-shaded-mongodb/0.9/ai/platon
|
java-sources/ai/platon/pulsar/gora-shaded-mongodb/0.9/ai/platon/pulsar/Placeholder.java
|
package ai.platon.pulsar;
/**
* A placeholder class
* */
public class Placeholder {
}
|
0
|
java-sources/ai/platon/pulsar/gora-shaded-mongodb/0.9/ai/platon
|
java-sources/ai/platon/pulsar/gora-shaded-mongodb/0.9/ai/platon/pulsar/package-info.java
|
package ai.platon.pulsar;
/**
* Since gora-0.x requires mongo-java-driver while spring-boot-2.4.x does not support it,
* we make a shaded jar to hide mongo-java-driver.
* */
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/document/BlockLabels.java
|
package ai.platon.pulsar.boilerpipe.document;
/**
* Some pre-defined labels which can be used in conjunction with {@link TextBlock#addLabel(String)}
* and {@link TextBlock#hasLabel(String)}.
*/
public interface BlockLabels {
String CONTENT_TITLE = "pulsar.text/CONTENT_TITLE";
String ARTICLE_METADATA = "pulsar.text/ARTICLE_METADATA";
String INDICATES_END_OF_TEXT = "pulsar.text/INDICATES_END_OF_TEXT";
String MIGHT_BE_CONTENT = "pulsar.text/MIGHT_BE_CONTENT";
String VERY_LIKELY_CONTENT = "pulsar.text/VERY_LIKELY_CONTENT";
String STRICTLY_NOT_CONTENT = "pulsar.text/STRICTLY_NOT_CONTENT";
String TOO_MANY_DATE_STRING_CONTENT = "pulsar.text/TOO_MANY_DATE_STRING_CONTENT";
String HR = "pulsar.text/HR";
String LI = "pulsar.text/LI";
String HEADING = "pulsar.text/HEADING";
String H1 = "pulsar.text/H1";
String H2 = "pulsar.text/H2";
String H3 = "pulsar.text/H3";
String MARKUP_PREFIX = "<";
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/document/BoiTextDocument.java
|
/**
* Created by vincent on 16-11-9.
* Copyright @ 2013-2016 Platon AI. All rights reserved
*/
package ai.platon.pulsar.boilerpipe.document;
import ai.platon.pulsar.boilerpipe.utils.PageCategory;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class BoiTextDocument implements Cloneable {
/** Scent Stat */
public static class Stat {
public int _char = 0;
public int _a = 0;
public int _img = 0;
}
private final List<TextBlock> textBlocks;
private String baseUrl;
private String pageTitle;
private String contentTitle;
private Instant publishTime = Instant.EPOCH;
private Instant modifiedTime = Instant.EPOCH;
private int dateTimeCount = 0;
private Stat stat = new Stat();
private PageCategory pageCategory = PageCategory.UNKNOWN;
private final Map<String, String> fields = new LinkedHashMap<>();
public BoiTextDocument(String baseUrl, String pageTitle, List<TextBlock> textBlocks) {
this.baseUrl = baseUrl;
this.pageTitle = pageTitle;
this.textBlocks = textBlocks;
}
public List<TextBlock> getTextBlocks() { return textBlocks; }
public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
public String getBaseUrl() { return baseUrl; }
public String getPageTitle() { return pageTitle == null ? "" : pageTitle; }
public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; }
public String getContentTitle() { return contentTitle == null ? "" : contentTitle; }
public void setContentTitle(String contentTitle) { this.contentTitle = contentTitle; }
public Instant getPublishTime() { return publishTime; }
public void setPublishTime(Instant publishTime) { this.publishTime = publishTime; }
public Instant getModifiedTime() { return modifiedTime; }
public void setModifiedTime(Instant modifiedTime) { this.modifiedTime = modifiedTime; }
public int getDateTimeCount() { return dateTimeCount; }
public void setDateTimeCount(int dateTimeCount) { this.dateTimeCount = dateTimeCount; }
public void setStat(Stat stat) { this.stat = stat; }
public Stat getStat() { return this.stat; }
public PageCategory getPageCategory() {
return pageCategory;
}
public String getPageCategoryAsString() {
return pageCategory.toString();
}
public void setPageCategory(PageCategory pageCategory) {
this.pageCategory = pageCategory;
}
public Map<String, String> getFields() {
return fields;
}
public String getField(String name) {
return fields.get(name);
}
public String getFieldOrDefault(String name, String defaultValue) {
return fields.getOrDefault(name, defaultValue);
}
public void setField(String name, String value) {
fields.put(name, value);
}
public String getTextContent() {
return getTextContent(true, false);
}
public String getTextContent(boolean includeContent, boolean includeNonContent) {
StringBuilder sb = new StringBuilder();
for (TextBlock block : getTextBlocks()) {
if (block.isContent()) {
if (!includeContent) {
continue;
}
} else {
if (!includeNonContent) {
continue;
}
}
sb.append(block.getText());
sb.append('\n');
}
return sb.toString();
}
public String getHtmlContent() {
return getHtmlContent(true, false);
}
public String getHtmlContent(boolean includeContent, boolean includeNonContent) {
StringBuilder sb = new StringBuilder();
sb.append("<div>");
LOOP:
for (TextBlock block : getTextBlocks()) {
if (block.isContent()) {
if (!includeContent) {
continue LOOP;
}
} else {
if (!includeNonContent) {
continue LOOP;
}
}
if (block.getRichText().length() > 1) {
sb.append("<div>");
sb.append(block.getRichText());
sb.append("</div>\n");
}
}
sb.append("</div>");
return sb.toString();
}
public String debugString() {
StringBuilder sb = new StringBuilder();
for (TextBlock tb : getTextBlocks()) {
if (!tb.getLabels().isEmpty()) {
sb.append("[LABLE : " + tb.getLabels() + "]");
}
sb.append(tb.toString());
sb.append('\n');
}
return sb.toString();
}
@Override
public BoiTextDocument clone() {
final List<TextBlock> list = new ArrayList<>(textBlocks.size());
for (TextBlock tb : textBlocks) {
list.add(tb.clone());
}
return new BoiTextDocument(baseUrl, pageTitle, list);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/document/LabelAction.java
|
package ai.platon.pulsar.boilerpipe.document;
import java.util.Arrays;
/**
* Helps adding labels to {@link TextBlock}s.
*/
public class LabelAction {
protected final String[] labels;
public LabelAction(String... labels) {
this.labels = labels;
}
public void addTo(final TextBlock tb) {
addLabelsTo(tb);
}
protected final void addLabelsTo(final TextBlock tb) {
tb.addLabels(labels);
}
public String toString() {
return super.toString() + "{" + Arrays.asList(labels) + "}";
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/document/TextBlock.java
|
/**
* Created by vincent on 16-11-9.
* Copyright @ 2013-2016 Platon AI. All rights reserved
*/
package ai.platon.pulsar.boilerpipe.document;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Set;
public class TextBlock implements Cloneable {
public static final BitSet EMPTY_BITSET = new BitSet();
public static final TextBlock EMPTY_START = new TextBlock("", EMPTY_BITSET, 0, 0, 0, 0, -1);
public static final TextBlock EMPTY_END = new TextBlock("", EMPTY_BITSET, 0, 0, 0, 0, Integer.MAX_VALUE);
private boolean isContent = false;
private CharSequence text;
private CharSequence richText;
private Set<String> labels = new HashSet<>(2);
private int offsetBlocksStart;
private int offsetBlocksEnd;
private int numWords;
private int numWordsInAnchorText;
private int numWordsInWrappedLines;
private int numWrappedLines;
private float textDensity;
private float linkDensity;
private BitSet containedTextElements;
private int numFullTextWords = 0;
private int tagLevel;
/** Reserved */
private String cssSelector;
public TextBlock(final String text) {
this(text, null, 0, 0, 0, 0, 0);
}
public TextBlock(final String text, final BitSet containedTextElements, final int numWords,
final int numWordsInAnchorText, final int numWordsInWrappedLines, final int numWrappedLines,
final int offsetBlocks) {
this.text = text;
this.richText = text.length() > 1 ? "<p>" + text + "</p>\n" : "";
this.containedTextElements = containedTextElements;
this.numWords = numWords;
this.numWordsInAnchorText = numWordsInAnchorText;
this.numWordsInWrappedLines = numWordsInWrappedLines;
this.numWrappedLines = numWrappedLines;
this.offsetBlocksStart = offsetBlocks;
this.offsetBlocksEnd = offsetBlocks;
initDensities();
}
public boolean isContent() {
return isContent;
}
public boolean setIsContent(boolean isContent) {
if (isContent != this.isContent) {
this.isContent = isContent;
return true;
} else {
return false;
}
}
public String getText() {
return text.toString();
}
public String getRichText() {
return richText.toString();
}
public int getNumWords() {
return numWords;
}
public int getNumWordsInAnchorText() {
return numWordsInAnchorText;
}
public float getTextDensity() {
return textDensity;
}
public float getLinkDensity() {
return linkDensity;
}
/** We support the most simple css selector only currently */
public String getCssSelector() { return cssSelector; }
public void setCssSelector(String cssSelector) { this.cssSelector = cssSelector; }
public void mergeNext(final TextBlock other) {
if (!(text instanceof StringBuilder)) {
text = new StringBuilder(text);
}
if (!(richText instanceof StringBuilder)) {
richText = new StringBuilder(richText);
}
StringBuilder sb = (StringBuilder) text;
StringBuilder richSb = (StringBuilder) richText;
String copy = other.text.toString();
sb.append('\n');
sb.append(copy);
if (copy.length() > 1) {
richSb.append("<p>");
richSb.append(copy);
richSb.append("</p>\n");
}
numWords += other.numWords;
numWordsInAnchorText += other.numWordsInAnchorText;
numWordsInWrappedLines += other.numWordsInWrappedLines;
numWrappedLines += other.numWrappedLines;
offsetBlocksStart = Math.min(offsetBlocksStart, other.offsetBlocksStart);
offsetBlocksEnd = Math.max(offsetBlocksEnd, other.offsetBlocksEnd);
initDensities();
this.isContent |= other.isContent;
if (containedTextElements == null) {
containedTextElements = (BitSet) other.containedTextElements.clone();
} else {
containedTextElements.or(other.containedTextElements);
}
numFullTextWords += other.numFullTextWords;
if (other.labels != null) {
if (labels == null) {
labels = new HashSet<>(other.labels);
} else {
labels.addAll(other.labels);
}
}
tagLevel = Math.min(tagLevel, other.tagLevel);
}
private void initDensities() {
if (numWordsInWrappedLines == 0) {
numWordsInWrappedLines = numWords;
numWrappedLines = 1;
}
textDensity = numWordsInWrappedLines / (float) numWrappedLines;
linkDensity = numWords == 0 ? 0 : numWordsInAnchorText / (float) numWords;
}
public int getOffsetBlocksStart() {
return offsetBlocksStart;
}
public int getOffsetBlocksEnd() {
return offsetBlocksEnd;
}
public String toString() {
return "[" + offsetBlocksStart + "-" + offsetBlocksEnd + ";tl=" + tagLevel + "; nw=" + numWords
+ ";nwl=" + numWrappedLines + ";ld=" + linkDensity + "]\t"
+ "selector=" + getCssSelector() + ";\t"
+ (isContent ? "CONTENT" : "boilerplate") + "," + labels + "\n" + getText();
}
public void addLabel(final String label) {
labels.add(label);
}
public boolean hasLabel(final String label) {
return labels != null && labels.contains(label);
}
public boolean removeLabel(final String label) {
return labels != null && labels.remove(label);
}
public Set<String> getLabels() {
return labels;
}
public void addLabels(final Set<String> l) {
if (l == null) {
return;
}
if (this.labels == null) {
this.labels = new HashSet<>(l);
} else {
this.labels.addAll(l);
}
}
public void addLabels(final String... l) {
if (l == null) {
return;
}
if (this.labels == null) {
this.labels = new HashSet<>();
}
for (final String label : l) {
this.labels.add(label);
}
}
public BitSet getContainedTextElements() {
return containedTextElements;
}
@Override
protected TextBlock clone() {
final TextBlock clone;
try {
clone = (TextBlock) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
if (text != null && !(text instanceof String)) {
clone.text = new StringBuilder(text);
}
if (labels != null && !labels.isEmpty()) {
clone.labels = new HashSet<String>(labels);
}
if (containedTextElements != null) {
clone.containedTextElements = (BitSet) containedTextElements.clone();
}
return clone;
}
public int getTagLevel() {
return tagLevel;
}
public void setTagLevel(int tagLevel) {
this.tagLevel = tagLevel;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/ArticleExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.heuristics.*;
import ai.platon.pulsar.boilerpipe.filters.simple.BoilerplateBlockFilter;
import ai.platon.pulsar.boilerpipe.filters.statistics.NumWordsRulesClassifier;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* A full-text extractor which is tuned towards news articles. In this scenario it achieves higher
* accuracy than {@link DefaultExtractor}.
*/
public final class ArticleExtractor implements TextExtractor {
public static final ArticleExtractor INSTANCE = new ArticleExtractor();
/**
* Returns the singleton instance for {@link ArticleExtractor}.
*/
public static ArticleExtractor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
return
TerminatingBlocksFinder.INSTANCE.process(doc)
| new DocumentTitleMatchClassifier(doc.getPageTitle()).process(doc)
| NumWordsRulesClassifier.INSTANCE.process(doc)
| IgnoreBlocksAfterContentFilter.DEFAULT_INSTANCE.process(doc)
| TrailingHeadlineToBoilerplateFilter.INSTANCE.process(doc)
| BlockProximityFusion.MAX_DISTANCE_1.process(doc)
| BoilerplateBlockFilter.INSTANCE_KEEP_TITLE.process(doc)
| BlockProximityFusion.MAX_DISTANCE_1_CONTENT_ONLY_SAME_TAGLEVEL.process(doc)
| KeepLargestBlockFilter.INSTANCE_EXPAND_TO_SAME_TAGLEVEL_MIN_WORDS.process(doc)
| ExpandTitleToContentFilter.INSTANCE.process(doc)
| LargeBlockSameTagLevelToContentFilter.INSTANCE.process(doc)
| ListAtEndFilter.INSTANCE.process(doc);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/ArticleSentencesExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.simple.MinClauseWordsFilter;
import ai.platon.pulsar.boilerpipe.filters.simple.SplitParagraphBlocksFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* A full-text extractor which is tuned towards extracting sentences from news articles.
*/
public final class ArticleSentencesExtractor implements TextExtractor {
public static final ArticleSentencesExtractor INSTANCE = new ArticleSentencesExtractor();
/**
* Returns the singleton instance for {@link ArticleSentencesExtractor}.
*/
public static ArticleSentencesExtractor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
return
ArticleExtractor.INSTANCE.process(doc) | SplitParagraphBlocksFilter.INSTANCE.process(doc)
| MinClauseWordsFilter.INSTANCE.process(doc);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/CanolaExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* A full-text extractor trained on <a href="http://krdwrd.org/">krdwrd</a> <a href
* ="https://krdwrd.org/trac/attachment/wiki/Corpora/Canola/CANOLA.pdf">Canola </a>.
*/
public class CanolaExtractor implements TextExtractor {
public static final CanolaExtractor INSTANCE = new CanolaExtractor();
/**
* Returns the singleton instance for {@link CanolaExtractor}.
*/
public static CanolaExtractor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
return CLASSIFIER.process(doc);
}
/**
* The actual classifier, exposed.
*/
public static final TextBlockFilter CLASSIFIER = new TextBlockFilter() {
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
boolean hasChanges = false;
ListIterator<TextBlock> it = textBlocks.listIterator();
if (!it.hasNext()) {
return false;
}
TextBlock prevBlock = TextBlock.EMPTY_START;
TextBlock currentBlock = it.next();
TextBlock nextBlock = it.hasNext() ? it.next() : TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
if (nextBlock != TextBlock.EMPTY_START) {
while (it.hasNext()) {
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = it.next();
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
return hasChanges;
}
protected boolean classify(final TextBlock prev, final TextBlock curr, final TextBlock next) {
final boolean isContent =
(curr.getLinkDensity() > 0 && next.getNumWords() > 11)
|| (curr.getNumWords() > 19 || (next.getNumWords() > 6 && next.getLinkDensity() == 0
&& prev.getLinkDensity() == 0 && (curr.getNumWords() > 6
|| prev.getNumWords() > 7 || next.getNumWords() > 19)));
return curr.setIsContent(isContent);
}
};
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/ChineseNewsExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.heuristics.*;
import ai.platon.pulsar.boilerpipe.filters.simple.BoilerplateBlockFilter;
import ai.platon.pulsar.boilerpipe.filters.simple.LabeledFieldExtractorFilter;
import ai.platon.pulsar.boilerpipe.filters.simple.RegexFieldExtractorFilter;
import ai.platon.pulsar.boilerpipe.filters.statistics.NumWordsRulesClassifier;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import ai.platon.pulsar.common.DateTimes;
import com.google.common.collect.ListMultimap;
import java.time.ZoneId;
import java.util.Set;
import static ai.platon.pulsar.boilerpipe.utils.BoiConstants.*;
/**
* A full-text extractor which is tuned towards news articles. In this scenario it achieves higher
* accuracy than {@link DefaultExtractor}.
*/
public final class ChineseNewsExtractor implements TextExtractor {
public static final ChineseNewsExtractor INSTANCE = new ChineseNewsExtractor();
private ZoneId zoneId = ZoneId.systemDefault();
private ListMultimap<String, String> labeledFieldRules;
private ListMultimap<String, String> regexFieldRules;
private Set<String> terminatingBlocksContains;
private Set<String> terminatingBlocksStartsWith;
public ChineseNewsExtractor() {
this.labeledFieldRules = LABELED_FIELD_RULES;
this.regexFieldRules = REGEX_FIELD_RULES;
this.terminatingBlocksContains = TERMINATING_BLOCKS_CONTAINS;
this.terminatingBlocksStartsWith = TERMINATING_BLOCKS_STARTS_WITH;
}
public void setZoneId(ZoneId zoneId) {
this.zoneId = zoneId;
}
public ZoneId getZoneId() {
return zoneId;
}
public void setLabeledFieldRules(ListMultimap<String, String> labeledFieldRules) {
this.labeledFieldRules.putAll(labeledFieldRules);
}
public void setRegexFieldRules(ListMultimap<String, String> regexFieldRules) {
this.regexFieldRules.putAll(regexFieldRules);
}
public void setTerminatingBlocksContains(Set<String> terminatingBlocksContains) {
this.terminatingBlocksContains.addAll(terminatingBlocksContains);
}
public void setTerminatingBlocksStartsWith(Set<String> terminatingBlocksStartsWith) {
this.terminatingBlocksStartsWith.addAll(terminatingBlocksStartsWith);
}
/**
* Returns the singleton instance for {@link ChineseNewsExtractor}.
*/
public static ChineseNewsExtractor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
var changed =
new TerminatingBlocksFinder(terminatingBlocksContains, terminatingBlocksStartsWith).process(doc) ||
new DocumentTitleMatchClassifier(doc.getPageTitle()).process(doc) ||
NumWordsRulesClassifier.INSTANCE.process(doc) ||
IgnoreBlocksAfterContentFilter.DEFAULT_INSTANCE.process(doc) ||
IgnoreBlocksAfterContentFromEndFilter.INSTANCE.process(doc) ||
TrailingHeadlineToBoilerplateFilter.INSTANCE.process(doc) ||
BlockProximityFusion.MAX_DISTANCE_1.process(doc) ||
new ArticleMetadataFilter(zoneId).process(doc) ||
BoilerplateBlockFilter.INSTANCE_KEEP_TITLE.process(doc) ||
BlockProximityFusion.MAX_DISTANCE_1_CONTENT_ONLY_SAME_TAGLEVEL.process(doc) ||
KeepLargestBlockFilter.INSTANCE_EXPAND_TO_SAME_TAGLEVEL_MIN_WORDS.process(doc) ||
ExpandTitleToContentFilter.INSTANCE.process(doc) ||
LargeBlockSameTagLevelToContentFilter.INSTANCE.process(doc) ||
ListAtEndFilter.INSTANCE.process(doc) ||
ContentDateStringNumberFilter.INSTANCE.process(doc) ||
new RegexFieldExtractorFilter(regexFieldRules, MAX_META_STR_LENGTH).process(doc) ||
new LabeledFieldExtractorFilter(labeledFieldRules).process(doc);
if (changed) {
doc.setContentTitle(doc.getFieldOrDefault(DOC_FIELD_CONTENT_TITLE, ""));
doc.setField(DOC_FIELD_TEXT_CONTENT_LENGTH, String.valueOf(doc.getTextContent().length()));
doc.setField(DOC_FIELD_HTML_CONTENT_LENGTH, String.valueOf(doc.getHtmlContent().length()));
doc.setField(DOC_FIELD_PUBLISH_TIME, DateTimes.isoInstantFormat(doc.getPublishTime()));
doc.setField(DOC_FIELD_MODIFIED_TIME, DateTimes.isoInstantFormat(doc.getModifiedTime()));
doc.setField(DOC_FIELD_PAGE_CATEGORY, doc.getPageCategoryAsString());
doc.setField(DOC_FIELD_PAGE_TITLE, doc.getPageTitle());
doc.setField(DOC_FIELD_CONTENT_TITLE, doc.getContentTitle());
doc.setField(DOC_FIELD_HTML_CONTENT, doc.getHtmlContent());
doc.setField(DOC_FIELD_TEXT_CONTENT, doc.getTextContent());
}
return changed;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/DefaultExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.heuristics.BlockProximityFusion;
import ai.platon.pulsar.boilerpipe.filters.heuristics.SimpleBlockFusionProcessor;
import ai.platon.pulsar.boilerpipe.filters.statistics.DensityRulesClassifier;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* A quite generic full-text extractor.
*/
public class DefaultExtractor implements TextExtractor {
public static final DefaultExtractor INSTANCE = new DefaultExtractor();
/**
* Returns the singleton instance for {@link DefaultExtractor}.
*/
public static DefaultExtractor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
return
SimpleBlockFusionProcessor.INSTANCE.process(doc)
| BlockProximityFusion.MAX_DISTANCE_1.process(doc)
| DensityRulesClassifier.INSTANCE.process(doc);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/extractors/TextExtractor.java
|
package ai.platon.pulsar.boilerpipe.extractors;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.sax.SAXInput;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import org.xml.sax.InputSource;
import java.io.Reader;
/**
* Describes a complete filter pipeline.
*/
public interface TextExtractor extends TextBlockFilter {
/**
* Extracts text from the HTML code given as a String.
*
* @param html The HTML code as a String.
* @return The extracted text.
* @throws ProcessingException
*/
default String getText(String baseUrl, String html) throws ProcessingException {
return getText(new SAXInput().parse(baseUrl, html));
}
/**
* Extracts text from the HTML code available from the given {@link InputSource}.
*
* @param is The InputSource containing the HTML
* @return The extracted text.
* @throws ProcessingException
*/
default String getText(String baseUrl, InputSource is) throws ProcessingException {
return getText(new SAXInput().parse(baseUrl, is));
}
/**
* Extracts text from the HTML code available from the given {@link Reader}.
*
* @param baseUrl The baseUrl of the page
* @param reader The Reader containing the HTML
* @return The extracted text.
* @throws ProcessingException
*/
default String getText(String baseUrl, Reader reader) throws ProcessingException {
return getText(baseUrl, new InputSource(reader));
}
/**
* Extracts text from the given {@link BoiTextDocument} object.
*
* @param doc The {@link BoiTextDocument}.
* @return The extracted text.
* @throws ProcessingException
*/
default String getText(BoiTextDocument doc) throws ProcessingException {
process(doc);
return doc.getTextContent();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/TextBlockFilter.java
|
package ai.platon.pulsar.boilerpipe.filters;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* A generic {@link TextBlockFilter}. Takes a {@link BoiTextDocument} and processes it somehow.
*/
public interface TextBlockFilter {
/**
* Processes the given document <code>doc</code>.
*
* @param doc The {@link BoiTextDocument} that is to be processed.
* @return <code>true</code> if changes have been made to the {@link BoiTextDocument}.
* @throws ProcessingException
*/
boolean process(final BoiTextDocument doc) throws ProcessingException;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/AddPrecedingLabelsFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
/**
* Adds the labels of the preceding block to the current block, optionally adding a prefix.
*/
public final class AddPrecedingLabelsFilter implements TextBlockFilter {
public static final AddPrecedingLabelsFilter INSTANCE = new AddPrecedingLabelsFilter("");
public static final AddPrecedingLabelsFilter INSTANCE_PRE = new AddPrecedingLabelsFilter("^");
private final String labelPrefix;
/**
* Creates a new {@link AddPrecedingLabelsFilter} instance.
*
* @param labelPrefix The maximum distance in blocks.
*/
public AddPrecedingLabelsFilter(final String labelPrefix) {
this.labelPrefix = labelPrefix;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
boolean changes = false;
int remaining = textBlocks.size();
TextBlock blockBelow = null;
TextBlock block;
for (ListIterator<TextBlock> it = textBlocks.listIterator(textBlocks.size()); it.hasPrevious(); ) {
if (--remaining <= 0) {
break;
}
if (blockBelow == null) {
blockBelow = it.previous();
continue;
}
block = it.previous();
Set<String> labels = block.getLabels();
if (labels != null && !labels.isEmpty()) {
for (String l : labels) {
blockBelow.addLabel(labelPrefix + l);
}
changes = true;
}
blockBelow = block;
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/ArticleMetadataFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import ai.platon.pulsar.boilerpipe.utils.BoiConstants;
import ai.platon.pulsar.common.DateTimeDetector;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.regex.Pattern;
/**
* Tries to find TextBlocks that comprise of "article metadata".
*/
public class ArticleMetadataFilter implements TextBlockFilter {
public static final ArticleMetadataFilter INSTANCE = new ArticleMetadataFilter();
private DateTimeDetector dateTimeDetector = new DateTimeDetector();
public ArticleMetadataFilter() {
}
public ArticleMetadataFilter(ZoneId zoneId) {
dateTimeDetector.setZoneId(zoneId);
}
@Override
public boolean process(BoiTextDocument doc) throws ProcessingException {
Instant now = Instant.now();
Instant publishTime = null;
int sniffedDateTimeCount = 0;
boolean changed = false;
boolean foundLongText = false;
for (TextBlock tb : doc.getTextBlocks()) {
final String text = tb.getText();
if (text.length() > BoiConstants.MAX_META_STR_LENGTH) {
foundLongText = true;
}
// Sniff latest page modified time
Instant sniffedTime = sniffValidDateTime(text, now);
if (sniffedTime.isAfter(doc.getModifiedTime())) {
++sniffedDateTimeCount;
doc.setModifiedTime(sniffedTime);
}
// sniff publish time
// TODO : need more features
if (!foundLongText && text.length() > BoiConstants.MIN_DATE_TIME_STR_LENGTH && publishTime == null) {
if (sniffedTime.isAfter(doc.getPublishTime())) {
publishTime = sniffedTime;
doc.setPublishTime(publishTime);
tb.setIsContent(true);
tb.addLabel(BlockLabels.ARTICLE_METADATA);
changed = true;
}
}
if (tb.getNumWords() < 10) {
for (Pattern p : BoiConstants.PATTERNS_SHORT) {
if (p.matcher(text).find()) {
changed = true;
tb.setIsContent(true);
tb.addLabel(BlockLabels.ARTICLE_METADATA);
}
} // for
}
}
doc.setDateTimeCount(sniffedDateTimeCount);
return changed;
}
private Instant sniffValidDateTime(String text, Instant now) {
OffsetDateTime offsetDateTime = dateTimeDetector.detectDateTimeLeniently(text);
if (offsetDateTime != null) {
Instant dateTime = offsetDateTime.toInstant();
long days = Duration.between(dateTime, now).toDays();
if (days < 5 * 365) {
return dateTime;
}
}
return Instant.EPOCH;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/BlockProximityFusion.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.Iterator;
import java.util.List;
/**
* Fuses adjacent blocks if their distance (in blocks) does not exceed a certain limit. This
* probably makes sense only in cases where an upstream filter already has removed some blocks.
*/
public final class BlockProximityFusion implements TextBlockFilter {
private final int maxBlocksDistance;
public static final BlockProximityFusion MAX_DISTANCE_1 = new BlockProximityFusion(1, false,
false);
public static final BlockProximityFusion MAX_DISTANCE_1_SAME_TAGLEVEL = new BlockProximityFusion(
1, false, true);
public static final BlockProximityFusion MAX_DISTANCE_1_CONTENT_ONLY = new BlockProximityFusion(
1, true, false);
public static final BlockProximityFusion MAX_DISTANCE_1_CONTENT_ONLY_SAME_TAGLEVEL =
new BlockProximityFusion(1, true, true);
private final boolean contentOnly;
private final boolean sameTagLevelOnly;
/**
* Creates a new {@link BlockProximityFusion} instance.
*
* @param maxBlocksDistance The maximum distance in blocks.
* @param contentOnly
*/
public BlockProximityFusion(final int maxBlocksDistance, final boolean contentOnly,
final boolean sameTagLevelOnly) {
this.maxBlocksDistance = maxBlocksDistance;
this.contentOnly = contentOnly;
this.sameTagLevelOnly = sameTagLevelOnly;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
boolean changes = false;
TextBlock prevBlock;
int offset;
if (contentOnly) {
prevBlock = null;
offset = 0;
for (TextBlock tb : textBlocks) {
offset++;
if (tb.isContent()) {
prevBlock = tb;
break;
}
}
if (prevBlock == null) {
return false;
}
} else {
prevBlock = textBlocks.get(0);
offset = 1;
}
for (Iterator<TextBlock> it = textBlocks.listIterator(offset); it.hasNext(); ) {
TextBlock block = it.next();
if (!block.isContent()) {
prevBlock = block;
continue;
}
int diffBlocks = block.getOffsetBlocksStart() - prevBlock.getOffsetBlocksEnd() - 1;
if (diffBlocks <= maxBlocksDistance) {
boolean ok = true;
if (contentOnly) {
if (!prevBlock.isContent() || !block.isContent()) {
ok = false;
}
}
if (ok && sameTagLevelOnly && prevBlock.getTagLevel() != block.getTagLevel()) {
ok = false;
}
if (ok) {
prevBlock.mergeNext(block);
it.remove();
changes = true;
} else {
prevBlock = block;
}
} else {
prevBlock = block;
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/ContentDateStringNumberFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Classifies {@link TextBlock}s as content/not-content through rules that have been determined
* using the C4.8 machine learning algorithm, as described in the paper
* "Boilerplate Detection using Shallow Text Features" (WSDM 2010), particularly using number of
* words per block and link density per block.
*/
public class ContentDateStringNumberFilter implements TextBlockFilter {
public static final ContentDateStringNumberFilter INSTANCE = new ContentDateStringNumberFilter();
/**
* Returns the singleton instance for ContentDateStringNumberFilter.
*/
public static ContentDateStringNumberFilter getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean hasChanges = false;
if (doc.getDateTimeCount() >= 8 && !doc.getPageCategory().isDetail()) {
for (TextBlock tb : doc.getTextBlocks()) {
tb.addLabel(BlockLabels.TOO_MANY_DATE_STRING_CONTENT);
tb.setIsContent(false);
hasChanges = true;
}
}
return hasChanges;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/ContentFusion.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Merges two blocks using some heuristics.
*/
public final class ContentFusion implements TextBlockFilter {
public static final ContentFusion INSTANCE = new ContentFusion();
/**
* Creates a new {@link ContentFusion} instance.
*
*/
public ContentFusion() {
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
TextBlock prevBlock = textBlocks.get(0);
boolean changes = false;
do {
changes = false;
for (ListIterator<TextBlock> it = textBlocks.listIterator(1); it.hasNext(); ) {
TextBlock block = it.next();
if (prevBlock.isContent() && block.getLinkDensity() < 0.56
&& !block.hasLabel(BlockLabels.STRICTLY_NOT_CONTENT)) {
prevBlock.mergeNext(block);
it.remove();
changes = true;
} else {
prevBlock = block;
}
}
} while (changes);
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/DocumentTitleMatchClassifier.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ManualRules;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Marks {@link TextBlock}s which contain parts of the HTML <code><CONTENT_TITLE></code> tag, using
* some heuristics which are quite specific to the news domain.
*/
public final class DocumentTitleMatchClassifier implements TextBlockFilter {
public static final Pattern PAT_REMOVE_CHARACTERS = Pattern.compile("[\\??\\!!\\.。\\-\\::]+");
public static final int MinTitleSize = 6;
public static final int MaxTitleSize = 200;
// 标题中常见的分隔符号,这些分隔符号往往带有一些低价值信息
public static final Pattern[] PotentialTitlePatterns = {
Pattern.compile("[ ]*[\\|»|-][ ]*"),
Pattern.compile("[ ]*[\\|»|:][ ]*"),
Pattern.compile("[ ]*[\\|»|:\\(\\)][ ]*"),
Pattern.compile("[ ]*[\\|»|:\\(\\)\\-][ ]*"),
Pattern.compile("[ ]*[\\|»|,|:\\(\\)\\-][ ]*"),
Pattern.compile("[ ]*[\\|»|,|:\\(\\)\\-\u00a0][ ]*"),
// 最精细分隔
Pattern.compile("[ ]*[»,,::_()【】\\|\\-\\(\\)][ ]*"),
// 相比上一个,少了-。某些标题中会带有范围参数如:索尼 NEX-3NL 16-50mm 单变焦镜头
Pattern.compile("[ ]*[»,,::_()【】\\|\\(\\)][ ]*"),
// 少了:和:
Pattern.compile("[ ]*[»,,_()【】\\|\\(\\)][ ]*"),
// 少了_
Pattern.compile("[ ]*[»,,()【】\\|\\(\\)][ ]*"),
// 最少分隔
Pattern.compile("[ ]*[»【】][ ]*")
};
private final Set<String> potentialTitles;
public DocumentTitleMatchClassifier(String title) {
if (title == null) {
this.potentialTitles = null;
} else {
title = title.replace('\u00a0', ' ');
title = title.replace("'", "");
title = title.trim().toLowerCase();
if (title.isEmpty()) {
this.potentialTitles = null;
} else {
this.potentialTitles = new HashSet<>();
potentialTitles.add(title);
for (Pattern pattern : PotentialTitlePatterns) {
String p = getLongestPart(title, pattern);
if (validatePotentialTitle(p)) {
potentialTitles.add(p);
}
}
addPotentialTitles(potentialTitles, title, "[ ]+[\\|][ ]+", 4);
addPotentialTitles(potentialTitles, title, "[ ]+[\\-][ ]+", 4);
potentialTitles.add(title.replaceFirst(" - [^\\-]+$", ""));
potentialTitles.add(title.replaceFirst("^[^\\-]+ - ", ""));
}
}
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
String contentTitle = extractContentTitleByRule(doc);
if (contentTitle != null) {
return true;
}
return extractContentTitleByPageTitle(doc);
}
public String extractContentTitleByRule(BoiTextDocument doc) {
String selector = null;
for (Map.Entry<String, String> entry : ManualRules.TITLE_RULES.entrySet()) {
if (doc.getBaseUrl().matches(entry.getKey())) {
selector = entry.getValue();
break;
}
}
if (selector == null) {
return null;
}
String contentTitle = null;
for (final TextBlock tb : doc.getTextBlocks()) {
if (tb.getCssSelector().equalsIgnoreCase(selector)) {
contentTitle = tb.getText();
tb.setIsContent(true);
tb.addLabel(BlockLabels.CONTENT_TITLE);
break;
}
}
return contentTitle;
}
public boolean extractContentTitleByPageTitle(BoiTextDocument doc) {
if (potentialTitles == null) {
return false;
}
boolean changes = false;
for (final TextBlock tb : doc.getTextBlocks()) {
String text = tb.getText();
text = text.replace('\u00a0', ' ');
text = text.replace("'", "");
text = text.trim().toLowerCase();
if (potentialTitles.contains(text)) {
tb.addLabel(BlockLabels.CONTENT_TITLE);
changes = true;
break;
}
if (text.length() > MaxTitleSize) {
continue;
}
text = PAT_REMOVE_CHARACTERS.matcher(text).replaceAll("").trim();
if (potentialTitles.contains(text)) {
tb.addLabel(BlockLabels.CONTENT_TITLE);
changes = true;
break;
}
}
return changes;
}
public boolean validatePotentialTitle(String title) {
// 商品标题,至少10个字符,最多200个字符
return !(title == null || title.length() <= MinTitleSize || title.length() >= MaxTitleSize);
}
public Set<String> getPotentialTitles() {
return potentialTitles;
}
private void addPotentialTitles(final Set<String> potentialTitles, final String title,
final String pattern, final int minWords) {
String[] parts = title.split(pattern);
if (parts.length == 1) {
return;
}
for (int i = 0; i < parts.length; i++) {
String p = parts[i];
if (p.contains(".com")) {
continue;
}
final int numWords = p.split("[\b ]+").length;
if (numWords >= minWords) {
potentialTitles.add(p);
}
}
}
private String getLongestPart(final String title, final Pattern pattern) {
String[] parts = title.split(pattern.pattern());
if (parts.length == 1) {
return null;
}
int longestNumWords = 0;
String longestPart = "";
for (int i = 0; i < parts.length; i++) {
String p = parts[i];
if (p.contains(".com")) {
continue;
}
final int numWords = p.split("[\b ]+").length;
if (numWords > longestNumWords || p.length() > longestPart.length()) {
longestNumWords = numWords;
longestPart = p;
}
}
if (longestPart.length() == 0) {
return null;
} else {
return longestPart.trim();
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/ExpandTitleToContentFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Marks all {@link TextBlock}s "content" which are between the headline and the part that has
* already been marked content, if they are marked {@link BlockLabels#MIGHT_BE_CONTENT}.
*
* This filter is quite specific to the news domain.
*/
public final class ExpandTitleToContentFilter implements TextBlockFilter {
public static final ExpandTitleToContentFilter INSTANCE = new ExpandTitleToContentFilter();
/**
* Returns the singleton instance for ExpandTitleToContentFilter.
*/
public static ExpandTitleToContentFilter getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
int i = 0;
int title = -1;
int contentStart = -1;
for (TextBlock tb : doc.getTextBlocks()) {
if (contentStart == -1 && tb.hasLabel(BlockLabels.CONTENT_TITLE)) {
title = i;
contentStart = -1;
}
if (contentStart == -1 && tb.isContent()) {
contentStart = i;
}
i++;
}
if (contentStart <= title || title == -1) {
return false;
}
boolean changes = false;
for (TextBlock tb : doc.getTextBlocks().subList(title, contentStart)) {
if (tb.hasLabel(BlockLabels.MIGHT_BE_CONTENT)) {
changes = tb.setIsContent(true) | changes;
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/HeuristicFilterBase.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
/**
* Base class for some heuristics that are used by boilerpipe filters.
*/
public abstract class HeuristicFilterBase {
protected static int getNumFullTextWords(final TextBlock tb) {
return getNumFullTextWords(tb, 9);
}
protected static int getNumFullTextWords(final TextBlock tb, float minTextDensity) {
if (tb.getTextDensity() >= minTextDensity) {
return tb.getNumWords();
} else {
return 0;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/IgnoreBlocksAfterContentFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.Iterator;
/**
* Marks all blocks as "non-content" that occur after blocks that have been marked
* {@link BlockLabels#INDICATES_END_OF_TEXT}. These marks are ignored unless a minimum number of
* words in content blocks occur before this mark (default: 60). This can be used in conjunction
* with an upstream {@link TerminatingBlocksFinder}.
*
* @see TerminatingBlocksFinder
*/
public final class IgnoreBlocksAfterContentFilter extends HeuristicFilterBase implements TextBlockFilter {
public static final IgnoreBlocksAfterContentFilter DEFAULT_INSTANCE = new IgnoreBlocksAfterContentFilter(60);
public static final IgnoreBlocksAfterContentFilter INSTANCE_200 = new IgnoreBlocksAfterContentFilter(200);
private final int minNumWords;
/**
* Returns the singleton instance for DeleteBlocksAfterContentFilter.
*/
public static IgnoreBlocksAfterContentFilter getDefaultInstance() {
return DEFAULT_INSTANCE;
}
public IgnoreBlocksAfterContentFilter(final int minNumWords) {
this.minNumWords = minNumWords;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
int numWords = 0;
boolean foundEndOfText = false;
for (Iterator<TextBlock> it = doc.getTextBlocks().iterator(); it.hasNext(); ) {
TextBlock block = it.next();
final boolean endOfText = block.hasLabel(BlockLabels.INDICATES_END_OF_TEXT);
if (block.isContent()) {
numWords += getNumFullTextWords(block);
}
if (endOfText && numWords >= minNumWords) {
foundEndOfText = true;
}
if (foundEndOfText) {
changes = true;
block.setIsContent(false);
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/IgnoreBlocksAfterContentFromEndFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Marks all blocks as "non-content" that occur after blocks that have been marked
* {@link BlockLabels#INDICATES_END_OF_TEXT}, and after any content block. This filter can be used
* in conjunction with an upstream {@link TerminatingBlocksFinder}.
*
* @see TerminatingBlocksFinder
*/
public final class IgnoreBlocksAfterContentFromEndFilter extends HeuristicFilterBase implements
TextBlockFilter {
public static final IgnoreBlocksAfterContentFromEndFilter INSTANCE =
new IgnoreBlocksAfterContentFromEndFilter();
private IgnoreBlocksAfterContentFromEndFilter() {
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
int words = 0;
List<TextBlock> blocks = doc.getTextBlocks();
if (!blocks.isEmpty()) {
ListIterator<TextBlock> it = blocks.listIterator(blocks.size());
TextBlock tb;
while (it.hasPrevious()) {
tb = it.previous();
if (tb.hasLabel(BlockLabels.INDICATES_END_OF_TEXT)) {
tb.addLabel(BlockLabels.STRICTLY_NOT_CONTENT);
tb.removeLabel(BlockLabels.MIGHT_BE_CONTENT);
tb.setIsContent(false);
changes = true;
} else if (tb.isContent()) {
words += tb.getNumWords();
if (words > 200) {
break;
}
}
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/KeepLargestBlockFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Keeps the largest {@link TextBlock} only (by the number of words). In case of more than one block
* with the same number of words, the first block is chosen. All discarded blocks are marked
* "not content" and flagged as {@link BlockLabels#MIGHT_BE_CONTENT}.
*
* Note that, by default, only TextBlocks marked as "content" are taken into consideration.
*/
public final class KeepLargestBlockFilter implements TextBlockFilter {
public static final KeepLargestBlockFilter INSTANCE = new KeepLargestBlockFilter(false, 0);
public static final KeepLargestBlockFilter INSTANCE_EXPAND_TO_SAME_TAGLEVEL =
new KeepLargestBlockFilter(true, 0);
public static final KeepLargestBlockFilter INSTANCE_EXPAND_TO_SAME_TAGLEVEL_MIN_WORDS =
new KeepLargestBlockFilter(true, 150);
private final boolean expandToSameLevelText;
private final int minWords;
public KeepLargestBlockFilter(boolean expandToSameLevelText, final int minWords) {
this.expandToSameLevelText = expandToSameLevelText;
this.minWords = minWords;
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
int maxNumWords = -1;
TextBlock largestBlock = null;
int level = -1;
int i = 0;
int n = -1;
for (TextBlock tb : textBlocks) {
if (tb.isContent()) {
final int nw = tb.getNumWords();
if (nw > maxNumWords) {
largestBlock = tb;
maxNumWords = nw;
n = i;
if (expandToSameLevelText) {
level = tb.getTagLevel();
}
}
}
i++;
}
for (TextBlock tb : textBlocks) {
if (tb == largestBlock) {
tb.setIsContent(true);
tb.addLabel(BlockLabels.VERY_LIKELY_CONTENT);
} else {
tb.setIsContent(false);
tb.addLabel(BlockLabels.MIGHT_BE_CONTENT);
}
}
if (expandToSameLevelText && n != -1) {
for (ListIterator<TextBlock> it = textBlocks.listIterator(n); it.hasPrevious(); ) {
TextBlock tb = it.previous();
final int tl = tb.getTagLevel();
if (tl < level) {
break;
} else if (tl == level) {
if (tb.getNumWords() >= minWords) {
tb.setIsContent(true);
}
}
}
for (ListIterator<TextBlock> it = textBlocks.listIterator(n); it.hasNext(); ) {
TextBlock tb = it.next();
final int tl = tb.getTagLevel();
if (tl < level) {
break;
} else if (tl == level) {
if (tb.getNumWords() >= minWords) {
tb.setIsContent(true);
}
}
}
}
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/KeepLargestFulltextBlockFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
/**
* Keeps the largest {@link TextBlock} only (by the number of words). In case of more than one block
* with the same number of words, the first block is chosen. All discarded blocks are marked
* "not content" and flagged as {@link BlockLabels#MIGHT_BE_CONTENT}.
*
* As opposed to {@link KeepLargestBlockFilter}, the number of words are computed using
* {@link HeuristicFilterBase#getNumFullTextWords(TextBlock)}, which only counts words that occur in
* text elements with at least 9 words and are thus believed to be full text.
*
* NOTE: Without language-specific fine-tuning (i.e., running the default instance), this filter may
* lead to suboptimal results. You better use {@link KeepLargestBlockFilter} instead, which works at
* the level of number-of-words instead of text densities.
*/
public final class KeepLargestFulltextBlockFilter extends HeuristicFilterBase implements
TextBlockFilter {
public static final KeepLargestFulltextBlockFilter INSTANCE =
new KeepLargestFulltextBlockFilter();
public boolean process(final BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
int max = -1;
TextBlock largestBlock = null;
for (TextBlock tb : textBlocks) {
if (!tb.isContent()) {
continue;
}
int numWords = getNumFullTextWords(tb);
if (numWords > max) {
largestBlock = tb;
max = numWords;
}
}
if (largestBlock == null) {
return false;
}
for (TextBlock tb : textBlocks) {
if (tb == largestBlock) {
tb.setIsContent(true);
} else {
tb.setIsContent(false);
tb.addLabel(BlockLabels.MIGHT_BE_CONTENT);
}
}
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/LabelFusion.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Fuses adjacent blocks if their labels are equal.
*/
public final class LabelFusion implements TextBlockFilter {
public static final LabelFusion INSTANCE = new LabelFusion();
/**
* Creates a new {@link LabelFusion} instance.
*/
private LabelFusion() {
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
if (textBlocks.size() < 2) {
return false;
}
boolean changes = false;
TextBlock prevBlock = textBlocks.get(0);
int offset = 1;
for (Iterator<TextBlock> it = textBlocks.listIterator(offset); it.hasNext(); ) {
TextBlock block = it.next();
if (equalLabels(prevBlock.getLabels(), block.getLabels())) {
prevBlock.mergeNext(block);
it.remove();
changes = true;
} else {
prevBlock = block;
}
}
return changes;
}
private boolean equalLabels(Set<String> labels, Set<String> labels2) {
if (labels == null || labels2 == null) {
return false;
}
return markupLabelsOnly(labels).equals(markupLabelsOnly(labels2));
}
private Set<String> markupLabelsOnly(final Set<String> set1) {
Set<String> set = new HashSet<String>(set1);
for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
final String label = it.next();
if (!label.startsWith(BlockLabels.MARKUP_PREFIX)) {
it.remove();
}
}
return set;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/LargeBlockSameTagLevelToContentFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Marks all blocks as content that:
* <ol>
* <li>are on the same tag-level as very likely main content (usually the level of the largest
* block)</li>
* <li>have a significant number of words, currently: at least 100</li>
* </ol>
*/
public final class LargeBlockSameTagLevelToContentFilter implements TextBlockFilter {
public static final LargeBlockSameTagLevelToContentFilter INSTANCE =
new LargeBlockSameTagLevelToContentFilter();
private LargeBlockSameTagLevelToContentFilter() {
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
int tagLevel = -1;
for (TextBlock tb : doc.getTextBlocks()) {
if (tb.isContent() && tb.hasLabel(BlockLabels.VERY_LIKELY_CONTENT)) {
tagLevel = tb.getTagLevel();
break;
}
}
if (tagLevel == -1) {
return false;
}
for (TextBlock tb : doc.getTextBlocks()) {
if (!tb.isContent()) {
if (tb.getNumWords() >= 100 && tb.getTagLevel() == tagLevel) {
tb.setIsContent(true);
changes = true;
}
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/ListAtEndFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Marks nested list-item blocks after the end of the main content.
*/
public final class ListAtEndFilter implements TextBlockFilter {
public static final ListAtEndFilter INSTANCE = new ListAtEndFilter();
private ListAtEndFilter() {
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
int tagLevel = Integer.MAX_VALUE;
for (TextBlock tb : doc.getTextBlocks()) {
if (tb.isContent() && tb.hasLabel(BlockLabels.VERY_LIKELY_CONTENT)) {
tagLevel = tb.getTagLevel();
} else {
if (tb.getTagLevel() > tagLevel && tb.hasLabel(BlockLabels.MIGHT_BE_CONTENT)
&& tb.hasLabel(BlockLabels.LI) && tb.getLinkDensity() == 0) {
tb.setIsContent(true);
changes = true;
} else {
tagLevel = Integer.MAX_VALUE;
}
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/SimpleBlockFusionProcessor.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.Iterator;
import java.util.List;
/**
* Merges two subsequent blocks if their text densities are equal.
*/
public class SimpleBlockFusionProcessor implements TextBlockFilter {
public static final SimpleBlockFusionProcessor INSTANCE = new SimpleBlockFusionProcessor();
/**
* Returns the singleton instance for BlockFusionProcessor.
*/
public static SimpleBlockFusionProcessor getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
boolean changes = false;
if (textBlocks.size() < 2) {
return false;
}
TextBlock b1 = textBlocks.get(0);
for (Iterator<TextBlock> it = textBlocks.listIterator(1); it.hasNext(); ) {
TextBlock b2 = it.next();
final boolean similar = (b1.getTextDensity() == b2.getTextDensity());
if (similar) {
b1.mergeNext(b2);
it.remove();
changes = true;
} else {
b1 = b2;
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/TerminatingBlocksFinder.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
/**
* Finds blocks which are potentially indicating the end of an article text and marks them with
* {@link BlockLabels#INDICATES_END_OF_TEXT}. This can be used in conjunction with a downstream
* {@link IgnoreBlocksAfterContentFilter}.
*
* @see IgnoreBlocksAfterContentFilter
*/
public class TerminatingBlocksFinder implements TextBlockFilter {
public static final TerminatingBlocksFinder INSTANCE = new TerminatingBlocksFinder();
private final Set<String> contains = Sets.newTreeSet();
private final Set<String> startsWith = Sets.newTreeSet();
/**
* Returns the singleton instance for TerminatingBlocksFinder.
*/
public static TerminatingBlocksFinder getInstance() {
return INSTANCE;
}
public TerminatingBlocksFinder() {
}
public TerminatingBlocksFinder(Collection<String> contains, Collection<String> startsWith) {
this.contains.addAll(contains);
this.startsWith.addAll(startsWith);
}
// public static long timeSpent = 0;
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
// long t = System.currentTimeMillis();
for (TextBlock tb : doc.getTextBlocks()) {
final int numWords = tb.getNumWords();
if (numWords < 15) {
final String text = tb.getText().trim();
final int len = text.length();
if (len >= 8) {
final String textLC = text.toLowerCase();
boolean isTerminatingBlock = startsWithNumber(textLC, len, " comments", " users responded in");
if (!isTerminatingBlock) {
for (String str : contains) {
if (textLC.contains(str.toLowerCase())) {
isTerminatingBlock = true;
break;
}
} // for
}
if (!isTerminatingBlock) {
for (String str : startsWith) {
if (textLC.startsWith(str.toLowerCase())) {
isTerminatingBlock = true;
break;
}
} // for
}
if (isTerminatingBlock) {
tb.addLabel(BlockLabels.INDICATES_END_OF_TEXT);
changes = true;
}
} else if (tb.getLinkDensity() == 1.0) {
if (text.equals("Comment")) {
tb.addLabel(BlockLabels.INDICATES_END_OF_TEXT);
}
}
}
}
// timeSpent += System.currentTimeMillis() - t;
return changes;
}
/**
* Checks whether the given text t starts with a sequence of digits, followed by one of the given
* strings.
*
* @param t The text to examine
* @param len The length of the text to examine
* @param str Any strings that may follow the digits.
* @return true if at least one combination matches
*/
private static boolean startsWithNumber(final String t, final int len, final String... str) {
int j = 0;
while (j < len && isDigit(t.charAt(j))) {
j++;
}
if (j != 0) {
for (String s : str) {
if (t.startsWith(s, j)) {
return true;
}
}
}
return false;
}
private static boolean isDigit(final char c) {
return c >= '0' && c <= '9';
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/TrailingHeadlineToBoilerplateFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.heuristics;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Marks trailing headlines ({@link TextBlock}s that have the label {@link BlockLabels#HEADING})
* as boilerplate. Trailing means they are marked content and are below any other content block.
*/
public final class TrailingHeadlineToBoilerplateFilter implements TextBlockFilter {
public static final TrailingHeadlineToBoilerplateFilter INSTANCE =
new TrailingHeadlineToBoilerplateFilter();
/**
* Returns the singleton instance for ExpandTitleToContentFilter.
*/
public static TrailingHeadlineToBoilerplateFilter getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
List<TextBlock> list = doc.getTextBlocks();
for (ListIterator<TextBlock> it = list.listIterator(list.size()); it.hasPrevious(); ) {
TextBlock tb = it.previous();
if (tb.isContent()) {
if (tb.hasLabel(BlockLabels.HEADING)) {
tb.setIsContent(false);
changes = true;
} else {
break;
}
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/heuristics/package-info.java
|
/**
* These BoilerpipeFilters are pure heuristics.
*/
package ai.platon.pulsar.boilerpipe.filters.heuristics;
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/BoilerplateBlockFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.Iterator;
import java.util.List;
/**
* Removes {@link TextBlock}s which have explicitly been marked as "not content".
*/
public final class BoilerplateBlockFilter implements TextBlockFilter {
public static final BoilerplateBlockFilter INSTANCE = new BoilerplateBlockFilter(null);
public static final BoilerplateBlockFilter INSTANCE_KEEP_TITLE = new BoilerplateBlockFilter(BlockLabels.CONTENT_TITLE);
private final String labelToKeep;
/**
* Returns the singleton instance for BoilerplateBlockFilter.
*/
public static BoilerplateBlockFilter getInstance() {
return INSTANCE;
}
public BoilerplateBlockFilter(final String labelToKeep) {
this.labelToKeep = labelToKeep;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
boolean hasChanges = false;
for (Iterator<TextBlock> it = textBlocks.iterator(); it.hasNext(); ) {
TextBlock tb = it.next();
if (!tb.isContent() && (labelToKeep == null || !tb.hasLabel(BlockLabels.CONTENT_TITLE) || !tb.hasLabel(BlockLabels.CONTENT_TITLE))) {
it.remove();
hasChanges = true;
}
}
return hasChanges;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/InvertedFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
/**
* Reverts the "isContent" flag for all {@link TextBlock}s
*/
public final class InvertedFilter implements TextBlockFilter {
public static final InvertedFilter INSTANCE = new InvertedFilter();
private InvertedFilter() {
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> tbs = doc.getTextBlocks();
if (tbs.isEmpty()) {
return false;
}
for (TextBlock tb : tbs) {
tb.setIsContent(!tb.isContent());
}
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/LabeledFieldExtractorFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import com.google.common.collect.ListMultimap;
/**
* Marks all blocks that contain a given label as "content".
*/
public final class LabeledFieldExtractorFilter implements TextBlockFilter {
private final ListMultimap<String, String> labeledRules;
// private final SortedBidiMap<String, String> labeledRules = new DualTreeBidiMap<>();
public LabeledFieldExtractorFilter(ListMultimap<String, String> labeledRules) {
this.labeledRules = labeledRules;
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean[] changes = {false};
doc.getTextBlocks().stream().filter(TextBlock::isContent).forEach(tb -> labeledRules.entries().stream()
.filter(rule -> tb.hasLabel(rule.getValue()))
.forEach(rule -> {
doc.setField(rule.getKey(), tb.getText());
changes[0] = true;
})
);
return changes[0];
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/MinClauseWordsFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Keeps only blocks that have at least one segment fragment ("clause") with at least <em>k</em>
* words (default: 5).
*
* NOTE: You might consider using the {@link SplitParagraphBlocksFilter} upstream.
*
* @see SplitParagraphBlocksFilter
*/
public final class MinClauseWordsFilter implements TextBlockFilter {
public static final MinClauseWordsFilter INSTANCE = new MinClauseWordsFilter(5, false);
private int minWords;
private final boolean acceptClausesWithoutDelimiter;
public MinClauseWordsFilter(final int minWords) {
this(minWords, false);
}
public MinClauseWordsFilter(final int minWords, final boolean acceptClausesWithoutDelimiter) {
this.minWords = minWords;
this.acceptClausesWithoutDelimiter = acceptClausesWithoutDelimiter;
}
private final Pattern PAT_CLAUSE_DELIMITER = Pattern
.compile("[\\p{L}\\d][\\,\\.\\:\\;\\!\\?]+([ \\n\\r]+|$)");
private final Pattern PAT_WHITESPACE = Pattern.compile("[ \\n\\r]+");
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
for (TextBlock tb : doc.getTextBlocks()) {
if (!tb.isContent()) {
continue;
}
final String text = tb.getText();
Matcher m = PAT_CLAUSE_DELIMITER.matcher(text);
boolean found = m.find();
int start = 0;
int end;
boolean hasClause = false;
while (found) {
end = m.start() + 1;
hasClause = isClause(text.subSequence(start, end));
start = m.end();
if (hasClause) {
break;
}
found = m.find();
}
end = text.length();
// since clauses should *always end* with a delimiter, we normally
// don't consider text without one
if (acceptClausesWithoutDelimiter) {
hasClause |= isClause(text.subSequence(start, end));
}
if (!hasClause) {
tb.setIsContent(false);
changes = true;
// System.err.println("IS NOT CONTENT: " + text);
}
}
return changes;
}
private boolean isClause(final CharSequence text) {
Matcher m = PAT_WHITESPACE.matcher(text);
int n = 1;
while (m.find()) {
n++;
if (n >= minWords) {
return true;
}
}
return n >= minWords;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/MinWordsFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Keeps only those content blocks which contain at least <em>k</em> words.
*/
public final class MinWordsFilter implements TextBlockFilter {
private final int minWords;
public MinWordsFilter(final int minWords) {
this.minWords = minWords;
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
for (TextBlock tb : doc.getTextBlocks()) {
if (!tb.isContent()) {
continue;
}
if (tb.getNumWords() < minWords) {
tb.setIsContent(false);
changes = true;
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/PrintDebugFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.io.PrintWriter;
/**
* Prints debug information about the current state of the TextDocument. (= calls
* {@link BoiTextDocument#debugString()}.
*/
public final class PrintDebugFilter implements TextBlockFilter {
/**
* Returns the default instance for {@link PrintDebugFilter}, which dumps debug information to
* <code>System.out</code>
*/
public static final PrintDebugFilter INSTANCE = new PrintDebugFilter(new PrintWriter(System.out,
true));
private final PrintWriter out;
/**
* Returns the default instance for {@link PrintDebugFilter}, which dumps debug information to
* <code>System.out</code>
*/
public static PrintDebugFilter getInstance() {
return INSTANCE;
}
/**
* Creates a new instance of {@link PrintDebugFilter}.
*
* Only use this method if you are not going to dump the debug information to
* <code>System.out</code> -- for this case, use {@link #getInstance()} instead.
*
* @param out The target {@link PrintWriter}. Will not be closed
*/
public PrintDebugFilter(final PrintWriter out) {
this.out = out;
}
@Override
public boolean process(BoiTextDocument doc) throws ProcessingException {
out.println(doc.debugString());
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/RegexFieldExtractorFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import ai.platon.pulsar.boilerpipe.utils.ScentUtils;
import com.google.common.collect.ListMultimap;
import java.util.Map;
/**
* Marks all blocks that contain a given label as "content".
*
* TODO : Combine with ArticleMetadataFilter
*/
public final class RegexFieldExtractorFilter implements TextBlockFilter {
// TODO : configurable
private int keyGroup = 1;
private int valueGroup = 2;
private final int maxTextLength;
private final ListMultimap<String, String> regexFieldRules;
public RegexFieldExtractorFilter(final ListMultimap<String, String> regexFieldRules, int maxTextLength) {
this.regexFieldRules = regexFieldRules;
this.maxTextLength = maxTextLength;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
for (final TextBlock tb : doc.getTextBlocks()) {
if (!tb.isContent()) {
continue;
}
String text = tb.getText();
if (text.length() < maxTextLength) {
changes = tryExtractText(doc, text);
} else {
// try extract from the beginning
changes = tryExtractText(doc, text.substring(0, maxTextLength));
// try extract from the ending
changes |= tryExtractText(doc, text.substring(text.length() - maxTextLength, text.length()));
}
}
return changes;
}
private boolean tryExtractText(BoiTextDocument doc, String text) {
Map<String, String> results = ScentUtils.extract(text, regexFieldRules, keyGroup, valueGroup);
results.forEach(doc::setField);
return !results.isEmpty();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/SplitParagraphBlocksFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.simple;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Splits TextBlocks at paragraph boundaries.
*
* NOTE: This is not fully supported (i.e., it will break highlighting support via
* #getContainedTextElements()), but this one probably is necessary for some other filters.
*
* @see MinClauseWordsFilter
*/
public final class SplitParagraphBlocksFilter implements TextBlockFilter {
public static final SplitParagraphBlocksFilter INSTANCE = new SplitParagraphBlocksFilter();
/**
* Returns the singleton instance for TerminatingBlocksFinder.
*/
public static SplitParagraphBlocksFilter getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
final List<TextBlock> blocks = doc.getTextBlocks();
final List<TextBlock> blocksNew = new ArrayList<TextBlock>();
for (TextBlock tb : blocks) {
final String text = tb.getText();
final String[] paragraphs = text.split("[\n\r]+");
if (paragraphs.length < 2) {
blocksNew.add(tb);
continue;
}
final boolean isContent = tb.isContent();
final Set<String> labels = tb.getLabels();
for (String p : paragraphs) {
final TextBlock tbP = new TextBlock(p);
tbP.setIsContent(isContent);
tbP.addLabels(labels);
blocksNew.add(tbP);
changes = true;
}
}
if (changes) {
blocks.clear();
blocks.addAll(blocksNew);
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/simple/package-info.java
|
/**
* These BoilerpipeFilters are straight-forward and probably not really specific to English.
*/
package ai.platon.pulsar.boilerpipe.filters.simple;
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/statistics/DensityRulesClassifier.java
|
package ai.platon.pulsar.boilerpipe.filters.statistics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Classifies {@link TextBlock}s as content/not-content through rules that have been determined
* using the C4.8 machine learning algorithm, as described in the paper
* "Boilerplate Detection using Shallow Text Features", particularly using text densities and link
* densities.
*/
public class DensityRulesClassifier implements TextBlockFilter {
public static final DensityRulesClassifier INSTANCE = new DensityRulesClassifier();
/**
* Returns the singleton instance for RulebasedBoilerpipeClassifier.
*/
public static DensityRulesClassifier getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
boolean hasChanges = false;
ListIterator<TextBlock> it = textBlocks.listIterator();
if (!it.hasNext()) {
return false;
}
TextBlock prevBlock = TextBlock.EMPTY_START;
TextBlock currentBlock = it.next();
TextBlock nextBlock = it.hasNext() ? it.next() : TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
if (nextBlock != TextBlock.EMPTY_START) {
while (it.hasNext()) {
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = it.next();
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
return hasChanges;
}
protected boolean classify(final TextBlock prev, final TextBlock curr, final TextBlock next) {
final boolean isContent;
if (curr.getLinkDensity() <= 0.333333) {
if (prev.getLinkDensity() <= 0.555556) {
if (curr.getTextDensity() <= 9) {
if (next.getTextDensity() <= 10) {
isContent = prev.getTextDensity() > 4;
} else {
isContent = true;
}
} else {
isContent = next.getTextDensity() != 0;
}
} else {
isContent = next.getTextDensity() > 11;
}
} else {
isContent = false;
}
return curr.setIsContent(isContent);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/statistics/MinFulltextWordsFilter.java
|
package ai.platon.pulsar.boilerpipe.filters.statistics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.filters.heuristics.HeuristicFilterBase;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
/**
* Keeps only those content blocks which contain at least k full-text words (measured by
* {@link HeuristicFilterBase#getNumFullTextWords(TextBlock)}). k is 30 by default.
*/
public final class MinFulltextWordsFilter extends HeuristicFilterBase implements TextBlockFilter {
public static final MinFulltextWordsFilter DEFAULT_INSTANCE = new MinFulltextWordsFilter(30);
private final int minWords;
public static MinFulltextWordsFilter getDefaultInstance() {
return DEFAULT_INSTANCE;
}
public MinFulltextWordsFilter(final int minWords) {
this.minWords = minWords;
}
public boolean process(final BoiTextDocument doc) throws ProcessingException {
boolean changes = false;
for (TextBlock tb : doc.getTextBlocks()) {
if (!tb.isContent()) {
continue;
}
if (getNumFullTextWords(tb) < minWords) {
tb.setIsContent(false);
changes = true;
}
}
return changes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/filters/statistics/NumWordsRulesClassifier.java
|
package ai.platon.pulsar.boilerpipe.filters.statistics;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.filters.TextBlockFilter;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import java.util.List;
import java.util.ListIterator;
/**
* Classifies {@link TextBlock}s as content/not-content through rules that have been determined
* using the C4.8 machine learning algorithm, as described in the paper
* "Boilerplate Detection using Shallow Text Features" (WSDM 2010), particularly using number of
* words per block and link density per block.
*/
public class NumWordsRulesClassifier implements TextBlockFilter {
public static final NumWordsRulesClassifier INSTANCE = new NumWordsRulesClassifier();
/**
* Returns the singleton instance for RulebasedBoilerpipeClassifier.
*/
public static NumWordsRulesClassifier getInstance() {
return INSTANCE;
}
public boolean process(BoiTextDocument doc) throws ProcessingException {
List<TextBlock> textBlocks = doc.getTextBlocks();
boolean hasChanges = false;
ListIterator<TextBlock> it = textBlocks.listIterator();
if (!it.hasNext()) {
return false;
}
TextBlock prevBlock = TextBlock.EMPTY_START;
TextBlock currentBlock = it.next();
TextBlock nextBlock = it.hasNext() ? it.next() : TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
if (nextBlock != TextBlock.EMPTY_START) {
while (it.hasNext()) {
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = it.next();
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
prevBlock = currentBlock;
currentBlock = nextBlock;
nextBlock = TextBlock.EMPTY_START;
hasChanges = classify(prevBlock, currentBlock, nextBlock) | hasChanges;
}
return hasChanges;
}
protected boolean classify(final TextBlock prev, final TextBlock curr, final TextBlock next) {
final boolean isContent;
if (curr.getLinkDensity() <= 0.333333) {
if (prev.getLinkDensity() <= 0.555556) {
isContent = curr.getNumWords() > 16 || next.getNumWords() > 15 || prev.getNumWords() > 4;
} else {
isContent = curr.getNumWords() > 40 || next.getNumWords() > 17;
}
} else {
isContent = false;
}
return curr.setIsContent(isContent);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/CommonTagActions.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.LabelAction;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Defines an action that is to be performed whenever a particular tag occurs during HTML parsing.
*/
public abstract class CommonTagActions {
private CommonTagActions() {
}
public static final class Chained implements TagAction {
private final TagAction t1;
private final TagAction t2;
public Chained(final TagAction t1, final TagAction t2) {
this.t1 = t1;
this.t2 = t2;
}
public boolean start(HTMLContentHandler instance, String localName, String qName, Attributes atts) throws SAXException {
return t1.start(instance, localName, qName, atts) | t2.start(instance, localName, qName, atts);
}
public boolean end(HTMLContentHandler instance, String localName, String qName) throws SAXException {
return t1.end(instance, localName, qName) | t2.end(instance, localName, qName);
}
public boolean changesTagLevel() {
return t1.changesTagLevel() || t2.changesTagLevel();
}
}
/**
* Marks this tag as "ignorable", i.e. all its inner content is silently skipped.
*/
public static final TagAction TA_IGNORABLE_ELEMENT = new TagAction() {
public boolean start(final HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
instance.inIgnorableElement++;
return true;
}
public boolean end(final HTMLContentHandler instance, final String localName, final String qName) {
instance.inIgnorableElement--;
return true;
}
public boolean changesTagLevel() {
return true;
}
};
/**
* Marks this tag as "anchor" (this should usually only be set for the <code><A></code>
* tag). Anchor tags may not be nested.
*
* There is a bug in certain versions of NekoHTML which still allows nested tags. If boilerpipe
* encounters such nestings, a SAXException is thrown.
*/
public static final TagAction TA_ANCHOR_TEXT = new TagAction() {
public boolean start(HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) throws SAXException {
if (instance.inAnchor++ > 0) {
// as nested A elements are not allowed per specification, we
// are probably reaching this branch due to a bug in the XML
// parser
System.err
.println("Warning: SAX input contains nested A elements -- You have probably hit a bug in your HTML parser (e.g., NekoHTML bug #2909310). Please clean the HTML externally and feed it to boilerpipe again. Trying to recover somehow...");
end(instance, localName, qName);
}
if (instance.inIgnorableElement == 0) {
instance.addWhitespaceIfNecessary();
instance.tokenBuffer.append(HTMLContentHandler.ANCHOR_TEXT_START);
instance.tokenBuffer.append(' ');
instance.sbLastWasWhitespace = true;
}
return false;
}
public boolean end(HTMLContentHandler instance, final String localName, final String qName) {
if (--instance.inAnchor == 0) {
if (instance.inIgnorableElement == 0) {
instance.addWhitespaceIfNecessary();
instance.tokenBuffer.append(HTMLContentHandler.ANCHOR_TEXT_END);
instance.tokenBuffer.append(' ');
instance.sbLastWasWhitespace = true;
}
}
++instance._a;
return false;
}
public boolean changesTagLevel() {
return true;
}
};
/**
* Marks this tag the body element (this should usually only be set for the
* <code><BODY></code> tag).
*/
public static final TagAction TA_BODY = new TagAction() {
public boolean start(final HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
instance.flushBlock();
instance.inBody++;
return false;
}
public boolean end(final HTMLContentHandler instance, final String localName, final String qName) {
instance.flushBlock();
instance.inBody--;
return false;
}
public boolean changesTagLevel() {
return true;
}
};
/**
* Marks this tag a simple "inline" element, which generates whitespace, but no new block.
*/
public static final TagAction TA_INLINE_WHITESPACE = new TagAction() {
public boolean start(HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
instance.addWhitespaceIfNecessary();
return false;
}
public boolean end(HTMLContentHandler instance, final String localName, final String qName) {
instance.addWhitespaceIfNecessary();
return false;
}
public boolean changesTagLevel() {
return false;
}
};
/**
* Marks this tag a simple "inline" element, which neither generates whitespace, nor a new block.
*/
public static final TagAction TA_INLINE_NO_WHITESPACE = new TagAction() {
public boolean start(HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
return false;
}
public boolean end(HTMLContentHandler instance, final String localName, final String qName) {
return false;
}
public boolean changesTagLevel() {
return false;
}
};
private static final Pattern PAT_FONT_SIZE = Pattern.compile("([\\+\\-]?)([0-9])");
/**
* Explicitly marks this tag a simple "block-level" element, which always generates whitespace
*/
public static final TagAction TA_BLOCK_LEVEL = new TagAction() {
public boolean start(HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
return true;
}
public boolean end(HTMLContentHandler instance, final String localName, final String qName) {
return true;
}
public boolean changesTagLevel() {
return true;
}
};
/**
* Special TagAction for the <code><FONT></code> tag, which keeps track of the absolute and
* relative font size.
*/
public static final TagAction TA_FONT = new TagAction() {
public boolean start(final HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) {
String sizeAttr = atts.getValue("size");
if (sizeAttr != null) {
Matcher m = PAT_FONT_SIZE.matcher(sizeAttr);
if (m.matches()) {
String rel = m.group(1);
final int val = Integer.parseInt(m.group(2));
final int size;
if (rel.length() == 0) {
// absolute
size = val;
} else {
// relative
int prevSize;
if (instance.fontSizeStack.isEmpty()) {
prevSize = 3;
} else {
prevSize = 3;
for (Integer s : instance.fontSizeStack) {
if (s != null) {
prevSize = s;
break;
}
}
}
if (rel.charAt(0) == '+') {
size = prevSize + val;
} else {
size = prevSize - val;
}
}
instance.fontSizeStack.add(0, size);
} else {
instance.fontSizeStack.add(0, null);
}
} else {
instance.fontSizeStack.add(0, null);
}
return false;
}
public boolean end(final HTMLContentHandler instance, final String localName, final String qName) {
instance.fontSizeStack.removeFirst();
return false;
}
public boolean changesTagLevel() {
return false;
}
};
/**
* {@link CommonTagActions} for inline elements, which triggers some {@link LabelAction} on the
* generated {@link TextBlock}.
*/
public static final class InlineTagLabelAction implements TagAction {
private final LabelAction action;
public InlineTagLabelAction(final LabelAction action) {
this.action = action;
}
public boolean start(HTMLContentHandler instance, final String localName,
final String qName, final Attributes atts) {
instance.addWhitespaceIfNecessary();
instance.addLabelAction(action);
return false;
}
public boolean end(HTMLContentHandler instance, final String localName,
final String qName) {
instance.addWhitespaceIfNecessary();
return false;
}
public boolean changesTagLevel() {
return false;
}
}
/**
* {@link CommonTagActions} for block-level elements, which triggers some {@link LabelAction} on
* the generated {@link TextBlock}.
*/
public static final class BlockTagLabelAction implements TagAction {
private final LabelAction action;
public BlockTagLabelAction(final LabelAction action) {
this.action = action;
}
public boolean start(HTMLContentHandler instance, final String localName,
final String qName, final Attributes atts) {
instance.addLabelAction(action);
return true;
}
public boolean end(HTMLContentHandler instance, final String localName, final String qName) {
return true;
}
public boolean changesTagLevel() {
return true;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/DefaultTagActionMap.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.LabelAction;
/**
* Default {@link TagAction}s. Seem to work well.
*/
public class DefaultTagActionMap extends TagActionMap {
public static final TagActionMap INSTANCE = new DefaultTagActionMap();
protected DefaultTagActionMap() {
setTagAction("STYLE", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("SCRIPT", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("OPTION", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("OBJECT", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("EMBED", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("APPLET", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("LINK", CommonTagActions.TA_IGNORABLE_ELEMENT);
setTagAction("A", CommonTagActions.TA_ANCHOR_TEXT);
setTagAction("BODY", CommonTagActions.TA_BODY);
setTagAction("STRIKE", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("U", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("B", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("I", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("EM", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("STRONG", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("SPAN", CommonTagActions.TA_INLINE_NO_WHITESPACE);
// New in 1.1 (especially to improve extraction quality from Wikipedia etc.)
setTagAction("SUP", CommonTagActions.TA_INLINE_NO_WHITESPACE);
// New in 1.2
setTagAction("CODE", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("TT", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("SUB", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("VAR", CommonTagActions.TA_INLINE_NO_WHITESPACE);
setTagAction("ABBR", CommonTagActions.TA_INLINE_WHITESPACE);
setTagAction("ACRONYM", CommonTagActions.TA_INLINE_WHITESPACE);
setTagAction("FONT", CommonTagActions.TA_INLINE_NO_WHITESPACE); // could also use TA_FONT
// added in 1.1.1
setTagAction("NOSCRIPT", CommonTagActions.TA_IGNORABLE_ELEMENT);
// New in 1.3
setTagAction("LI", new CommonTagActions.BlockTagLabelAction(new LabelAction(BlockLabels.LI)));
setTagAction("H1", new CommonTagActions.BlockTagLabelAction(new LabelAction(BlockLabels.H1,
BlockLabels.HEADING)));
setTagAction("H2", new CommonTagActions.BlockTagLabelAction(new LabelAction(BlockLabels.H2,
BlockLabels.HEADING)));
setTagAction("H3", new CommonTagActions.BlockTagLabelAction(new LabelAction(BlockLabels.H3,
BlockLabels.HEADING)));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/HTMLContentHandler.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.LabelAction;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.utils.PageCategory;
import ai.platon.pulsar.boilerpipe.utils.UnicodeTokenizer;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import java.util.*;
import java.util.regex.Pattern;
/**
* A simple SAX {@link ContentHandler}, used by {@link SAXInput}. Can be used by different
* parser implementations, e.g. NekoHTML and TagSoup.
*/
public class HTMLContentHandler implements ContentHandler {
private final Map<String, TagAction> tagActions;
private String baseUrl = null;
private String pageTitle = null;
static final String ANCHOR_TEXT_START = "$\ue00a<";
static final String ANCHOR_TEXT_END = ">\ue00a$";
StringBuilder tokenBuffer = new StringBuilder();
StringBuilder textBuffer = new StringBuilder();
int inBody = 0;
int inAnchor = 0;
int inIgnorableElement = 0;
int tagLevel = 0;
int blockTagLevel = -1;
boolean sbLastWasWhitespace = false;
private int textElementIdx = 0;
private final List<TextBlock> textBlocks = new ArrayList<>();
private String lastStartTag = null;
@SuppressWarnings("unused")
private String lastEndTag = null;
@SuppressWarnings("unused")
private Event lastEvent = null;
private int offsetBlocks = 0;
private BitSet currentContainedTextElements = new BitSet();
private boolean flush = false;
boolean inAnchorText = false;
/** The number of characters, the naming conversion is pulsar compatible */
int _char = 0;
/** The number of links, the naming conversion is pulsar compatible */
int _a = 0;
LinkedList<LinkedList<LabelAction>> labelStacks = new LinkedList<>();
LinkedList<Integer> fontSizeStack = new LinkedList<>();
/**
* Constructs a {@link HTMLContentHandler} using the {@link DefaultTagActionMap}.
*/
public HTMLContentHandler(String baseUrl) {
this(baseUrl, DefaultTagActionMap.INSTANCE);
}
/**
* Constructs a {@link HTMLContentHandler} using the given {@link TagActionMap}.
*
* @param tagActions The {@link TagActionMap} to use, e.g. {@link DefaultTagActionMap}.
*/
public HTMLContentHandler(String baseUrl, TagActionMap tagActions) {
this.baseUrl = baseUrl;
this.tagActions = tagActions;
}
@Override
public void endDocument() throws SAXException {
flushBlock();
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if (!sbLastWasWhitespace) {
textBuffer.append(' ');
tokenBuffer.append(' ');
}
sbLastWasWhitespace = true;
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
labelStacks.add(null);
TagAction ta = tagActions.get(localName);
if (ta != null) {
if (ta.changesTagLevel()) {
tagLevel++;
}
flush = ta.start(this, localName, qName, atts) | flush;
} else {
tagLevel++;
flush = true;
}
lastEvent = Event.START_TAG;
lastStartTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
TagAction ta = tagActions.get(localName);
if (ta != null) {
flush = ta.end(this, localName, qName) | flush;
} else {
flush = true;
}
if (ta == null || ta.changesTagLevel()) {
tagLevel--;
}
if (flush) {
flushBlock();
}
lastEvent = Event.END_TAG;
lastEndTag = localName;
labelStacks.removeLast();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
textElementIdx++;
if (flush) {
flushBlock();
flush = false;
}
if (inIgnorableElement != 0) {
return;
}
char c;
boolean startWhitespace = false;
boolean endWhitespace = false;
if (length == 0) {
return;
}
final int end = start + length;
for (int i = start; i < end; i++) {
if (Character.isWhitespace(ch[i])) {
ch[i] = ' ';
}
}
while (start < end) {
c = ch[start];
if (c == ' ') {
startWhitespace = true;
start++;
length--;
} else {
break;
}
}
while (length > 0) {
c = ch[start + length - 1];
if (c == ' ') {
endWhitespace = true;
length--;
} else {
break;
}
}
if (length == 0) {
if (startWhitespace || endWhitespace) {
if (!sbLastWasWhitespace) {
textBuffer.append(' ');
tokenBuffer.append(' ');
}
sbLastWasWhitespace = true;
} else {
sbLastWasWhitespace = false;
}
lastEvent = Event.WHITESPACE;
return;
}
if (startWhitespace) {
if (!sbLastWasWhitespace) {
textBuffer.append(' ');
tokenBuffer.append(' ');
}
}
if (blockTagLevel == -1) {
blockTagLevel = tagLevel;
}
textBuffer.append(ch, start, length);
tokenBuffer.append(ch, start, length);
if (endWhitespace) {
textBuffer.append(' ');
tokenBuffer.append(' ');
}
sbLastWasWhitespace = endWhitespace;
lastEvent = Event.CHARACTERS;
_char += length;
currentContainedTextElements.set(textElementIdx);
}
List<TextBlock> getTextBlocks() {
return textBlocks;
}
public void flushBlock() {
if (inBody == 0) {
if ("TITLE".equalsIgnoreCase(lastStartTag)) {
// TODO : Why we enter the tag for 3 times?
if (pageTitle == null || pageTitle.isEmpty()) {
pageTitle = tokenBuffer.toString().trim();
}
}
textBuffer.setLength(0);
tokenBuffer.setLength(0);
return;
}
final int length = tokenBuffer.length();
switch (length) {
case 0:
return;
case 1:
if (sbLastWasWhitespace) {
textBuffer.setLength(0);
tokenBuffer.setLength(0);
return;
}
}
final String[] tokens = UnicodeTokenizer.tokenize(tokenBuffer);
int numWords = 0;
int numLinkedWords = 0;
int numWrappedLines = 0;
int currentLineLength = -1; // don't count the first space
final int maxLineLength = 80;
int numTokens = 0;
int numWordsCurrentLine = 0;
for (String token : tokens) {
if (ANCHOR_TEXT_START.equals(token)) {
inAnchorText = true;
} else if (ANCHOR_TEXT_END.equals(token)) {
inAnchorText = false;
} else if (isWord(token)) {
numTokens++;
numWords++;
numWordsCurrentLine++;
if (inAnchorText) {
numLinkedWords++;
}
final int tokenLength = token.length();
currentLineLength += tokenLength + 1;
if (currentLineLength > maxLineLength) {
numWrappedLines++;
currentLineLength = tokenLength;
numWordsCurrentLine = 1;
}
} else {
numTokens++;
}
}
if (numTokens == 0) {
return;
}
int numWordsInWrappedLines;
if (numWrappedLines == 0) {
numWordsInWrappedLines = numWords;
numWrappedLines = 1;
} else {
numWordsInWrappedLines = numWords - numWordsCurrentLine;
}
TextBlock tb =
new TextBlock(textBuffer.toString().trim(), currentContainedTextElements, numWords,
numLinkedWords, numWordsInWrappedLines, numWrappedLines, offsetBlocks);
tb.setCssSelector(lastStartTag);
currentContainedTextElements = new BitSet();
offsetBlocks++;
textBuffer.setLength(0);
tokenBuffer.setLength(0);
tb.setTagLevel(blockTagLevel);
addTextBlock(tb);
blockTagLevel = -1;
}
protected void addTextBlock(final TextBlock tb) {
for (Integer l : fontSizeStack) {
if (l != null) {
tb.addLabel("font-" + l);
break;
}
}
for (LinkedList<LabelAction> labelStack : labelStacks) {
if (labelStack != null) {
for (LabelAction labels : labelStack) {
if (labels != null) {
labels.addTo(tb);
}
}
}
}
textBlocks.add(tb);
}
private static final Pattern PAT_VALID_WORD_CHARACTER = Pattern.compile("[\\p{L}\\p{Nd}\\p{Nl}\\p{No}]");
private static boolean isWord(final String token) {
return PAT_VALID_WORD_CHARACTER.matcher(token).find();
}
private enum Event {
START_TAG, END_TAG, CHARACTERS, WHITESPACE
}
public String getPageTitle() { return this.pageTitle; }
public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; }
public String getBaseUrl() { return this.baseUrl; }
public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
/**
* Returns a {@link BoiTextDocument} containing the extracted {@link TextBlock} s. NOTE: Only call
* this after parsing.
*
* @return The {@link BoiTextDocument}
*/
public BoiTextDocument toTextDocument() {
// just to be sure
flushBlock();
BoiTextDocument doc = new BoiTextDocument(baseUrl, pageTitle, getTextBlocks());
doc.getStat()._char = _char;
doc.getStat()._a = _a;
doc.setPageCategory(PageCategory.sniff(baseUrl, _char, _a));
return doc;
}
public void addWhitespaceIfNecessary() {
if (!sbLastWasWhitespace) {
tokenBuffer.append(' ');
textBuffer.append(' ');
sbLastWasWhitespace = true;
}
}
public void addLabelAction(final LabelAction la) throws IllegalStateException {
LinkedList<LabelAction> labelStack = labelStacks.getLast();
if (labelStack == null) {
labelStack = new LinkedList<>();
labelStacks.removeLast();
labelStacks.add(labelStack);
}
labelStack.add(la);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/HTMLParser.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.cyberneko.html.HTMLConfiguration;
import org.xml.sax.ContentHandler;
/**
* A simple SAX Parser, used by {@link SAXInput}. The parser uses <a
* href="http://nekohtml.sourceforge.net/">CyberNeko</a> to getTextDocument HTML content.
*/
public class HTMLParser extends AbstractSAXParser {
private HTMLContentHandler contentHandler;
/**
* Constructs a {@link HTMLParser} using a default HTML content handler.
*/
public HTMLParser(String baseUrl) {
this(new HTMLContentHandler(baseUrl));
}
/**
* Constructs a {@link HTMLParser} using the given {@link HTMLContentHandler}.
*
* @param contentHandler
*/
private HTMLParser(HTMLContentHandler contentHandler) {
super(new HTMLConfiguration());
setContentHandler(contentHandler);
}
public void setContentHandler(HTMLContentHandler contentHandler) {
this.contentHandler = contentHandler;
super.setContentHandler(contentHandler);
}
public void setContentHandler(ContentHandler contentHandler) {
this.contentHandler = null;
super.setContentHandler(contentHandler);
}
/**
* Returns a {@link BoiTextDocument} containing the extracted {@link TextBlock} s. NOTE: Only call
* this after {@link #parse(org.xml.sax.InputSource)}.
*
* @return The {@link BoiTextDocument}
*/
public BoiTextDocument getTextDocument() {
return contentHandler.toTextDocument();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/MarkupTagAction.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import ai.platon.pulsar.boilerpipe.document.LabelAction;
import ai.platon.pulsar.boilerpipe.document.TextBlock;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.util.*;
import java.util.regex.Pattern;
/**
* Assigns labels for element CSS classes and ids to the corresponding {@link TextBlock}. CSS
* classes are prefixed by <code>{@link BlockLabels#MARKUP_PREFIX}.</code>, and IDs are prefixed
* by <code>{@link BlockLabels#MARKUP_PREFIX}#</code>
*/
public final class MarkupTagAction implements TagAction {
private final boolean isBlockLevel;
private LinkedList<List<String>> labelStack = new LinkedList<>();
public MarkupTagAction(final boolean isBlockLevel) {
this.isBlockLevel = isBlockLevel;
}
private static final Pattern PAT_NUM = Pattern.compile("[0-9]+");
@Override
public boolean start(HTMLContentHandler instance, String localName, String qName,
Attributes atts) throws SAXException {
List<String> labels = new ArrayList<>(5);
labels.add(BlockLabels.MARKUP_PREFIX + localName);
String classVal = atts.getValue("class");
if (classVal != null && classVal.length() > 0) {
classVal = PAT_NUM.matcher(classVal).replaceAll("#");
classVal = classVal.trim();
String[] vals = classVal.split("[ ]+");
labels.add(BlockLabels.MARKUP_PREFIX + "." + classVal.replace(' ', '.'));
if (vals.length > 1) {
for (String s : vals) {
labels.add(BlockLabels.MARKUP_PREFIX + "." + s);
}
}
}
String id = atts.getValue("id");
if (id != null && id.length() > 0) {
id = PAT_NUM.matcher(id).replaceAll("#");
labels.add(BlockLabels.MARKUP_PREFIX + "#" + id);
}
Set<String> ancestors = getAncestorLabels();
List<String> labelsWithAncestors = new ArrayList<>((ancestors.size() + 1) * labels.size());
for (String l : labels) {
for (String an : ancestors) {
labelsWithAncestors.add(an);
labelsWithAncestors.add(an + " " + l);
}
labelsWithAncestors.add(l);
}
instance.addLabelAction(new LabelAction(labelsWithAncestors.toArray(new String[labelsWithAncestors.size()])));
labelStack.add(labels);
return isBlockLevel;
}
@Override
public boolean end(HTMLContentHandler instance, String localName, String qName)
throws SAXException {
labelStack.removeLast();
return isBlockLevel;
}
public boolean changesTagLevel() {
return isBlockLevel;
}
private Set<String> getAncestorLabels() {
Set<String> set = new HashSet<>();
for (List<String> labels : labelStack) {
if (labels == null) {
continue;
}
set.addAll(labels);
}
return set;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/SAXInput.java
|
package ai.platon.pulsar.boilerpipe.sax;
import ai.platon.pulsar.boilerpipe.document.BoiTextDocument;
import ai.platon.pulsar.boilerpipe.utils.ProcessingException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
/**
* Parses an {@link InputSource} using SAX and returns a {@link BoiTextDocument}.
*/
public final class SAXInput {
/**
* Retrieves the {@link BoiTextDocument} using a default HTML parser.
*/
public BoiTextDocument parse(String baseUrl, InputSource is) throws ProcessingException {
HTMLParser parser = new HTMLParser(baseUrl);
try {
parser.parse(is);
} catch (IOException|SAXException e) {
throw new ProcessingException(e);
}
return parser.getTextDocument();
}
/**
* Extracts text from the HTML code given as a String.
*
* @param html The HTML code as a String.
* @return The extracted text.
* @throws ProcessingException
*/
public BoiTextDocument parse(String baseUrl, String html) throws ProcessingException {
return parse(baseUrl, new InputSource(new StringReader(html)));
}
// public BoiTextDocument parse(URL url) throws ProcessingException {
// try {
// return parse(url.toString(), HTMLDownloader.fetch(url));
// } catch (IOException e) {
// throw new ProcessingException(e);
// }
// }
//
// public BoiTextDocument parse(String url) throws ProcessingException {
// try {
// String html = HTMLDownloader.fetch(url);
// // System.out.println(html);
// return parse(url, html);
// } catch (IOException e) {
// throw new ProcessingException(e);
// }
// }
//
// public BoiTextDocument parse(String baseUrl, Reader reader) throws ProcessingException {
// return parse(baseUrl, new InputSource(reader));
// }
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/TagAction.java
|
package ai.platon.pulsar.boilerpipe.sax;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* Defines an action that is to be performed whenever a particular tag occurs during HTML parsing.
*/
public interface TagAction {
boolean start(final HTMLContentHandler instance, final String localName, final String qName, final Attributes atts) throws SAXException;
boolean end(final HTMLContentHandler instance, final String localName, final String qName) throws SAXException;
boolean changesTagLevel();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/TagActionMap.java
|
package ai.platon.pulsar.boilerpipe.sax;
import java.util.HashMap;
/**
* Base class for definition a set of {@link TagAction}s that are to be used for the HTML parsing
* process.
*
* @see DefaultTagActionMap
*/
public abstract class TagActionMap extends HashMap<String, TagAction> {
private static final long serialVersionUID = 1L;
/**
* Sets a particular {@link TagAction} for a given tag. Any existing TagAction for that tag will
* be removed and overwritten.
*
* @param tag The tag (will be stored internally 1. as it is, 2. lower-case, 3. upper-case)
* @param action The {@link TagAction}
*/
protected void setTagAction(final String tag, final TagAction action) {
put(tag.toUpperCase(), action);
put(tag.toLowerCase(), action);
put(tag, action);
}
/**
* Adds a particular {@link TagAction} for a given tag. If a TagAction already exists for that
* tag, a chained action, consisting of the previous and the new {@link TagAction} is created.
*
* @param tag The tag (will be stored internally 1. as it is, 2. lower-case, 3. upper-case)
* @param action The {@link TagAction}
*/
protected void addTagAction(final String tag, final TagAction action) {
TagAction previousAction = get(tag);
if (previousAction == null) {
setTagAction(tag, action);
} else {
setTagAction(tag, new CommonTagActions.Chained(previousAction, action));
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/sax/package-info.java
|
/**
* Classes related to parsing and producing HTML from/to Scent TextDocuments.
*/
package ai.platon.pulsar.boilerpipe.sax;
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/BoiConstants.java
|
package ai.platon.pulsar.boilerpipe.utils;
import ai.platon.pulsar.boilerpipe.document.BlockLabels;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by vincent on 16-10-27.
* Copyright @ 2013-2016 Platon AI. All rights reserved
*/
public class BoiConstants {
public static final int MIN_DATE_TIME_STR_LENGTH = 15;
public static final int MAX_META_STR_LENGTH = 200;
public static final String DOC_FIELD_PUBLISH_TIME = "auto_publish_time";
public static final String DOC_FIELD_MODIFIED_TIME = "auto_modified_time";
public static final String DOC_FIELD_ARTICLE_TILE = "auto_article_title";
public static final String DOC_FIELD_PAGE_TITLE = "auto_page_title";
public static final String DOC_FIELD_CONTENT_TITLE = "auto_article_title";
public static final String DOC_FIELD_PAGE_CATEGORY = "auto_page_category";
public static final String DOC_FIELD_LINKS_COUNT = "auto_links_count";
public static final String DOC_FIELD_HTML_CONTENT = "auto_html_content";
public static final String DOC_FIELD_TEXT_CONTENT = "auto_text_content";
public static final String DOC_FIELD_TEXT_CONTENT_LENGTH = "auto_text_content_length";
public static final String DOC_FIELD_HTML_CONTENT_LENGTH = "auto_html_content_length";
public static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows; U; Win 9x 4.90; SG; rv:1.9.2.4) Gecko/20101104 Netscape/9.1.0285";
public static final Pattern[] PATTERNS_SHORT =
new Pattern[]{
Pattern.compile("^[0-9 \\,\\./]*\\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|May|June|July|August|September|October|November|December)?\\b[0-9 \\,\\:apm\\./]*([CPSDMGET]{2,3})?$"),
Pattern.compile("^[Bb]y "),
};
public static final char[] CHINESE_FAMILY_NAME_CHARS = new char[]{
'赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '楮', '卫', '蒋', '沈', '韩', '杨',
'朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜',
'戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎',
'鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '俞', '任', '袁', '柳', '酆', '鲍', '史', '唐',
'费', '廉', '岑', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '邬', '安', '常',
'乐', '于', '时', '傅', '皮', '卞', '齐', '康', '伍', '余', '元', '卜', '顾', '孟', '平', '黄',
'和', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '禹', '狄', '米', '贝', '明', '臧',
'计', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁',
'杜', '阮', '蓝', '闽', '席', '季', '麻', '强', '贾', '路', '娄', '危', '江', '童', '颜', '郭',
'梅', '盛', '林', '刁', '锺', '徐', '丘', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍',
'虞', '万', '支', '柯', '昝', '管', '卢', '莫', '经', '房', '裘', '缪', '干', '解', '应', '宗',
'丁', '宣', '贲', '邓', '郁', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '钮', '龚',
'程', '嵇', '邢', '滑', '裴', '陆', '荣', '翁', '荀', '羊', '於', '惠', '甄', '麹', '家', '封',
'芮', '羿', '储', '靳', '汲', '邴', '糜', '松', '井', '段', '富', '巫', '乌', '焦', '巴', '弓',
'牧', '隗', '山', '谷', '车', '侯', '宓', '蓬', '全', '郗', '班', '仰', '秋', '仲', '伊', '宫',
'宁', '仇', '栾', '暴', '甘', '斜', '厉', '戎', '祖', '武', '符', '刘', '景', '詹', '束', '龙',
'叶', '幸', '司', '韶', '郜', '黎', '蓟', '薄', '印', '宿', '白', '怀', '蒲', '邰', '从', '鄂',
'索', '咸', '籍', '赖', '卓', '蔺', '屠', '蒙', '池', '乔', '阴', '郁', '胥', '能', '苍', '双',
'闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '郦', '雍',
'郤', '璩', '桑', '桂', '濮', '牛', '寿', '通', '边', '扈', '燕', '冀', '郏', '浦', '尚', '农',
'温', '别', '庄', '晏', '柴', '瞿', '阎', '充', '慕', '连', '茹', '习', '宦', '艾', '鱼', '容',
'向', '古', '易', '慎', '戈', '廖', '庾', '终', '暨', '居', '衡', '步', '都', '耿', '满', '弘',
'匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '殳', '沃', '利', '蔚', '越', '夔', '隆',
'师', '巩', '厍', '聂', '晁', '勾', '敖', '融', '冷', '訾', '辛', '阚', '那', '简', '饶', '空',
'曾', '毋', '沙', '乜', '养', '鞠', '须', '丰', '巢', '关', '蒯', '相', '查', '后', '荆', '红',
'游', '竺', '权', '逑', '盖', '益', '桓', '公', '仉', '督', '晋', '楚', '阎', '法', '汝', '鄢',
'涂', '钦', '岳', '帅', '缑', '亢', '况', '后', '有', '琴', '归', '海', '墨', '哈', '谯', '笪',
'年', '爱', '阳', '佟', '商', '牟', '佘', '佴', '伯', '赏'
};
public static final CharSequence[] CHINESE_S_FAMILY_NAMES = Stream.of(CHINESE_FAMILY_NAME_CHARS)
.map(String::valueOf).collect(Collectors.toList()).toArray(new CharSequence[0]);
public static final CharSequence[] CHINESE_D_FAMILY_NAMES = new String[]{
"万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "尉迟", "公羊",
"澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐",
"锺离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "丌官", "司寇", "子车", "微生",
"颛孙", "端木", "巫马", "公西", "漆雕", "乐正", "壤驷", "公良", "拓拔", "夹谷", "宰父", "谷梁",
"段干", "百里", "东郭", "南门", "呼延", "羊舌", "梁丘", "左丘", "东门", "西门", "南宫"
};
public static final ListMultimap<String, String> LABELED_FIELD_RULES = LinkedListMultimap.create();
public static final ListMultimap<String, String> REGEX_FIELD_RULES = LinkedListMultimap.create();
public static final Set<String> TERMINATING_BLOCKS_CONTAINS = Sets.newTreeSet();
public static final Set<String> TERMINATING_BLOCKS_STARTS_WITH = Sets.newTreeSet();
public static final Map<String, Integer> MAX_FIELD_LENGTH_MAP = new TreeMap<>();
public static final String[] REGEX_FIELD_BOUNDERS = {"作者", "责任编辑", "编辑", "来源"};
public static final String[] BAD_PHRASE_IN_NAME = new String[]{
"等", "介绍", "了解", "在", "采访", "发现", "独家", "获悉", "获知",
"回忆", "关注", "提醒", "各位", "管窥", "到了", "昨天", "今天", "最近", "打开"
};
public static final String[] BAD_DATE_TIME_STRING_CONTAINS = new String[]{
"GMT+8",
"UTC+8",
"Processed",
"访问",
"刷新",
"visit"
};
public static final String[] BAD_PHRASE_IN_TITLE = new String[]{
"主流媒体 山西门户",
};
static {
LABELED_FIELD_RULES.put(DOC_FIELD_CONTENT_TITLE, BlockLabels.CONTENT_TITLE);
// TODO : Regex explain : (作者|记者)\s{0,}:{0,1}\s{0,}([一-龥]{2,6})(作者|责任|编辑|来源){0,1}
REGEX_FIELD_RULES.put("author", "(作者|记者)\\s{0,5}:{0,1}\\s{0,}([一-龥]{2,4})(作者|责编|责任编辑|编辑|来源){0,1}");
REGEX_FIELD_RULES.put("director", "(编辑)\\s{0,5}:{0,1}\\s{0,}([一-龥]{2,4})(作者|责编|责任编辑|编辑|来源){0,1}");
REGEX_FIELD_RULES.put("reference", "(来源|来源于|来自|转载|转载自)\\s{0,5}:{0,1}\\s{0,}([一-龥]{2,7})(作者|责编|责任编辑|编辑|来源){0,1}");
REGEX_FIELD_RULES.put("keywords", "(关键词)\\s{0,5}:{0,1}\\s{0,}(.+)");
REGEX_FIELD_RULES.put("keywords", "(标签)\\s{0,5}:{0,1}\\s{0,}(.+)");
MAX_FIELD_LENGTH_MAP.put("author", 4);
MAX_FIELD_LENGTH_MAP.put("director", 4);
MAX_FIELD_LENGTH_MAP.put("reference", 100);
TERMINATING_BLOCKS_CONTAINS.addAll(Lists.newArrayList(
"All Rights Reserved",
"Copyright ©",
"what you think...",
"add your comment",
"add comment",
"reader views",
"have your say",
"reader comments",
"comments",
"© reuters",
"please rate this",
"post a comment",
"参与讨论",
"精彩评论",
"网友跟贴",
"登录发帖",
"版权所有",
"京ICP证",
"网友跟贴",
"版权所有",
"网络传播视听节目许可证号",
"增值电信业务经营许可证",
"相关阅读",
"免责声明",
"互联网违法和不良信息举报方式",
"转载请注明",
"技术支持热线",
"站长统计"
));
TERMINATING_BLOCKS_STARTS_WITH.addAll(Lists.newArrayList(
));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/ManualRules.java
|
package ai.platon.pulsar.boilerpipe.utils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by vincent on 16-10-27.
* Copyright @ 2013-2016 Platon AI. All rights reserved
*/
public class ManualRules {
public static final Map<String, String> TITLE_RULES = new HashMap<>();
static {
TITLE_RULES.put("http://www.sxrb.com/(.+)", "h2");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/PageCategory.java
|
package ai.platon.pulsar.boilerpipe.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Created by vincent on 17-2-13.
*
* TODO: distinguish with ai.platon.pulsar.persist.metadata.PageCategory
*/
public enum PageCategory {
INDEX, DETAIL, SEARCH, MEDIA, BBS, TIEBA, BLOG, UNKNOWN;
/**
* The follow patterns are simple rule to indicate a url's category, this is a very simple solution, and the result is
* not accurate
*/
public static Pattern[] INDEX_PAGE_URL_PATTERNS = {
Pattern.compile(".+tieba.baidu.com/.+search.+"),
Pattern.compile(".+(index|list|tags|chanel).+"),
};
public static Pattern SEARCH_PAGE_URL_PATTERN = Pattern.compile(".+(search|query|select).+");
public static Pattern[] DETAIL_PAGE_URL_PATTERNS = {
Pattern.compile(".+tieba.baidu.com/p/(\\d+)"),
Pattern.compile(".+(detail|item|article|book|good|product|thread|view|post|content|/20[012][0-9]/{0,1}[01][0-9]/|/20[012]-[0-9]{0,1}-[01][0-9]/|/\\d{2,}/\\d{5,}|\\d{7,}).+")
};
public static Pattern MEDIA_PAGE_URL_PATTERN = Pattern.compile(".+(pic|picture|photo|avatar|photoshow|video).+");
public static final String[] MEDIA_URL_SUFFIXES = {"js", "css", "jpg", "png", "jpeg", "gif"};
public boolean is(PageCategory pageCategory) {
return pageCategory == this;
}
public boolean isIndex() {
return this == INDEX;
}
public boolean isDetail() {
return this == DETAIL;
}
public boolean isSearch() {
return this == SEARCH;
}
public boolean isMedia() {
return this == MEDIA;
}
public boolean isBBS() {
return this == BBS;
}
public boolean isTieBa() {
return this == TIEBA;
}
public boolean isBlog() {
return this == BLOG;
}
public boolean isUnknown() {
return this == UNKNOWN;
}
/**
* TODO : need carefully test
*/
public static PageCategory sniff(String url, int _char, int _a) {
if (url.isEmpty()) {
return UNKNOWN;
}
PageCategory pageCategory = sniff(url);
if (pageCategory.isDetail()) {
return pageCategory;
}
if (_char < 100) {
if (_a > 30) {
pageCategory = INDEX;
}
} else {
return sniffByTextDensity(_char, _a);
}
return pageCategory;
}
/* TODO : use machine learning to calculate the parameters */
private static PageCategory sniffByTextDensity(double _char, double _a) {
PageCategory pageCategory = UNKNOWN;
if (_a < 1) {
_a = 1;
}
if (_a > 60 && _char / _a < 20) {
// 索引页:链接数不少于60个,文本密度小于20
pageCategory = INDEX;
} else if (_char / _a > 30) {
pageCategory = DETAIL;
}
return pageCategory;
}
/**
* A simple regex rule to sniff the possible category of a web page
* */
public static PageCategory sniff(String urlString) {
PageCategory pageCategory = UNKNOWN;
if (StringUtils.isEmpty(urlString)) {
return pageCategory;
}
final String url = urlString.toLowerCase();
// Notice : ***DO KEEP*** the right order
if (url.endsWith("/")) {
pageCategory = INDEX;
}
else if (StringUtils.countMatches(url, "/") <= 3) {
// http://t.tt/12345678
pageCategory = INDEX;
}
else if (Stream.of(INDEX_PAGE_URL_PATTERNS).anyMatch(pattern -> pattern.matcher(url).matches())) {
pageCategory = INDEX;
}
else if (Stream.of(DETAIL_PAGE_URL_PATTERNS).anyMatch(pattern -> pattern.matcher(url).matches())){
pageCategory = DETAIL;
}
else if (SEARCH_PAGE_URL_PATTERN.matcher(url).matches()) {
pageCategory = SEARCH;
}
else if (MEDIA_PAGE_URL_PATTERN.matcher(url).matches()) {
pageCategory = MEDIA;
}
return pageCategory;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/ProcessingException.java
|
package ai.platon.pulsar.boilerpipe.utils;
/**
* Exception for signaling failure in the processing pipeline.
*/
public class ProcessingException extends Exception {
private static final long serialVersionUID = 1L;
public ProcessingException() {
super();
}
public ProcessingException(String message, Throwable cause) {
super(message, cause);
}
public ProcessingException(String message) {
super(message);
}
public ProcessingException(Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/ScentUtils.java
|
package ai.platon.pulsar.boilerpipe.utils;
import com.google.common.collect.ListMultimap;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by vincent on 16-10-27.
* Copyright @ 2013-2016 Platon AI. All rights reserved
*/
public class ScentUtils {
public static boolean checkFieldIsAPersonName(String fieldName) {
return fieldName.equals("author") || fieldName.equals("director");
}
public static Map<String, String> extract(String text, ListMultimap<String, String> regexFieldRules) {
return extract(text, regexFieldRules, 1, 2);
}
public static Map<String, String> extract(String text, ListMultimap<String, String> regexFieldRules, int keyGroup, int valueGroup) {
Map<String, String> results = new LinkedHashMap<>();
for (Map.Entry<String, String> rule : regexFieldRules.entries()) {
String[] parts = extractToArray(text, Pattern.compile(rule.getValue()), keyGroup, valueGroup);
if (parts[0].length() > 0 && parts[1].length() > 0) {
String key = rule.getKey();
String value = filterExtractedValue(key, parts[1]);
if (value == null || value.isEmpty()) {
continue;
}
// The value is a name, but the value does not like a name
if (checkFieldIsAPersonName(key)) {
if (Arrays.stream(BoiConstants.BAD_PHRASE_IN_NAME).anyMatch(value::contains)) {
value = null;
}
}
if (value == null || value.isEmpty()) {
continue;
}
Integer maxLength = BoiConstants.MAX_FIELD_LENGTH_MAP.get(key);
if (maxLength == null) {
results.put(key, value);
} else if (value.length() <= maxLength) {
results.put(key, value);
}
}
} // for
return results;
}
private static String filterExtractedValue(String key, String value) {
for (String bounder : BoiConstants.REGEX_FIELD_BOUNDERS) {
if (value.endsWith(bounder)) {
value = StringUtils.substringBefore(value, bounder);
break;
}
}
return value;
}
public static String[] extractToArray(String text, Pattern pattern) {
return extractToArray(text, pattern, 1, 2);
}
public static String[] extractToArray(String text, Pattern pattern, int keyGroup, int valueGroup) {
String[] parts = {"", ""};
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[0] = k.trim();
parts[1] = v.trim();
}
}
}
return parts;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/UnicodeTokenizer.java
|
package ai.platon.pulsar.boilerpipe.utils;
import java.util.regex.Pattern;
/**
* Tokenizes text according to Unicode word boundaries and strips off non-word characters.
*
* TODO : employ a better tokenize utility
*/
public class UnicodeTokenizer {
private static final Pattern PAT_WORD_BOUNDARY = Pattern.compile("\\b");
private static final Pattern PAT_NOT_WORD_BOUNDARY = Pattern.compile("[\u2063]*([\\\"'\\.,\\!\\@\\-\\:\\;\\$\\?\\(\\)/])[\u2063]*");
/**
* Tokenizes the text and returns an array of tokens.
*
* @param text The text
* @return The tokens
*/
public static String[] tokenize(final CharSequence text) {
return PAT_NOT_WORD_BOUNDARY.matcher(PAT_WORD_BOUNDARY.matcher(text).replaceAll("\u2063"))
.replaceAll("$1").replaceAll("[ \u2063]+", " ").trim().split("[ ]+");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe
|
java-sources/ai/platon/pulsar/pulsar-boilerpipe/3.0.15/ai/platon/pulsar/boilerpipe/utils/package-info.java
|
/**
* Some helper classes.
*/
package ai.platon.pulsar.boilerpipe.utils;
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/ChromeDevTools.java
|
package com.github.kklisura.cdt.protocol.v2023;
/*-
* #%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.commands.Runtime;
import com.github.kklisura.cdt.protocol.v2023.commands.*;
public interface ChromeDevTools {
/** Returns the Console command. */
Console getConsole();
/** Returns the Debugger command. */
Debugger getDebugger();
/** Returns the HeapProfiler command. */
HeapProfiler getHeapProfiler();
/** Returns the Profiler command. */
Profiler getProfiler();
/** Returns the Runtime command. */
Runtime getRuntime();
/** Returns the Schema command. */
Schema getSchema();
/** Returns the Accessibility command. */
Accessibility getAccessibility();
/** Returns the Animation command. */
Animation getAnimation();
/** Returns the Audits command. */
Audits getAudits();
/** Returns the Autofill command. */
Autofill getAutofill();
/** Returns the BackgroundService command. */
BackgroundService getBackgroundService();
/** Returns the Browser command. */
Browser getBrowser();
/** Returns the CSS command. */
CSS getCSS();
/** Returns the CacheStorage command. */
CacheStorage getCacheStorage();
/** Returns the Cast command. */
Cast getCast();
/** Returns the DOM command. */
DOM getDOM();
/** Returns the DOMDebugger command. */
DOMDebugger getDOMDebugger();
/** Returns the EventBreakpoints command. */
EventBreakpoints getEventBreakpoints();
/** Returns the DOMSnapshot command. */
DOMSnapshot getDOMSnapshot();
/** Returns the DOMStorage command. */
DOMStorage getDOMStorage();
/** Returns the Database command. */
Database getDatabase();
/** Returns the DeviceOrientation command. */
DeviceOrientation getDeviceOrientation();
/** Returns the Emulation command. */
Emulation getEmulation();
/** Returns the HeadlessExperimental command. */
HeadlessExperimental getHeadlessExperimental();
/** Returns the IO command. */
IO getIO();
/** Returns the IndexedDB command. */
IndexedDB getIndexedDB();
/** Returns the Input command. */
Input getInput();
/** Returns the Inspector command. */
Inspector getInspector();
/** Returns the LayerTree command. */
LayerTree getLayerTree();
/** Returns the Log command. */
Log getLog();
/** Returns the Memory command. */
Memory getMemory();
/** Returns the Network command. */
Network getNetwork();
/** Returns the Overlay command. */
Overlay getOverlay();
/** Returns the Page command. */
Page getPage();
/** Returns the Performance command. */
Performance getPerformance();
/** Returns the PerformanceTimeline command. */
PerformanceTimeline getPerformanceTimeline();
/** Returns the Security command. */
Security getSecurity();
/** Returns the ServiceWorker command. */
ServiceWorker getServiceWorker();
/** Returns the Storage command. */
Storage getStorage();
/** Returns the SystemInfo command. */
SystemInfo getSystemInfo();
/** Returns the Target command. */
Target getTarget();
/** Returns the Tethering command. */
Tethering getTethering();
/** Returns the Tracing command. */
Tracing getTracing();
/** Returns the Fetch command. */
Fetch getFetch();
/** Returns the WebAudio command. */
WebAudio getWebAudio();
/** Returns the WebAuthn command. */
WebAuthn getWebAuthn();
/** Returns the Media command. */
Media getMedia();
/** Returns the DeviceAccess command. */
DeviceAccess getDeviceAccess();
/** Returns the Preload command. */
Preload getPreload();
/** Returns the FedCm command. */
FedCm getFedCm();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/package-info.java
|
package com.github.kklisura.cdt.protocol.v2023;
/*
* Chrome DevTools protocol version 2023.
*
* <p>Generated by kklisura.
*
* @see <a href="https://github.com/kklisura/chrome-devtools-java-client">Chrome DevTools Java Client</a>
* @see <a href="https://chromedevtools.github.io/devtools-protocol/tot/">Chrome DevTools Protocol</a>
*/
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Accessibility.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.accessibility.LoadComplete;
import com.github.kklisura.cdt.protocol.v2023.events.accessibility.NodesUpdated;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.accessibility.AXNode;
import java.util.List;
@Experimental
public interface Accessibility {
/** Disables the accessibility domain. */
void disable();
/**
* Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method
* calls. This turns on accessibility for the page, which can impact performance until
* accessibility is disabled.
*/
void enable();
/**
* Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getPartialAXTree();
/**
* Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.
*
* @param nodeId Identifier of the node to get the partial accessibility tree for.
* @param backendNodeId Identifier of the backend node to get the partial accessibility tree for.
* @param objectId JavaScript object id of the node wrapper to get the partial accessibility tree
* for.
* @param fetchRelatives Whether to fetch this node's ancestors, siblings and children. Defaults
* to true.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getPartialAXTree(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId,
@Optional @ParamName("fetchRelatives") Boolean fetchRelatives);
/** Fetches the entire accessibility tree for the root Document */
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getFullAXTree();
/**
* Fetches the entire accessibility tree for the root Document
*
* @param depth The maximum depth at which descendants of the root node should be retrieved. If
* omitted, the full tree is returned.
* @param frameId The frame for whose document the AX tree should be retrieved. If omited, the
* root frame is used.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getFullAXTree(
@Optional @ParamName("depth") Integer depth, @Optional @ParamName("frameId") String frameId);
/** Fetches the root node. Requires `enable()` to have been called previously. */
@Experimental
@Returns("node")
AXNode getRootAXNode();
/**
* Fetches the root node. Requires `enable()` to have been called previously.
*
* @param frameId The frame in whose document the node resides. If omitted, the root frame is
* used.
*/
@Experimental
@Returns("node")
AXNode getRootAXNode(@Optional @ParamName("frameId") String frameId);
/**
* Fetches a node and all ancestors up to and including the root. Requires `enable()` to have been
* called previously.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getAXNodeAndAncestors();
/**
* Fetches a node and all ancestors up to and including the root. Requires `enable()` to have been
* called previously.
*
* @param nodeId Identifier of the node to get.
* @param backendNodeId Identifier of the backend node to get.
* @param objectId JavaScript object id of the node wrapper to get.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getAXNodeAndAncestors(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Fetches a particular accessibility node by AXNodeId. Requires `enable()` to have been called
* previously.
*
* @param id
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getChildAXNodes(@ParamName("id") String id);
/**
* Fetches a particular accessibility node by AXNodeId. Requires `enable()` to have been called
* previously.
*
* @param id
* @param frameId The frame in whose document the node resides. If omitted, the root frame is
* used.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> getChildAXNodes(
@ParamName("id") String id, @Optional @ParamName("frameId") String frameId);
/**
* Query a DOM node's accessibility subtree for accessible name and role. This command computes
* the name and role for all nodes in the subtree, including those that are ignored for
* accessibility, and returns those that mactch the specified name and role. If no DOM node is
* specified, or the DOM node does not exist, the command returns an error. If neither
* `accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> queryAXTree();
/**
* Query a DOM node's accessibility subtree for accessible name and role. This command computes
* the name and role for all nodes in the subtree, including those that are ignored for
* accessibility, and returns those that mactch the specified name and role. If no DOM node is
* specified, or the DOM node does not exist, the command returns an error. If neither
* `accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree.
*
* @param nodeId Identifier of the node for the root to query.
* @param backendNodeId Identifier of the backend node for the root to query.
* @param objectId JavaScript object id of the node wrapper for the root to query.
* @param accessibleName Find nodes with this computed name.
* @param role Find nodes with this computed role.
*/
@Experimental
@Returns("nodes")
@ReturnTypeParameter(AXNode.class)
List<AXNode> queryAXTree(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId,
@Optional @ParamName("accessibleName") String accessibleName,
@Optional @ParamName("role") String role);
/**
* The loadComplete event mirrors the load complete event sent by the browser to assistive
* technology when the web page has finished loading.
*/
@EventName("loadComplete")
@Experimental
EventListener onLoadComplete(EventHandler<LoadComplete> eventListener);
/**
* The nodesUpdated event is sent every time a previously requested node has changed the in tree.
*/
@EventName("nodesUpdated")
@Experimental
EventListener onNodesUpdated(EventHandler<NodesUpdated> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Animation.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.animation.AnimationCanceled;
import com.github.kklisura.cdt.protocol.v2023.events.animation.AnimationCreated;
import com.github.kklisura.cdt.protocol.v2023.events.animation.AnimationStarted;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.EventName;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Returns;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.RemoteObject;
import java.util.List;
@Experimental
public interface Animation {
/** Disables animation domain notifications. */
void disable();
/** Enables animation domain notifications. */
void enable();
/**
* Returns the current time of the an animation.
*
* @param id Id of animation.
*/
@Returns("currentTime")
Double getCurrentTime(@ParamName("id") String id);
/** Gets the playback rate of the document timeline. */
@Returns("playbackRate")
Double getPlaybackRate();
/**
* Releases a set of animations to no longer be manipulated.
*
* @param animations List of animation ids to seek.
*/
void releaseAnimations(@ParamName("animations") List<String> animations);
/**
* Gets the remote object of the Animation.
*
* @param animationId Animation id.
*/
@Returns("remoteObject")
RemoteObject resolveAnimation(@ParamName("animationId") String animationId);
/**
* Seek a set of animations to a particular time within each animation.
*
* @param animations List of animation ids to seek.
* @param currentTime Set the current time of each animation.
*/
void seekAnimations(
@ParamName("animations") List<String> animations,
@ParamName("currentTime") Double currentTime);
/**
* Sets the paused state of a set of animations.
*
* @param animations Animations to set the pause state of.
* @param paused Paused state to set to.
*/
void setPaused(
@ParamName("animations") List<String> animations, @ParamName("paused") Boolean paused);
/**
* Sets the playback rate of the document timeline.
*
* @param playbackRate Playback rate for animations on page
*/
void setPlaybackRate(@ParamName("playbackRate") Double playbackRate);
/**
* Sets the timing of an animation node.
*
* @param animationId Animation id.
* @param duration Duration of the animation.
* @param delay Delay of the animation.
*/
void setTiming(
@ParamName("animationId") String animationId,
@ParamName("duration") Double duration,
@ParamName("delay") Double delay);
/** Event for when an animation has been cancelled. */
@EventName("animationCanceled")
EventListener onAnimationCanceled(EventHandler<AnimationCanceled> eventListener);
/** Event for each animation that has been created. */
@EventName("animationCreated")
EventListener onAnimationCreated(EventHandler<AnimationCreated> eventListener);
/** Event for animation that has been started. */
@EventName("animationStarted")
EventListener onAnimationStarted(EventHandler<AnimationStarted> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Audits.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.audits.IssueAdded;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.audits.EncodedResponse;
import com.github.kklisura.cdt.protocol.v2023.types.audits.GenericIssueDetails;
import com.github.kklisura.cdt.protocol.v2023.types.audits.GetEncodedResponseEncoding;
import java.util.List;
/** Audits domain allows investigation of page violations and possible improvements. */
@Experimental
public interface Audits {
/**
* Returns the response body and size if it were re-encoded with the specified settings. Only
* applies to images.
*
* @param requestId Identifier of the network request to get content for.
* @param encoding The encoding to use.
*/
EncodedResponse getEncodedResponse(
@ParamName("requestId") String requestId,
@ParamName("encoding") GetEncodedResponseEncoding encoding);
/**
* Returns the response body and size if it were re-encoded with the specified settings. Only
* applies to images.
*
* @param requestId Identifier of the network request to get content for.
* @param encoding The encoding to use.
* @param quality The quality of the encoding (0-1). (defaults to 1)
* @param sizeOnly Whether to only return the size information (defaults to false).
*/
EncodedResponse getEncodedResponse(
@ParamName("requestId") String requestId,
@ParamName("encoding") GetEncodedResponseEncoding encoding,
@Optional @ParamName("quality") Double quality,
@Optional @ParamName("sizeOnly") Boolean sizeOnly);
/** Disables issues domain, prevents further issues from being reported to the client. */
void disable();
/**
* Enables issues domain, sends the issues collected so far to the client by means of the
* `issueAdded` event.
*/
void enable();
/**
* Runs the contrast check for the target page. Found issues are reported using Audits.issueAdded
* event.
*/
void checkContrast();
/**
* Runs the contrast check for the target page. Found issues are reported using Audits.issueAdded
* event.
*
* @param reportAAA Whether to report WCAG AAA level issues. Default is false.
*/
void checkContrast(@Optional @ParamName("reportAAA") Boolean reportAAA);
/**
* Runs the form issues check for the target page. Found issues are reported using
* Audits.issueAdded event.
*/
@Returns("formIssues")
@ReturnTypeParameter(GenericIssueDetails.class)
List<GenericIssueDetails> checkFormsIssues();
@EventName("issueAdded")
EventListener onIssueAdded(EventHandler<IssueAdded> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Autofill.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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 com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.types.autofill.Address;
import com.github.kklisura.cdt.protocol.v2023.types.autofill.CreditCard;
import java.util.List;
/** Defines commands and events for Autofill. */
@Experimental
public interface Autofill {
/**
* Trigger autofill on a form identified by the fieldId. If the field and related form cannot be
* autofilled, returns an error.
*
* @param fieldId Identifies a field that serves as an anchor for autofill.
* @param card Credit card information to fill out the form. Credit card data is not saved.
*/
void trigger(@ParamName("fieldId") Integer fieldId, @ParamName("card") CreditCard card);
/**
* Trigger autofill on a form identified by the fieldId. If the field and related form cannot be
* autofilled, returns an error.
*
* @param fieldId Identifies a field that serves as an anchor for autofill.
* @param frameId Identifies the frame that field belongs to.
* @param card Credit card information to fill out the form. Credit card data is not saved.
*/
void trigger(
@ParamName("fieldId") Integer fieldId,
@Optional @ParamName("frameId") String frameId,
@ParamName("card") CreditCard card);
/**
* Set addresses so that developers can verify their forms implementation.
*
* @param addresses
*/
void setAddresses(@ParamName("addresses") List<Address> addresses);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/BackgroundService.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.backgroundservice.BackgroundServiceEventReceived;
import com.github.kklisura.cdt.protocol.v2023.events.backgroundservice.RecordingStateChanged;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.EventName;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.backgroundservice.ServiceName;
/** Defines events for background web platform features. */
@Experimental
public interface BackgroundService {
/**
* Enables event updates for the service.
*
* @param service
*/
void startObserving(@ParamName("service") ServiceName service);
/**
* Disables event updates for the service.
*
* @param service
*/
void stopObserving(@ParamName("service") ServiceName service);
/**
* Set the recording state for the service.
*
* @param shouldRecord
* @param service
*/
void setRecording(
@ParamName("shouldRecord") Boolean shouldRecord, @ParamName("service") ServiceName service);
/**
* Clears all stored data for the service.
*
* @param service
*/
void clearEvents(@ParamName("service") ServiceName service);
/** Called when the recording state for the service has been updated. */
@EventName("recordingStateChanged")
EventListener onRecordingStateChanged(EventHandler<RecordingStateChanged> eventListener);
/**
* Called with all existing backgroundServiceEvents when enabled, and all new events afterwards if
* enabled and recording.
*/
@EventName("backgroundServiceEventReceived")
EventListener onBackgroundServiceEventReceived(
EventHandler<BackgroundServiceEventReceived> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Browser.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.browser.DownloadProgress;
import com.github.kklisura.cdt.protocol.v2023.events.browser.DownloadWillBegin;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.browser.*;
import java.util.List;
/** The Browser domain defines methods and events for browser managing. */
public interface Browser {
/**
* Set permission settings for given origin.
*
* @param permission Descriptor of permission to override.
* @param setting Setting of the permission.
*/
@Experimental
void setPermission(
@ParamName("permission") PermissionDescriptor permission,
@ParamName("setting") PermissionSetting setting);
/**
* Set permission settings for given origin.
*
* @param permission Descriptor of permission to override.
* @param setting Setting of the permission.
* @param origin Origin the permission applies to, all origins if not specified.
* @param browserContextId Context to override. When omitted, default browser context is used.
*/
@Experimental
void setPermission(
@ParamName("permission") PermissionDescriptor permission,
@ParamName("setting") PermissionSetting setting,
@Optional @ParamName("origin") String origin,
@Optional @ParamName("browserContextId") String browserContextId);
/**
* Grant specific permissions to the given origin and reject all others.
*
* @param permissions
*/
@Experimental
void grantPermissions(@ParamName("permissions") List<PermissionType> permissions);
/**
* Grant specific permissions to the given origin and reject all others.
*
* @param permissions
* @param origin Origin the permission applies to, all origins if not specified.
* @param browserContextId BrowserContext to override permissions. When omitted, default browser
* context is used.
*/
@Experimental
void grantPermissions(
@ParamName("permissions") List<PermissionType> permissions,
@Optional @ParamName("origin") String origin,
@Optional @ParamName("browserContextId") String browserContextId);
/** Reset all permission management for all origins. */
@Experimental
void resetPermissions();
/**
* Reset all permission management for all origins.
*
* @param browserContextId BrowserContext to reset permissions. When omitted, default browser
* context is used.
*/
@Experimental
void resetPermissions(@Optional @ParamName("browserContextId") String browserContextId);
/**
* Set the behavior when downloading a file.
*
* @param behavior Whether to allow all or deny all download requests, or use default Chrome
* behavior if available (otherwise deny). |allowAndName| allows download and names files
* according to their dowmload guids.
*/
@Experimental
void setDownloadBehavior(@ParamName("behavior") SetDownloadBehaviorBehavior behavior);
/**
* Set the behavior when downloading a file.
*
* @param behavior Whether to allow all or deny all download requests, or use default Chrome
* behavior if available (otherwise deny). |allowAndName| allows download and names files
* according to their dowmload guids.
* @param browserContextId BrowserContext to set download behavior. When omitted, default browser
* context is used.
* @param downloadPath The default path to save downloaded files to. This is required if behavior
* is set to 'allow' or 'allowAndName'.
* @param eventsEnabled Whether to emit download events (defaults to false).
*/
@Experimental
void setDownloadBehavior(
@ParamName("behavior") SetDownloadBehaviorBehavior behavior,
@Optional @ParamName("browserContextId") String browserContextId,
@Optional @ParamName("downloadPath") String downloadPath,
@Optional @ParamName("eventsEnabled") Boolean eventsEnabled);
/**
* Cancel a download if in progress
*
* @param guid Global unique identifier of the download.
*/
@Experimental
void cancelDownload(@ParamName("guid") String guid);
/**
* Cancel a download if in progress
*
* @param guid Global unique identifier of the download.
* @param browserContextId BrowserContext to perform the action in. When omitted, default browser
* context is used.
*/
@Experimental
void cancelDownload(
@ParamName("guid") String guid,
@Optional @ParamName("browserContextId") String browserContextId);
/** Close browser gracefully. */
void close();
/** Crashes browser on the main thread. */
@Experimental
void crash();
/** Crashes GPU process. */
@Experimental
void crashGpuProcess();
/** Returns version information. */
Version getVersion();
/**
* Returns the command line switches for the browser process if, and only if --enable-automation
* is on the commandline.
*/
@Experimental
@Returns("arguments")
@ReturnTypeParameter(String.class)
List<String> getBrowserCommandLine();
/** Get Chrome histograms. */
@Experimental
@Returns("histograms")
@ReturnTypeParameter(Histogram.class)
List<Histogram> getHistograms();
/**
* Get Chrome histograms.
*
* @param query Requested substring in name. Only histograms which have query as a substring in
* their name are extracted. An empty or absent query returns all histograms.
* @param delta If true, retrieve delta since last delta call.
*/
@Experimental
@Returns("histograms")
@ReturnTypeParameter(Histogram.class)
List<Histogram> getHistograms(
@Optional @ParamName("query") String query, @Optional @ParamName("delta") Boolean delta);
/**
* Get a Chrome histogram by name.
*
* @param name Requested histogram name.
*/
@Experimental
@Returns("histogram")
Histogram getHistogram(@ParamName("name") String name);
/**
* Get a Chrome histogram by name.
*
* @param name Requested histogram name.
* @param delta If true, retrieve delta since last delta call.
*/
@Experimental
@Returns("histogram")
Histogram getHistogram(
@ParamName("name") String name, @Optional @ParamName("delta") Boolean delta);
/**
* Get position and size of the browser window.
*
* @param windowId Browser window id.
*/
@Experimental
@Returns("bounds")
Bounds getWindowBounds(@ParamName("windowId") Integer windowId);
/** Get the browser window that contains the devtools target. */
@Experimental
WindowForTarget getWindowForTarget();
/**
* Get the browser window that contains the devtools target.
*
* @param targetId Devtools agent host id. If called as a part of the session, associated targetId
* is used.
*/
@Experimental
WindowForTarget getWindowForTarget(@Optional @ParamName("targetId") String targetId);
/**
* Set position and/or size of the browser window.
*
* @param windowId Browser window id.
* @param bounds New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be
* combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged.
*/
@Experimental
void setWindowBounds(@ParamName("windowId") Integer windowId, @ParamName("bounds") Bounds bounds);
/** Set dock tile details, platform-specific. */
@Experimental
void setDockTile();
/**
* Set dock tile details, platform-specific.
*
* @param badgeLabel
* @param image Png encoded image. (Encoded as a base64 string when passed over JSON)
*/
@Experimental
void setDockTile(
@Optional @ParamName("badgeLabel") String badgeLabel,
@Optional @ParamName("image") String image);
/**
* Invoke custom browser commands used by telemetry.
*
* @param commandId
*/
@Experimental
void executeBrowserCommand(@ParamName("commandId") BrowserCommandId commandId);
/**
* Allows a site to use privacy sandbox features that require enrollment without the site actually
* being enrolled. Only supported on page targets.
*
* @param url
*/
void addPrivacySandboxEnrollmentOverride(@ParamName("url") String url);
/** Fired when page is about to start a download. */
@EventName("downloadWillBegin")
@Experimental
EventListener onDownloadWillBegin(EventHandler<DownloadWillBegin> eventListener);
/** Fired when download makes progress. Last call has |done| == true. */
@EventName("downloadProgress")
@Experimental
EventListener onDownloadProgress(EventHandler<DownloadProgress> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/CSS.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.css.*;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.css.*;
import java.util.List;
/**
* This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles)
* have an associated `id` used in subsequent operations on the related object. Each object type has
* a specific `id` structure, and those are not interchangeable between objects of different kinds.
* CSS objects can be loaded using the `get*ForNode()` calls (which accept a DOM node id). A client
* can also keep track of stylesheets via the `styleSheetAdded`/`styleSheetRemoved` events and
* subsequently load the required stylesheet contents using the `getStyleSheet[Text]()` methods.
*/
@Experimental
public interface CSS {
/**
* Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the
* position specified by `location`.
*
* @param styleSheetId The css style sheet identifier where a new rule should be inserted.
* @param ruleText The text of a new rule.
* @param location Text position of a new rule in the target style sheet.
*/
@Returns("rule")
CSSRule addRule(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("ruleText") String ruleText,
@ParamName("location") SourceRange location);
/**
* Returns all class names from specified stylesheet.
*
* @param styleSheetId
*/
@Returns("classNames")
@ReturnTypeParameter(String.class)
List<String> collectClassNames(@ParamName("styleSheetId") String styleSheetId);
/**
* Creates a new special "via-inspector" stylesheet in the frame with given `frameId`.
*
* @param frameId Identifier of the frame where "via-inspector" stylesheet should be created.
*/
@Returns("styleSheetId")
String createStyleSheet(@ParamName("frameId") String frameId);
/** Disables the CSS agent for the given page. */
void disable();
/**
* Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been
* enabled until the result of this command is received.
*/
void enable();
/**
* Ensures that the given node will have specified pseudo-classes whenever its style is computed
* by the browser.
*
* @param nodeId The element id for which to force the pseudo state.
* @param forcedPseudoClasses Element pseudo classes to force when computing the element's style.
*/
void forcePseudoState(
@ParamName("nodeId") Integer nodeId,
@ParamName("forcedPseudoClasses") List<String> forcedPseudoClasses);
/** @param nodeId Id of the node to get background colors for. */
BackgroundColors getBackgroundColors(@ParamName("nodeId") Integer nodeId);
/**
* Returns the computed style for a DOM node identified by `nodeId`.
*
* @param nodeId
*/
@Returns("computedStyle")
@ReturnTypeParameter(CSSComputedStyleProperty.class)
List<CSSComputedStyleProperty> getComputedStyleForNode(@ParamName("nodeId") Integer nodeId);
/**
* Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using
* DOM attributes) for a DOM node identified by `nodeId`.
*
* @param nodeId
*/
InlineStylesForNode getInlineStylesForNode(@ParamName("nodeId") Integer nodeId);
/**
* Returns requested styles for a DOM node identified by `nodeId`.
*
* @param nodeId
*/
MatchedStylesForNode getMatchedStylesForNode(@ParamName("nodeId") Integer nodeId);
/** Returns all media queries parsed by the rendering engine. */
@Returns("medias")
@ReturnTypeParameter(CSSMedia.class)
List<CSSMedia> getMediaQueries();
/**
* Requests information about platform fonts which we used to render child TextNodes in the given
* node.
*
* @param nodeId
*/
@Returns("fonts")
@ReturnTypeParameter(PlatformFontUsage.class)
List<PlatformFontUsage> getPlatformFontsForNode(@ParamName("nodeId") Integer nodeId);
/**
* Returns the current textual content for a stylesheet.
*
* @param styleSheetId
*/
@Returns("text")
String getStyleSheetText(@ParamName("styleSheetId") String styleSheetId);
/**
* Returns all layers parsed by the rendering engine for the tree scope of a node. Given a DOM
* element identified by nodeId, getLayersForNode returns the root layer for the nearest ancestor
* document or shadow root. The layer root contains the full layer tree for the tree scope and
* their ordering.
*
* @param nodeId
*/
@Experimental
@Returns("rootLayer")
CSSLayerData getLayersForNode(@ParamName("nodeId") Integer nodeId);
/**
* Starts tracking the given computed styles for updates. The specified array of properties
* replaces the one previously specified. Pass empty array to disable tracking. Use
* takeComputedStyleUpdates to retrieve the list of nodes that had properties modified. The
* changes to computed style properties are only tracked for nodes pushed to the front-end by the
* DOM agent. If no changes to the tracked properties occur after the node has been pushed to the
* front-end, no updates will be issued for the node.
*
* @param propertiesToTrack
*/
@Experimental
void trackComputedStyleUpdates(
@ParamName("propertiesToTrack") List<CSSComputedStyleProperty> propertiesToTrack);
/** Polls the next batch of computed style updates. */
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> takeComputedStyleUpdates();
/**
* Find a rule with the given active property for the given node and set the new value for this
* property
*
* @param nodeId The element id for which to set property.
* @param propertyName
* @param value
*/
void setEffectivePropertyValueForNode(
@ParamName("nodeId") Integer nodeId,
@ParamName("propertyName") String propertyName,
@ParamName("value") String value);
/**
* Modifies the keyframe rule key text.
*
* @param styleSheetId
* @param range
* @param keyText
*/
@Returns("keyText")
Value setKeyframeKey(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("keyText") String keyText);
/**
* Modifies the rule selector.
*
* @param styleSheetId
* @param range
* @param text
*/
@Returns("media")
CSSMedia setMediaText(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("text") String text);
/**
* Modifies the expression of a container query.
*
* @param styleSheetId
* @param range
* @param text
*/
@Experimental
@Returns("containerQuery")
CSSContainerQuery setContainerQueryText(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("text") String text);
/**
* Modifies the expression of a supports at-rule.
*
* @param styleSheetId
* @param range
* @param text
*/
@Experimental
@Returns("supports")
CSSSupports setSupportsText(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("text") String text);
/**
* Modifies the expression of a scope at-rule.
*
* @param styleSheetId
* @param range
* @param text
*/
@Experimental
@Returns("scope")
CSSScope setScopeText(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("text") String text);
/**
* Modifies the rule selector.
*
* @param styleSheetId
* @param range
* @param selector
*/
@Returns("selectorList")
SelectorList setRuleSelector(
@ParamName("styleSheetId") String styleSheetId,
@ParamName("range") SourceRange range,
@ParamName("selector") String selector);
/**
* Sets the new stylesheet text.
*
* @param styleSheetId
* @param text
*/
@Returns("sourceMapURL")
String setStyleSheetText(
@ParamName("styleSheetId") String styleSheetId, @ParamName("text") String text);
/**
* Applies specified style edits one after another in the given order.
*
* @param edits
*/
@Returns("styles")
@ReturnTypeParameter(CSSStyle.class)
List<CSSStyle> setStyleTexts(@ParamName("edits") List<StyleDeclarationEdit> edits);
/** Enables the selector recording. */
void startRuleUsageTracking();
/**
* Stop tracking rule usage and return the list of rules that were used since last call to
* `takeCoverageDelta` (or since start of coverage instrumentation).
*/
@Returns("ruleUsage")
@ReturnTypeParameter(RuleUsage.class)
List<RuleUsage> stopRuleUsageTracking();
/**
* Obtain list of rules that became used since last call to this method (or since start of
* coverage instrumentation).
*/
TakeCoverageDelta takeCoverageDelta();
/**
* Enables/disables rendering of local CSS fonts (enabled by default).
*
* @param enabled Whether rendering of local fonts is enabled.
*/
@Experimental
void setLocalFontsEnabled(@ParamName("enabled") Boolean enabled);
/**
* Fires whenever a web font is updated. A non-empty font parameter indicates a successfully
* loaded web font.
*/
@EventName("fontsUpdated")
EventListener onFontsUpdated(EventHandler<FontsUpdated> eventListener);
/**
* Fires whenever a MediaQuery result changes (for example, after a browser window has been
* resized.) The current implementation considers only viewport-dependent media features.
*/
@EventName("mediaQueryResultChanged")
EventListener onMediaQueryResultChanged(EventHandler<MediaQueryResultChanged> eventListener);
/** Fired whenever an active document stylesheet is added. */
@EventName("styleSheetAdded")
EventListener onStyleSheetAdded(EventHandler<StyleSheetAdded> eventListener);
/** Fired whenever a stylesheet is changed as a result of the client operation. */
@EventName("styleSheetChanged")
EventListener onStyleSheetChanged(EventHandler<StyleSheetChanged> eventListener);
/** Fired whenever an active document stylesheet is removed. */
@EventName("styleSheetRemoved")
EventListener onStyleSheetRemoved(EventHandler<StyleSheetRemoved> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/CacheStorage.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.*;
import com.github.kklisura.cdt.protocol.v2023.types.cachestorage.Cache;
import com.github.kklisura.cdt.protocol.v2023.types.cachestorage.CachedResponse;
import com.github.kklisura.cdt.protocol.v2023.types.cachestorage.Header;
import com.github.kklisura.cdt.protocol.v2023.types.cachestorage.RequestEntries;
import com.github.kklisura.cdt.protocol.v2023.types.storage.StorageBucket;
import java.util.List;
@Experimental
public interface CacheStorage {
/**
* Deletes a cache.
*
* @param cacheId Id of cache for deletion.
*/
void deleteCache(@ParamName("cacheId") String cacheId);
/**
* Deletes a cache entry.
*
* @param cacheId Id of cache where the entry will be deleted.
* @param request URL spec of the request.
*/
void deleteEntry(@ParamName("cacheId") String cacheId, @ParamName("request") String request);
/** Requests cache names. */
@Returns("caches")
@ReturnTypeParameter(Cache.class)
List<Cache> requestCacheNames();
/**
* Requests cache names.
*
* @param securityOrigin At least and at most one of securityOrigin, storageKey, storageBucket
* must be specified. Security origin.
* @param storageKey Storage key.
* @param storageBucket Storage bucket. If not specified, it uses the default bucket.
*/
@Returns("caches")
@ReturnTypeParameter(Cache.class)
List<Cache> requestCacheNames(
@Optional @ParamName("securityOrigin") String securityOrigin,
@Optional @ParamName("storageKey") String storageKey,
@Optional @ParamName("storageBucket") StorageBucket storageBucket);
/**
* Fetches cache entry.
*
* @param cacheId Id of cache that contains the entry.
* @param requestURL URL spec of the request.
* @param requestHeaders headers of the request.
*/
@Returns("response")
CachedResponse requestCachedResponse(
@ParamName("cacheId") String cacheId,
@ParamName("requestURL") String requestURL,
@ParamName("requestHeaders") List<Header> requestHeaders);
/**
* Requests data from cache.
*
* @param cacheId ID of cache to get entries from.
*/
RequestEntries requestEntries(@ParamName("cacheId") String cacheId);
/**
* Requests data from cache.
*
* @param cacheId ID of cache to get entries from.
* @param skipCount Number of records to skip.
* @param pageSize Number of records to fetch.
* @param pathFilter If present, only return the entries containing this substring in the path
*/
RequestEntries requestEntries(
@ParamName("cacheId") String cacheId,
@Optional @ParamName("skipCount") Integer skipCount,
@Optional @ParamName("pageSize") Integer pageSize,
@Optional @ParamName("pathFilter") String pathFilter);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Cast.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.cast.IssueUpdated;
import com.github.kklisura.cdt.protocol.v2023.events.cast.SinksUpdated;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.EventName;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Optional;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
/**
* A domain for interacting with Cast, Presentation API, and Remote Playback API functionalities.
*/
@Experimental
public interface Cast {
/**
* Starts observing for sinks that can be used for tab mirroring, and if set, sinks compatible
* with |presentationUrl| as well. When sinks are found, a |sinksUpdated| event is fired. Also
* starts observing for issue messages. When an issue is added or removed, an |issueUpdated| event
* is fired.
*/
void enable();
/**
* Starts observing for sinks that can be used for tab mirroring, and if set, sinks compatible
* with |presentationUrl| as well. When sinks are found, a |sinksUpdated| event is fired. Also
* starts observing for issue messages. When an issue is added or removed, an |issueUpdated| event
* is fired.
*
* @param presentationUrl
*/
void enable(@Optional @ParamName("presentationUrl") String presentationUrl);
/** Stops observing for sinks and issues. */
void disable();
/**
* Sets a sink to be used when the web page requests the browser to choose a sink via Presentation
* API, Remote Playback API, or Cast SDK.
*
* @param sinkName
*/
void setSinkToUse(@ParamName("sinkName") String sinkName);
/**
* Starts mirroring the desktop to the sink.
*
* @param sinkName
*/
void startDesktopMirroring(@ParamName("sinkName") String sinkName);
/**
* Starts mirroring the tab to the sink.
*
* @param sinkName
*/
void startTabMirroring(@ParamName("sinkName") String sinkName);
/**
* Stops the active Cast session on the sink.
*
* @param sinkName
*/
void stopCasting(@ParamName("sinkName") String sinkName);
/**
* This is fired whenever the list of available sinks changes. A sink is a device or a software
* surface that you can cast to.
*/
@EventName("sinksUpdated")
EventListener onSinksUpdated(EventHandler<SinksUpdated> eventListener);
/**
* This is fired whenever the outstanding issue/error message changes. |issueMessage| is empty if
* there is no issue.
*/
@EventName("issueUpdated")
EventListener onIssueUpdated(EventHandler<IssueUpdated> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Console.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.console.MessageAdded;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.EventName;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
/** This domain is deprecated - use Runtime or Log instead. */
@Deprecated
public interface Console {
/** Does nothing. */
void clearMessages();
/**
* Disables console domain, prevents further console messages from being reported to the client.
*/
void disable();
/**
* Enables console domain, sends the messages collected so far to the client by means of the
* `messageAdded` notification.
*/
void enable();
/** Issued when new console message is added. */
@EventName("messageAdded")
EventListener onMessageAdded(EventHandler<MessageAdded> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DOM.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.dom.*;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.dom.*;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.RemoteObject;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.StackTrace;
import java.util.List;
/**
* This domain exposes DOM read/write operations. Each DOM Node is represented with its mirror
* object that has an `id`. This `id` can be used to get additional information on the Node, resolve
* it into the JavaScript object wrapper, etc. It is important that client receives DOM events only
* for the nodes that are known to the client. Backend keeps track of the nodes that were sent to
* the client and never sends the same node twice. It is client's responsibility to collect
* information about the nodes that were sent to the client. Note that `iframe` owner elements will
* return corresponding document elements as their child nodes.
*/
public interface DOM {
/**
* Collects class names for the node with given id and all of it's child nodes.
*
* @param nodeId Id of the node to collect class names.
*/
@Experimental
@Returns("classNames")
@ReturnTypeParameter(String.class)
List<String> collectClassNamesFromSubtree(@ParamName("nodeId") Integer nodeId);
/**
* Creates a deep copy of the specified node and places it into the target container before the
* given anchor.
*
* @param nodeId Id of the node to copy.
* @param targetNodeId Id of the element to drop the copy into.
*/
@Experimental
@Returns("nodeId")
Integer copyTo(
@ParamName("nodeId") Integer nodeId, @ParamName("targetNodeId") Integer targetNodeId);
/**
* Creates a deep copy of the specified node and places it into the target container before the
* given anchor.
*
* @param nodeId Id of the node to copy.
* @param targetNodeId Id of the element to drop the copy into.
* @param insertBeforeNodeId Drop the copy before this node (if absent, the copy becomes the last
* child of `targetNodeId`).
*/
@Experimental
@Returns("nodeId")
Integer copyTo(
@ParamName("nodeId") Integer nodeId,
@ParamName("targetNodeId") Integer targetNodeId,
@Optional @ParamName("insertBeforeNodeId") Integer insertBeforeNodeId);
/**
* Describes node given its id, does not require domain to be enabled. Does not start tracking any
* objects, can be used for automation.
*/
@Returns("node")
Node describeNode();
/**
* Describes node given its id, does not require domain to be enabled. Does not start tracking any
* objects, can be used for automation.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
* @param depth The maximum depth at which children should be retrieved, defaults to 1. Use -1 for
* the entire subtree or provide an integer larger than 0.
* @param pierce Whether or not iframes and shadow roots should be traversed when returning the
* subtree (default is false).
*/
@Returns("node")
Node describeNode(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId,
@Optional @ParamName("depth") Integer depth,
@Optional @ParamName("pierce") Boolean pierce);
/**
* Scrolls the specified rect of the given node into view if not already visible. Note: exactly
* one between nodeId, backendNodeId and objectId should be passed to identify the node.
*/
@Experimental
void scrollIntoViewIfNeeded();
/**
* Scrolls the specified rect of the given node into view if not already visible. Note: exactly
* one between nodeId, backendNodeId and objectId should be passed to identify the node.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
* @param rect The rect to be scrolled into view, relative to the node's border box, in CSS
* pixels. When omitted, center of the node will be used, similar to Element.scrollIntoView.
*/
@Experimental
void scrollIntoViewIfNeeded(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId,
@Optional @ParamName("rect") Rect rect);
/** Disables DOM agent for the given page. */
void disable();
/**
* Discards search results from the session with the given id. `getSearchResults` should no longer
* be called for that search.
*
* @param searchId Unique search session identifier.
*/
@Experimental
void discardSearchResults(@ParamName("searchId") String searchId);
/** Enables DOM agent for the given page. */
void enable();
/**
* Enables DOM agent for the given page.
*
* @param includeWhitespace Whether to include whitespaces in the children array of returned
* Nodes.
*/
void enable(
@Experimental @Optional @ParamName("includeWhitespace")
EnableIncludeWhitespace includeWhitespace);
/** Focuses the given element. */
void focus();
/**
* Focuses the given element.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
*/
void focus(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Returns attributes for the specified node.
*
* @param nodeId Id of the node to retrieve attibutes for.
*/
@Returns("attributes")
@ReturnTypeParameter(String.class)
List<String> getAttributes(@ParamName("nodeId") Integer nodeId);
/** Returns boxes for the given node. */
@Returns("model")
BoxModel getBoxModel();
/**
* Returns boxes for the given node.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
*/
@Returns("model")
BoxModel getBoxModel(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Returns quads that describe node position on the page. This method might return multiple quads
* for inline nodes.
*/
@Experimental
@Returns("quads")
@ReturnTypeParameter({List.class, Double.class})
List<List<Double>> getContentQuads();
/**
* Returns quads that describe node position on the page. This method might return multiple quads
* for inline nodes.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
*/
@Experimental
@Returns("quads")
@ReturnTypeParameter({List.class, Double.class})
List<List<Double>> getContentQuads(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Returns the root DOM node (and optionally the subtree) to the caller. Implicitly enables the
* DOM domain events for the current target.
*/
@Returns("root")
Node getDocument();
/**
* Returns the root DOM node (and optionally the subtree) to the caller. Implicitly enables the
* DOM domain events for the current target.
*
* @param depth The maximum depth at which children should be retrieved, defaults to 1. Use -1 for
* the entire subtree or provide an integer larger than 0.
* @param pierce Whether or not iframes and shadow roots should be traversed when returning the
* subtree (default is false).
*/
@Returns("root")
Node getDocument(
@Optional @ParamName("depth") Integer depth, @Optional @ParamName("pierce") Boolean pierce);
/**
* Returns the root DOM node (and optionally the subtree) to the caller. Deprecated, as it is not
* designed to work well with the rest of the DOM agent. Use DOMSnapshot.captureSnapshot instead.
*/
@Deprecated
@Returns("nodes")
@ReturnTypeParameter(Node.class)
List<Node> getFlattenedDocument();
/**
* Returns the root DOM node (and optionally the subtree) to the caller. Deprecated, as it is not
* designed to work well with the rest of the DOM agent. Use DOMSnapshot.captureSnapshot instead.
*
* @param depth The maximum depth at which children should be retrieved, defaults to 1. Use -1 for
* the entire subtree or provide an integer larger than 0.
* @param pierce Whether or not iframes and shadow roots should be traversed when returning the
* subtree (default is false).
*/
@Deprecated
@Returns("nodes")
@ReturnTypeParameter(Node.class)
List<Node> getFlattenedDocument(
@Optional @ParamName("depth") Integer depth, @Optional @ParamName("pierce") Boolean pierce);
/**
* Finds nodes with a given computed style in a subtree.
*
* @param nodeId Node ID pointing to the root of a subtree.
* @param computedStyles The style to filter nodes by (includes nodes if any of properties
* matches).
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> getNodesForSubtreeByStyle(
@ParamName("nodeId") Integer nodeId,
@ParamName("computedStyles") List<CSSComputedStyleProperty> computedStyles);
/**
* Finds nodes with a given computed style in a subtree.
*
* @param nodeId Node ID pointing to the root of a subtree.
* @param computedStyles The style to filter nodes by (includes nodes if any of properties
* matches).
* @param pierce Whether or not iframes and shadow roots in the same target should be traversed
* when returning the results (default is false).
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> getNodesForSubtreeByStyle(
@ParamName("nodeId") Integer nodeId,
@ParamName("computedStyles") List<CSSComputedStyleProperty> computedStyles,
@Optional @ParamName("pierce") Boolean pierce);
/**
* Returns node id at given location. Depending on whether DOM domain is enabled, nodeId is either
* returned or not.
*
* @param x X coordinate.
* @param y Y coordinate.
*/
NodeForLocation getNodeForLocation(@ParamName("x") Integer x, @ParamName("y") Integer y);
/**
* Returns node id at given location. Depending on whether DOM domain is enabled, nodeId is either
* returned or not.
*
* @param x X coordinate.
* @param y Y coordinate.
* @param includeUserAgentShadowDOM False to skip to the nearest non-UA shadow root ancestor
* (default: false).
* @param ignorePointerEventsNone Whether to ignore pointer-events: none on elements and hit test
* them.
*/
NodeForLocation getNodeForLocation(
@ParamName("x") Integer x,
@ParamName("y") Integer y,
@Optional @ParamName("includeUserAgentShadowDOM") Boolean includeUserAgentShadowDOM,
@Optional @ParamName("ignorePointerEventsNone") Boolean ignorePointerEventsNone);
/** Returns node's HTML markup. */
@Returns("outerHTML")
String getOuterHTML();
/**
* Returns node's HTML markup.
*
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
*/
@Returns("outerHTML")
String getOuterHTML(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Returns the id of the nearest ancestor that is a relayout boundary.
*
* @param nodeId Id of the node.
*/
@Experimental
@Returns("nodeId")
Integer getRelayoutBoundary(@ParamName("nodeId") Integer nodeId);
/**
* Returns search results from given `fromIndex` to given `toIndex` from the search with the given
* identifier.
*
* @param searchId Unique search session identifier.
* @param fromIndex Start index of the search result to be returned.
* @param toIndex End index of the search result to be returned.
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> getSearchResults(
@ParamName("searchId") String searchId,
@ParamName("fromIndex") Integer fromIndex,
@ParamName("toIndex") Integer toIndex);
/** Marks last undoable state. */
@Experimental
void markUndoableState();
/**
* Moves node into the new container, places it before the given anchor.
*
* @param nodeId Id of the node to move.
* @param targetNodeId Id of the element to drop the moved node into.
*/
@Returns("nodeId")
Integer moveTo(
@ParamName("nodeId") Integer nodeId, @ParamName("targetNodeId") Integer targetNodeId);
/**
* Moves node into the new container, places it before the given anchor.
*
* @param nodeId Id of the node to move.
* @param targetNodeId Id of the element to drop the moved node into.
* @param insertBeforeNodeId Drop node before this one (if absent, the moved node becomes the last
* child of `targetNodeId`).
*/
@Returns("nodeId")
Integer moveTo(
@ParamName("nodeId") Integer nodeId,
@ParamName("targetNodeId") Integer targetNodeId,
@Optional @ParamName("insertBeforeNodeId") Integer insertBeforeNodeId);
/**
* Searches for a given string in the DOM tree. Use `getSearchResults` to access search results or
* `cancelSearch` to end this search session.
*
* @param query Plain text or query selector or XPath search query.
*/
@Experimental
PerformSearch performSearch(@ParamName("query") String query);
/**
* Searches for a given string in the DOM tree. Use `getSearchResults` to access search results or
* `cancelSearch` to end this search session.
*
* @param query Plain text or query selector or XPath search query.
* @param includeUserAgentShadowDOM True to search in user agent shadow DOM.
*/
@Experimental
PerformSearch performSearch(
@ParamName("query") String query,
@Optional @ParamName("includeUserAgentShadowDOM") Boolean includeUserAgentShadowDOM);
/**
* Requests that the node is sent to the caller given its path. // FIXME, use XPath
*
* @param path Path to node in the proprietary format.
*/
@Experimental
@Returns("nodeId")
Integer pushNodeByPathToFrontend(@ParamName("path") String path);
/**
* Requests that a batch of nodes is sent to the caller given their backend node ids.
*
* @param backendNodeIds The array of backend node ids.
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> pushNodesByBackendIdsToFrontend(
@ParamName("backendNodeIds") List<Integer> backendNodeIds);
/**
* Executes `querySelector` on a given node.
*
* @param nodeId Id of the node to query upon.
* @param selector Selector string.
*/
@Returns("nodeId")
Integer querySelector(
@ParamName("nodeId") Integer nodeId, @ParamName("selector") String selector);
/**
* Executes `querySelectorAll` on a given node.
*
* @param nodeId Id of the node to query upon.
* @param selector Selector string.
*/
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> querySelectorAll(
@ParamName("nodeId") Integer nodeId, @ParamName("selector") String selector);
/**
* Returns NodeIds of current top layer elements. Top layer is rendered closest to the user within
* a viewport, therefore its elements always appear on top of all other content.
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> getTopLayerElements();
/** Re-does the last undone action. */
@Experimental
void redo();
/**
* Removes attribute with given name from an element with given id.
*
* @param nodeId Id of the element to remove attribute from.
* @param name Name of the attribute to remove.
*/
void removeAttribute(@ParamName("nodeId") Integer nodeId, @ParamName("name") String name);
/**
* Removes node with given id.
*
* @param nodeId Id of the node to remove.
*/
void removeNode(@ParamName("nodeId") Integer nodeId);
/**
* Requests that children of the node with given id are returned to the caller in form of
* `setChildNodes` events where not only immediate children are retrieved, but all children down
* to the specified depth.
*
* @param nodeId Id of the node to get children for.
*/
void requestChildNodes(@ParamName("nodeId") Integer nodeId);
/**
* Requests that children of the node with given id are returned to the caller in form of
* `setChildNodes` events where not only immediate children are retrieved, but all children down
* to the specified depth.
*
* @param nodeId Id of the node to get children for.
* @param depth The maximum depth at which children should be retrieved, defaults to 1. Use -1 for
* the entire subtree or provide an integer larger than 0.
* @param pierce Whether or not iframes and shadow roots should be traversed when returning the
* sub-tree (default is false).
*/
void requestChildNodes(
@ParamName("nodeId") Integer nodeId,
@Optional @ParamName("depth") Integer depth,
@Optional @ParamName("pierce") Boolean pierce);
/**
* Requests that the node is sent to the caller given the JavaScript node object reference. All
* nodes that form the path from the node to the root are also sent to the client as a series of
* `setChildNodes` notifications.
*
* @param objectId JavaScript object id to convert into node.
*/
@Returns("nodeId")
Integer requestNode(@ParamName("objectId") String objectId);
/** Resolves the JavaScript node object for a given NodeId or BackendNodeId. */
@Returns("object")
RemoteObject resolveNode();
/**
* Resolves the JavaScript node object for a given NodeId or BackendNodeId.
*
* @param nodeId Id of the node to resolve.
* @param backendNodeId Backend identifier of the node to resolve.
* @param objectGroup Symbolic group name that can be used to release multiple objects.
* @param executionContextId Execution context in which to resolve the node.
*/
@Returns("object")
RemoteObject resolveNode(
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectGroup") String objectGroup,
@Optional @ParamName("executionContextId") Integer executionContextId);
/**
* Sets attribute for an element with given id.
*
* @param nodeId Id of the element to set attribute for.
* @param name Attribute name.
* @param value Attribute value.
*/
void setAttributeValue(
@ParamName("nodeId") Integer nodeId,
@ParamName("name") String name,
@ParamName("value") String value);
/**
* Sets attributes on element with given id. This method is useful when user edits some existing
* attribute value and types in several attribute name/value pairs.
*
* @param nodeId Id of the element to set attributes for.
* @param text Text with a number of attributes. Will parse this text using HTML parser.
*/
void setAttributesAsText(@ParamName("nodeId") Integer nodeId, @ParamName("text") String text);
/**
* Sets attributes on element with given id. This method is useful when user edits some existing
* attribute value and types in several attribute name/value pairs.
*
* @param nodeId Id of the element to set attributes for.
* @param text Text with a number of attributes. Will parse this text using HTML parser.
* @param name Attribute name to replace with new attributes derived from text in case text parsed
* successfully.
*/
void setAttributesAsText(
@ParamName("nodeId") Integer nodeId,
@ParamName("text") String text,
@Optional @ParamName("name") String name);
/**
* Sets files for the given file input element.
*
* @param files Array of file paths to set.
*/
void setFileInputFiles(@ParamName("files") List<String> files);
/**
* Sets files for the given file input element.
*
* @param files Array of file paths to set.
* @param nodeId Identifier of the node.
* @param backendNodeId Identifier of the backend node.
* @param objectId JavaScript object id of the node wrapper.
*/
void setFileInputFiles(
@ParamName("files") List<String> files,
@Optional @ParamName("nodeId") Integer nodeId,
@Optional @ParamName("backendNodeId") Integer backendNodeId,
@Optional @ParamName("objectId") String objectId);
/**
* Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is
* disabled.
*
* @param enable Enable or disable.
*/
@Experimental
void setNodeStackTracesEnabled(@ParamName("enable") Boolean enable);
/**
* Gets stack traces associated with a Node. As of now, only provides stack trace for Node
* creation.
*
* @param nodeId Id of the node to get stack traces for.
*/
@Experimental
@Returns("creation")
StackTrace getNodeStackTraces(@ParamName("nodeId") Integer nodeId);
/**
* Returns file information for the given File wrapper.
*
* @param objectId JavaScript object id of the node wrapper.
*/
@Experimental
@Returns("path")
String getFileInfo(@ParamName("objectId") String objectId);
/**
* Enables console to refer to the node with given id via $x (see Command Line API for more
* details $x functions).
*
* @param nodeId DOM node id to be accessible by means of $x command line API.
*/
@Experimental
void setInspectedNode(@ParamName("nodeId") Integer nodeId);
/**
* Sets node name for a node with given id.
*
* @param nodeId Id of the node to set name for.
* @param name New node's name.
*/
@Returns("nodeId")
Integer setNodeName(@ParamName("nodeId") Integer nodeId, @ParamName("name") String name);
/**
* Sets node value for a node with given id.
*
* @param nodeId Id of the node to set value for.
* @param value New node's value.
*/
void setNodeValue(@ParamName("nodeId") Integer nodeId, @ParamName("value") String value);
/**
* Sets node HTML markup, returns new node id.
*
* @param nodeId Id of the node to set markup for.
* @param outerHTML Outer HTML markup to set.
*/
void setOuterHTML(@ParamName("nodeId") Integer nodeId, @ParamName("outerHTML") String outerHTML);
/** Undoes the last performed action. */
@Experimental
void undo();
/**
* Returns iframe node that owns iframe with the given domain.
*
* @param frameId
*/
@Experimental
FrameOwner getFrameOwner(@ParamName("frameId") String frameId);
/**
* Returns the query container of the given node based on container query conditions:
* containerName, physical, and logical axes. If no axes are provided, the style container is
* returned, which is the direct parent or the closest element with a matching container-name.
*
* @param nodeId
*/
@Experimental
@Returns("nodeId")
Integer getContainerForNode(@ParamName("nodeId") Integer nodeId);
/**
* Returns the query container of the given node based on container query conditions:
* containerName, physical, and logical axes. If no axes are provided, the style container is
* returned, which is the direct parent or the closest element with a matching container-name.
*
* @param nodeId
* @param containerName
* @param physicalAxes
* @param logicalAxes
*/
@Experimental
@Returns("nodeId")
Integer getContainerForNode(
@ParamName("nodeId") Integer nodeId,
@Optional @ParamName("containerName") String containerName,
@Optional @ParamName("physicalAxes") PhysicalAxes physicalAxes,
@Optional @ParamName("logicalAxes") LogicalAxes logicalAxes);
/**
* Returns the descendants of a container query container that have container queries against this
* container.
*
* @param nodeId Id of the container node to find querying descendants from.
*/
@Experimental
@Returns("nodeIds")
@ReturnTypeParameter(Integer.class)
List<Integer> getQueryingDescendantsForContainer(@ParamName("nodeId") Integer nodeId);
/** Fired when `Element`'s attribute is modified. */
@EventName("attributeModified")
EventListener onAttributeModified(EventHandler<AttributeModified> eventListener);
/** Fired when `Element`'s attribute is removed. */
@EventName("attributeRemoved")
EventListener onAttributeRemoved(EventHandler<AttributeRemoved> eventListener);
/** Mirrors `DOMCharacterDataModified` event. */
@EventName("characterDataModified")
EventListener onCharacterDataModified(EventHandler<CharacterDataModified> eventListener);
/** Fired when `Container`'s child node count has changed. */
@EventName("childNodeCountUpdated")
EventListener onChildNodeCountUpdated(EventHandler<ChildNodeCountUpdated> eventListener);
/** Mirrors `DOMNodeInserted` event. */
@EventName("childNodeInserted")
EventListener onChildNodeInserted(EventHandler<ChildNodeInserted> eventListener);
/** Mirrors `DOMNodeRemoved` event. */
@EventName("childNodeRemoved")
EventListener onChildNodeRemoved(EventHandler<ChildNodeRemoved> eventListener);
/** Called when distribution is changed. */
@EventName("distributedNodesUpdated")
@Experimental
EventListener onDistributedNodesUpdated(EventHandler<DistributedNodesUpdated> eventListener);
/** Fired when `Document` has been totally updated. Node ids are no longer valid. */
@EventName("documentUpdated")
EventListener onDocumentUpdated(EventHandler<DocumentUpdated> eventListener);
/** Fired when `Element`'s inline style is modified via a CSS property modification. */
@EventName("inlineStyleInvalidated")
@Experimental
EventListener onInlineStyleInvalidated(EventHandler<InlineStyleInvalidated> eventListener);
/** Called when a pseudo element is added to an element. */
@EventName("pseudoElementAdded")
@Experimental
EventListener onPseudoElementAdded(EventHandler<PseudoElementAdded> eventListener);
/** Called when top layer elements are changed. */
@EventName("topLayerElementsUpdated")
@Experimental
EventListener onTopLayerElementsUpdated(EventHandler<TopLayerElementsUpdated> eventListener);
/** Called when a pseudo element is removed from an element. */
@EventName("pseudoElementRemoved")
@Experimental
EventListener onPseudoElementRemoved(EventHandler<PseudoElementRemoved> eventListener);
/**
* Fired when backend wants to provide client with the missing DOM structure. This happens upon
* most of the calls requesting node ids.
*/
@EventName("setChildNodes")
EventListener onSetChildNodes(EventHandler<SetChildNodes> eventListener);
/** Called when shadow root is popped from the element. */
@EventName("shadowRootPopped")
@Experimental
EventListener onShadowRootPopped(EventHandler<ShadowRootPopped> eventListener);
/** Called when shadow root is pushed into the element. */
@EventName("shadowRootPushed")
@Experimental
EventListener onShadowRootPushed(EventHandler<ShadowRootPushed> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DOMDebugger.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.*;
import com.github.kklisura.cdt.protocol.v2023.types.domdebugger.CSPViolationType;
import com.github.kklisura.cdt.protocol.v2023.types.domdebugger.DOMBreakpointType;
import com.github.kklisura.cdt.protocol.v2023.types.domdebugger.EventListener;
import java.util.List;
/**
* DOM debugging allows setting breakpoints on particular DOM operations and events. JavaScript
* execution will stop on these operations as if there was a regular breakpoint set.
*/
public interface DOMDebugger {
/**
* Returns event listeners of the given object.
*
* @param objectId Identifier of the object to return listeners for.
*/
@Returns("listeners")
@ReturnTypeParameter(EventListener.class)
List<EventListener> getEventListeners(@ParamName("objectId") String objectId);
/**
* Returns event listeners of the given object.
*
* @param objectId Identifier of the object to return listeners for.
* @param depth The maximum depth at which Node children should be retrieved, defaults to 1. Use
* -1 for the entire subtree or provide an integer larger than 0.
* @param pierce Whether or not iframes and shadow roots should be traversed when returning the
* subtree (default is false). Reports listeners for all contexts if pierce is enabled.
*/
@Returns("listeners")
@ReturnTypeParameter(EventListener.class)
List<EventListener> getEventListeners(
@ParamName("objectId") String objectId,
@Optional @ParamName("depth") Integer depth,
@Optional @ParamName("pierce") Boolean pierce);
/**
* Removes DOM breakpoint that was set using `setDOMBreakpoint`.
*
* @param nodeId Identifier of the node to remove breakpoint from.
* @param type Type of the breakpoint to remove.
*/
void removeDOMBreakpoint(
@ParamName("nodeId") Integer nodeId, @ParamName("type") DOMBreakpointType type);
/**
* Removes breakpoint on particular DOM event.
*
* @param eventName Event name.
*/
void removeEventListenerBreakpoint(@ParamName("eventName") String eventName);
/**
* Removes breakpoint on particular DOM event.
*
* @param eventName Event name.
* @param targetName EventTarget interface name.
*/
void removeEventListenerBreakpoint(
@ParamName("eventName") String eventName,
@Experimental @Optional @ParamName("targetName") String targetName);
/**
* Removes breakpoint on particular native event.
*
* @param eventName Instrumentation name to stop on.
*/
@Experimental
void removeInstrumentationBreakpoint(@ParamName("eventName") String eventName);
/**
* Removes breakpoint from XMLHttpRequest.
*
* @param url Resource URL substring.
*/
void removeXHRBreakpoint(@ParamName("url") String url);
/**
* Sets breakpoint on particular CSP violations.
*
* @param violationTypes CSP Violations to stop upon.
*/
@Experimental
void setBreakOnCSPViolation(@ParamName("violationTypes") List<CSPViolationType> violationTypes);
/**
* Sets breakpoint on particular operation with DOM.
*
* @param nodeId Identifier of the node to set breakpoint on.
* @param type Type of the operation to stop upon.
*/
void setDOMBreakpoint(
@ParamName("nodeId") Integer nodeId, @ParamName("type") DOMBreakpointType type);
/**
* Sets breakpoint on particular DOM event.
*
* @param eventName DOM Event name to stop on (any DOM event will do).
*/
void setEventListenerBreakpoint(@ParamName("eventName") String eventName);
/**
* Sets breakpoint on particular DOM event.
*
* @param eventName DOM Event name to stop on (any DOM event will do).
* @param targetName EventTarget interface name to stop on. If equal to `"*"` or not provided,
* will stop on any EventTarget.
*/
void setEventListenerBreakpoint(
@ParamName("eventName") String eventName,
@Experimental @Optional @ParamName("targetName") String targetName);
/**
* Sets breakpoint on particular native event.
*
* @param eventName Instrumentation name to stop on.
*/
@Experimental
void setInstrumentationBreakpoint(@ParamName("eventName") String eventName);
/**
* Sets breakpoint on XMLHttpRequest.
*
* @param url Resource URL substring. All XHRs having this substring in the URL will get stopped
* upon.
*/
void setXHRBreakpoint(@ParamName("url") String url);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DOMSnapshot.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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 com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.types.domsnapshot.CaptureSnapshot;
import com.github.kklisura.cdt.protocol.v2023.types.domsnapshot.Snapshot;
import java.util.List;
/** This domain facilitates obtaining document snapshots with DOM, layout, and style information. */
@Experimental
public interface DOMSnapshot {
/** Disables DOM snapshot agent for the given page. */
void disable();
/** Enables DOM snapshot agent for the given page. */
void enable();
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
* template contents, and imported documents) in a flattened array, as well as layout and
* white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
* flattened.
*
* @param computedStyleWhitelist Whitelist of computed styles to return.
*/
@Deprecated
Snapshot getSnapshot(@ParamName("computedStyleWhitelist") List<String> computedStyleWhitelist);
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
* template contents, and imported documents) in a flattened array, as well as layout and
* white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
* flattened.
*
* @param computedStyleWhitelist Whitelist of computed styles to return.
* @param includeEventListeners Whether or not to retrieve details of DOM listeners (default
* false).
* @param includePaintOrder Whether to determine and include the paint order index of
* LayoutTreeNodes (default false).
* @param includeUserAgentShadowTree Whether to include UA shadow tree in the snapshot (default
* false).
*/
@Deprecated
Snapshot getSnapshot(
@ParamName("computedStyleWhitelist") List<String> computedStyleWhitelist,
@Optional @ParamName("includeEventListeners") Boolean includeEventListeners,
@Optional @ParamName("includePaintOrder") Boolean includePaintOrder,
@Optional @ParamName("includeUserAgentShadowTree") Boolean includeUserAgentShadowTree);
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
* template contents, and imported documents) in a flattened array, as well as layout and
* white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
* flattened.
*
* @param computedStyles Whitelist of computed styles to return.
*/
CaptureSnapshot captureSnapshot(@ParamName("computedStyles") List<String> computedStyles);
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
* template contents, and imported documents) in a flattened array, as well as layout and
* white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
* flattened.
*
* @param computedStyles Whitelist of computed styles to return.
* @param includePaintOrder Whether to include layout object paint orders into the snapshot.
* @param includeDOMRects Whether to include DOM rectangles (offsetRects, clientRects,
* scrollRects) into the snapshot
* @param includeBlendedBackgroundColors Whether to include blended background colors in the
* snapshot (default: false). Blended background color is achieved by blending background
* colors of all elements that overlap with the current element.
* @param includeTextColorOpacities Whether to include text color opacity in the snapshot
* (default: false). An element might have the opacity property set that affects the text
* color of the element. The final text color opacity is computed based on the opacity of all
* overlapping elements.
*/
CaptureSnapshot captureSnapshot(
@ParamName("computedStyles") List<String> computedStyles,
@Optional @ParamName("includePaintOrder") Boolean includePaintOrder,
@Optional @ParamName("includeDOMRects") Boolean includeDOMRects,
@Experimental @Optional @ParamName("includeBlendedBackgroundColors")
Boolean includeBlendedBackgroundColors,
@Experimental @Optional @ParamName("includeTextColorOpacities")
Boolean includeTextColorOpacities);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DOMStorage.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.domstorage.DomStorageItemAdded;
import com.github.kklisura.cdt.protocol.v2023.events.domstorage.DomStorageItemRemoved;
import com.github.kklisura.cdt.protocol.v2023.events.domstorage.DomStorageItemUpdated;
import com.github.kklisura.cdt.protocol.v2023.events.domstorage.DomStorageItemsCleared;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.domstorage.StorageId;
import java.util.List;
/** Query and modify DOM storage. */
@Experimental
public interface DOMStorage {
/** @param storageId */
void clear(@ParamName("storageId") StorageId storageId);
/** Disables storage tracking, prevents storage events from being sent to the client. */
void disable();
/** Enables storage tracking, storage events will now be delivered to the client. */
void enable();
/** @param storageId */
@Returns("entries")
@ReturnTypeParameter({List.class, String.class})
List<List<String>> getDOMStorageItems(@ParamName("storageId") StorageId storageId);
/**
* @param storageId
* @param key
*/
void removeDOMStorageItem(
@ParamName("storageId") StorageId storageId, @ParamName("key") String key);
/**
* @param storageId
* @param key
* @param value
*/
void setDOMStorageItem(
@ParamName("storageId") StorageId storageId,
@ParamName("key") String key,
@ParamName("value") String value);
@EventName("domStorageItemAdded")
EventListener onDomStorageItemAdded(EventHandler<DomStorageItemAdded> eventListener);
@EventName("domStorageItemRemoved")
EventListener onDomStorageItemRemoved(EventHandler<DomStorageItemRemoved> eventListener);
@EventName("domStorageItemUpdated")
EventListener onDomStorageItemUpdated(EventHandler<DomStorageItemUpdated> eventListener);
@EventName("domStorageItemsCleared")
EventListener onDomStorageItemsCleared(EventHandler<DomStorageItemsCleared> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Database.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.database.AddDatabase;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.database.ExecuteSQL;
import java.util.List;
@Experimental
public interface Database {
/** Disables database tracking, prevents database events from being sent to the client. */
void disable();
/** Enables database tracking, database events will now be delivered to the client. */
void enable();
/**
* @param databaseId
* @param query
*/
ExecuteSQL executeSQL(
@ParamName("databaseId") String databaseId, @ParamName("query") String query);
/** @param databaseId */
@Returns("tableNames")
@ReturnTypeParameter(String.class)
List<String> getDatabaseTableNames(@ParamName("databaseId") String databaseId);
@EventName("addDatabase")
EventListener onAddDatabase(EventHandler<AddDatabase> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Debugger.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.debugger.*;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.debugger.*;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.CallArgument;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.StackTrace;
import com.github.kklisura.cdt.protocol.v2023.types.runtime.StackTraceId;
import java.util.List;
/**
* Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing
* breakpoints, stepping through execution, exploring stack traces, etc.
*/
public interface Debugger {
/**
* Continues execution until specific location is reached.
*
* @param location Location to continue to.
*/
void continueToLocation(@ParamName("location") Location location);
/**
* Continues execution until specific location is reached.
*
* @param location Location to continue to.
* @param targetCallFrames
*/
void continueToLocation(
@ParamName("location") Location location,
@Optional @ParamName("targetCallFrames") ContinueToLocationTargetCallFrames targetCallFrames);
/** Disables debugger for given page. */
void disable();
/**
* Enables debugger for the given page. Clients should not assume that the debugging has been
* enabled until the result for this command is received.
*/
@Returns("debuggerId")
String enable();
/**
* Enables debugger for the given page. Clients should not assume that the debugging has been
* enabled until the result for this command is received.
*
* @param maxScriptsCacheSize The maximum size in bytes of collected scripts (not referenced by
* other heap objects) the debugger can hold. Puts no limit if parameter is omitted.
*/
@Returns("debuggerId")
String enable(
@Experimental @Optional @ParamName("maxScriptsCacheSize") Double maxScriptsCacheSize);
/**
* Evaluates expression on a given call frame.
*
* @param callFrameId Call frame identifier to evaluate on.
* @param expression Expression to evaluate.
*/
EvaluateOnCallFrame evaluateOnCallFrame(
@ParamName("callFrameId") String callFrameId, @ParamName("expression") String expression);
/**
* Evaluates expression on a given call frame.
*
* @param callFrameId Call frame identifier to evaluate on.
* @param expression Expression to evaluate.
* @param objectGroup String object group name to put result into (allows rapid releasing
* resulting object handles using `releaseObjectGroup`).
* @param includeCommandLineAPI Specifies whether command line API should be available to the
* evaluated expression, defaults to false.
* @param silent In silent mode exceptions thrown during evaluation are not reported and do not
* pause execution. Overrides `setPauseOnException` state.
* @param returnByValue Whether the result is expected to be a JSON object that should be sent by
* value.
* @param generatePreview Whether preview should be generated for the result.
* @param throwOnSideEffect Whether to throw an exception if side effect cannot be ruled out
* during evaluation.
* @param timeout Terminate execution after timing out (number of milliseconds).
*/
EvaluateOnCallFrame evaluateOnCallFrame(
@ParamName("callFrameId") String callFrameId,
@ParamName("expression") String expression,
@Optional @ParamName("objectGroup") String objectGroup,
@Optional @ParamName("includeCommandLineAPI") Boolean includeCommandLineAPI,
@Optional @ParamName("silent") Boolean silent,
@Optional @ParamName("returnByValue") Boolean returnByValue,
@Experimental @Optional @ParamName("generatePreview") Boolean generatePreview,
@Optional @ParamName("throwOnSideEffect") Boolean throwOnSideEffect,
@Experimental @Optional @ParamName("timeout") Double timeout);
/**
* Returns possible locations for breakpoint. scriptId in start and end range locations should be
* the same.
*
* @param start Start of range to search possible breakpoint locations in.
*/
@Returns("locations")
@ReturnTypeParameter(BreakLocation.class)
List<BreakLocation> getPossibleBreakpoints(@ParamName("start") Location start);
/**
* Returns possible locations for breakpoint. scriptId in start and end range locations should be
* the same.
*
* @param start Start of range to search possible breakpoint locations in.
* @param end End of range to search possible breakpoint locations in (excluding). When not
* specified, end of scripts is used as end of range.
* @param restrictToFunction Only consider locations which are in the same (non-nested) function
* as start.
*/
@Returns("locations")
@ReturnTypeParameter(BreakLocation.class)
List<BreakLocation> getPossibleBreakpoints(
@ParamName("start") Location start,
@Optional @ParamName("end") Location end,
@Optional @ParamName("restrictToFunction") Boolean restrictToFunction);
/**
* Returns source for the script with given id.
*
* @param scriptId Id of the script to get source for.
*/
ScriptSource getScriptSource(@ParamName("scriptId") String scriptId);
/** @param scriptId Id of the script to disassemble */
@Experimental
DisassembleWasmModule disassembleWasmModule(@ParamName("scriptId") String scriptId);
/**
* Disassemble the next chunk of lines for the module corresponding to the stream. If disassembly
* is complete, this API will invalidate the streamId and return an empty chunk. Any subsequent
* calls for the now invalid stream will return errors.
*
* @param streamId
*/
@Experimental
@Returns("chunk")
WasmDisassemblyChunk nextWasmDisassemblyChunk(@ParamName("streamId") String streamId);
/**
* This command is deprecated. Use getScriptSource instead.
*
* @param scriptId Id of the Wasm script to get source for.
*/
@Deprecated
@Returns("bytecode")
String getWasmBytecode(@ParamName("scriptId") String scriptId);
/**
* Returns stack trace with given `stackTraceId`.
*
* @param stackTraceId
*/
@Experimental
@Returns("stackTrace")
StackTrace getStackTrace(@ParamName("stackTraceId") StackTraceId stackTraceId);
/** Stops on the next JavaScript statement. */
void pause();
/**
* @param parentStackTraceId Debugger will pause when async call with given stack trace is
* started.
*/
@Deprecated
@Experimental
void pauseOnAsyncCall(@ParamName("parentStackTraceId") StackTraceId parentStackTraceId);
/**
* Removes JavaScript breakpoint.
*
* @param breakpointId
*/
void removeBreakpoint(@ParamName("breakpointId") String breakpointId);
/**
* Restarts particular call frame from the beginning. The old, deprecated behavior of
* `restartFrame` is to stay paused and allow further CDP commands after a restart was scheduled.
* This can cause problems with restarting, so we now continue execution immediatly after it has
* been scheduled until we reach the beginning of the restarted frame.
*
* <p>To stay back-wards compatible, `restartFrame` now expects a `mode` parameter to be present.
* If the `mode` parameter is missing, `restartFrame` errors out.
*
* <p>The various return values are deprecated and `callFrames` is always empty. Use the call
* frames from the `Debugger#paused` events instead, that fires once V8 pauses at the beginning of
* the restarted function.
*
* @param callFrameId Call frame identifier to evaluate on.
*/
RestartFrame restartFrame(@ParamName("callFrameId") String callFrameId);
/**
* Restarts particular call frame from the beginning. The old, deprecated behavior of
* `restartFrame` is to stay paused and allow further CDP commands after a restart was scheduled.
* This can cause problems with restarting, so we now continue execution immediatly after it has
* been scheduled until we reach the beginning of the restarted frame.
*
* <p>To stay back-wards compatible, `restartFrame` now expects a `mode` parameter to be present.
* If the `mode` parameter is missing, `restartFrame` errors out.
*
* <p>The various return values are deprecated and `callFrames` is always empty. Use the call
* frames from the `Debugger#paused` events instead, that fires once V8 pauses at the beginning of
* the restarted function.
*
* @param callFrameId Call frame identifier to evaluate on.
* @param mode The `mode` parameter must be present and set to 'StepInto', otherwise
* `restartFrame` will error out.
*/
RestartFrame restartFrame(
@ParamName("callFrameId") String callFrameId,
@Experimental @Optional @ParamName("mode") RestartFrameMode mode);
/** Resumes JavaScript execution. */
void resume();
/**
* Resumes JavaScript execution.
*
* @param terminateOnResume Set to true to terminate execution upon resuming execution. In
* contrast to Runtime.terminateExecution, this will allows to execute further JavaScript
* (i.e. via evaluation) until execution of the paused code is actually resumed, at which
* point termination is triggered. If execution is currently not paused, this parameter has no
* effect.
*/
void resume(@Optional @ParamName("terminateOnResume") Boolean terminateOnResume);
/**
* Searches for given string in script content.
*
* @param scriptId Id of the script to search in.
* @param query String to search for.
*/
@Returns("result")
@ReturnTypeParameter(SearchMatch.class)
List<SearchMatch> searchInContent(
@ParamName("scriptId") String scriptId, @ParamName("query") String query);
/**
* Searches for given string in script content.
*
* @param scriptId Id of the script to search in.
* @param query String to search for.
* @param caseSensitive If true, search is case sensitive.
* @param isRegex If true, treats string parameter as regex.
*/
@Returns("result")
@ReturnTypeParameter(SearchMatch.class)
List<SearchMatch> searchInContent(
@ParamName("scriptId") String scriptId,
@ParamName("query") String query,
@Optional @ParamName("caseSensitive") Boolean caseSensitive,
@Optional @ParamName("isRegex") Boolean isRegex);
/**
* Enables or disables async call stacks tracking.
*
* @param maxDepth Maximum depth of async call stacks. Setting to `0` will effectively disable
* collecting async call stacks (default).
*/
void setAsyncCallStackDepth(@ParamName("maxDepth") Integer maxDepth);
/**
* Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in
* scripts with url matching one of the patterns. VM will try to leave blackboxed script by
* performing 'step in' several times, finally resorting to 'step out' if unsuccessful.
*
* @param patterns Array of regexps that will be used to check script url for blackbox state.
*/
@Experimental
void setBlackboxPatterns(@ParamName("patterns") List<String> patterns);
/**
* Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted
* scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful.
* Positions array contains positions where blackbox state is changed. First interval isn't
* blackboxed. Array should be sorted.
*
* @param scriptId Id of the script.
* @param positions
*/
@Experimental
void setBlackboxedRanges(
@ParamName("scriptId") String scriptId,
@ParamName("positions") List<ScriptPosition> positions);
/**
* Sets JavaScript breakpoint at a given location.
*
* @param location Location to set breakpoint in.
*/
SetBreakpoint setBreakpoint(@ParamName("location") Location location);
/**
* Sets JavaScript breakpoint at a given location.
*
* @param location Location to set breakpoint in.
* @param condition Expression to use as a breakpoint condition. When specified, debugger will
* only stop on the breakpoint if this expression evaluates to true.
*/
SetBreakpoint setBreakpoint(
@ParamName("location") Location location, @Optional @ParamName("condition") String condition);
/**
* Sets instrumentation breakpoint.
*
* @param instrumentation Instrumentation name.
*/
@Returns("breakpointId")
String setInstrumentationBreakpoint(
@ParamName("instrumentation") SetInstrumentationBreakpointInstrumentation instrumentation);
/**
* Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this
* command is issued, all existing parsed scripts will have breakpoints resolved and returned in
* `locations` property. Further matching script parsing will result in subsequent
* `breakpointResolved` events issued. This logical breakpoint will survive page reloads.
*
* @param lineNumber Line number to set breakpoint at.
*/
SetBreakpointByUrl setBreakpointByUrl(@ParamName("lineNumber") Integer lineNumber);
/**
* Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this
* command is issued, all existing parsed scripts will have breakpoints resolved and returned in
* `locations` property. Further matching script parsing will result in subsequent
* `breakpointResolved` events issued. This logical breakpoint will survive page reloads.
*
* @param lineNumber Line number to set breakpoint at.
* @param url URL of the resources to set breakpoint on.
* @param urlRegex Regex pattern for the URLs of the resources to set breakpoints on. Either `url`
* or `urlRegex` must be specified.
* @param scriptHash Script hash of the resources to set breakpoint on.
* @param columnNumber Offset in the line to set breakpoint at.
* @param condition Expression to use as a breakpoint condition. When specified, debugger will
* only stop on the breakpoint if this expression evaluates to true.
*/
SetBreakpointByUrl setBreakpointByUrl(
@ParamName("lineNumber") Integer lineNumber,
@Optional @ParamName("url") String url,
@Optional @ParamName("urlRegex") String urlRegex,
@Optional @ParamName("scriptHash") String scriptHash,
@Optional @ParamName("columnNumber") Integer columnNumber,
@Optional @ParamName("condition") String condition);
/**
* Sets JavaScript breakpoint before each call to the given function. If another function was
* created from the same source as a given one, calling it will also trigger the breakpoint.
*
* @param objectId Function object id.
*/
@Experimental
@Returns("breakpointId")
String setBreakpointOnFunctionCall(@ParamName("objectId") String objectId);
/**
* Sets JavaScript breakpoint before each call to the given function. If another function was
* created from the same source as a given one, calling it will also trigger the breakpoint.
*
* @param objectId Function object id.
* @param condition Expression to use as a breakpoint condition. When specified, debugger will
* stop on the breakpoint if this expression evaluates to true.
*/
@Experimental
@Returns("breakpointId")
String setBreakpointOnFunctionCall(
@ParamName("objectId") String objectId, @Optional @ParamName("condition") String condition);
/**
* Activates / deactivates all breakpoints on the page.
*
* @param active New value for breakpoints active state.
*/
void setBreakpointsActive(@ParamName("active") Boolean active);
/**
* Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions,
* or caught exceptions, no exceptions. Initial pause on exceptions state is `none`.
*
* @param state Pause on exceptions mode.
*/
void setPauseOnExceptions(@ParamName("state") SetPauseOnExceptionsState state);
/**
* Changes return value in top frame. Available only at return break position.
*
* @param newValue New return value.
*/
@Experimental
void setReturnValue(@ParamName("newValue") CallArgument newValue);
/**
* Edits JavaScript source live.
*
* <p>In general, functions that are currently on the stack can not be edited with a single
* exception: If the edited function is the top-most stack frame and that is the only activation
* of that function on the stack. In this case the live edit will be successful and a
* `Debugger.restartFrame` for the top-most function is automatically triggered.
*
* @param scriptId Id of the script to edit.
* @param scriptSource New content of the script.
*/
SetScriptSource setScriptSource(
@ParamName("scriptId") String scriptId, @ParamName("scriptSource") String scriptSource);
/**
* Edits JavaScript source live.
*
* <p>In general, functions that are currently on the stack can not be edited with a single
* exception: If the edited function is the top-most stack frame and that is the only activation
* of that function on the stack. In this case the live edit will be successful and a
* `Debugger.restartFrame` for the top-most function is automatically triggered.
*
* @param scriptId Id of the script to edit.
* @param scriptSource New content of the script.
* @param dryRun If true the change will not actually be applied. Dry run may be used to get
* result description without actually modifying the code.
* @param allowTopFrameEditing If true, then `scriptSource` is allowed to change the function on
* top of the stack as long as the top-most stack frame is the only activation of that
* function.
*/
SetScriptSource setScriptSource(
@ParamName("scriptId") String scriptId,
@ParamName("scriptSource") String scriptSource,
@Optional @ParamName("dryRun") Boolean dryRun,
@Experimental @Optional @ParamName("allowTopFrameEditing") Boolean allowTopFrameEditing);
/**
* Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc).
*
* @param skip New value for skip pauses state.
*/
void setSkipAllPauses(@ParamName("skip") Boolean skip);
/**
* Changes value of variable in a callframe. Object-based scopes are not supported and must be
* mutated manually.
*
* @param scopeNumber 0-based number of scope as was listed in scope chain. Only 'local',
* 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually.
* @param variableName Variable name.
* @param newValue New variable value.
* @param callFrameId Id of callframe that holds variable.
*/
void setVariableValue(
@ParamName("scopeNumber") Integer scopeNumber,
@ParamName("variableName") String variableName,
@ParamName("newValue") CallArgument newValue,
@ParamName("callFrameId") String callFrameId);
/** Steps into the function call. */
void stepInto();
/**
* Steps into the function call.
*
* @param breakOnAsyncCall Debugger will pause on the execution of the first async task which was
* scheduled before next pause.
* @param skipList The skipList specifies location ranges that should be skipped on step into.
*/
void stepInto(
@Experimental @Optional @ParamName("breakOnAsyncCall") Boolean breakOnAsyncCall,
@Experimental @Optional @ParamName("skipList") List<LocationRange> skipList);
/** Steps out of the function call. */
void stepOut();
/** Steps over the statement. */
void stepOver();
/**
* Steps over the statement.
*
* @param skipList The skipList specifies location ranges that should be skipped on step over.
*/
void stepOver(@Experimental @Optional @ParamName("skipList") List<LocationRange> skipList);
/** Fired when breakpoint is resolved to an actual script and location. */
@EventName("breakpointResolved")
EventListener onBreakpointResolved(EventHandler<BreakpointResolved> eventListener);
/**
* Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria.
*/
@EventName("paused")
EventListener onPaused(EventHandler<Paused> eventListener);
/** Fired when the virtual machine resumed execution. */
@EventName("resumed")
EventListener onResumed(EventHandler<Resumed> eventListener);
/** Fired when virtual machine fails to parse the script. */
@EventName("scriptFailedToParse")
EventListener onScriptFailedToParse(EventHandler<ScriptFailedToParse> eventListener);
/**
* Fired when virtual machine parses script. This event is also fired for all known and
* uncollected scripts upon enabling debugger.
*/
@EventName("scriptParsed")
EventListener onScriptParsed(EventHandler<ScriptParsed> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DeviceAccess.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.deviceaccess.DeviceRequestPrompted;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.EventName;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.Experimental;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.ParamName;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
@Experimental
public interface DeviceAccess {
/** Enable events in this domain. */
void enable();
/** Disable events in this domain. */
void disable();
/**
* Select a device in response to a DeviceAccess.deviceRequestPrompted event.
*
* @param id
* @param deviceId
*/
void selectPrompt(@ParamName("id") String id, @ParamName("deviceId") String deviceId);
/**
* Cancel a prompt in response to a DeviceAccess.deviceRequestPrompted event.
*
* @param id
*/
void cancelPrompt(@ParamName("id") String id);
/**
* A device request opened a user prompt to select a device. Respond with the selectPrompt or
* cancelPrompt command.
*/
@EventName("deviceRequestPrompted")
EventListener onDeviceRequestPrompted(EventHandler<DeviceRequestPrompted> eventListener);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/DeviceOrientation.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.ParamName;
@Experimental
public interface DeviceOrientation {
/** Clears the overridden Device Orientation. */
void clearDeviceOrientationOverride();
/**
* Overrides the Device Orientation.
*
* @param alpha Mock alpha
* @param beta Mock beta
* @param gamma Mock gamma
*/
void setDeviceOrientationOverride(
@ParamName("alpha") Double alpha,
@ParamName("beta") Double beta,
@ParamName("gamma") Double gamma);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023
|
java-sources/ai/platon/pulsar/pulsar-browser/3.0.15/com/github/kklisura/cdt/protocol/v2023/commands/Emulation.java
|
package com.github.kklisura.cdt.protocol.v2023.commands;
/*-
* #%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.events.emulation.VirtualTimeBudgetExpired;
import com.github.kklisura.cdt.protocol.v2023.support.annotations.*;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventHandler;
import com.github.kklisura.cdt.protocol.v2023.support.types.EventListener;
import com.github.kklisura.cdt.protocol.v2023.types.dom.RGBA;
import com.github.kklisura.cdt.protocol.v2023.types.emulation.*;
import com.github.kklisura.cdt.protocol.v2023.types.page.Viewport;
import java.util.List;
/** This domain emulates different environments for the page. */
public interface Emulation {
/** Tells whether emulation is supported. */
@Returns("result")
Boolean canEmulate();
/** Clears the overridden device metrics. */
void clearDeviceMetricsOverride();
/** Clears the overridden Geolocation Position and Error. */
void clearGeolocationOverride();
/** Requests that page scale factor is reset to initial values. */
@Experimental
void resetPageScaleFactor();
/**
* Enables or disables simulating a focused and active page.
*
* @param enabled Whether to enable to disable focus emulation.
*/
@Experimental
void setFocusEmulationEnabled(@ParamName("enabled") Boolean enabled);
/** Automatically render all web contents using a dark theme. */
@Experimental
void setAutoDarkModeOverride();
/**
* Automatically render all web contents using a dark theme.
*
* @param enabled Whether to enable or disable automatic dark mode. If not specified, any existing
* override will be cleared.
*/
@Experimental
void setAutoDarkModeOverride(@Optional @ParamName("enabled") Boolean enabled);
/**
* Enables CPU throttling to emulate slow CPUs.
*
* @param rate Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
*/
@Experimental
void setCPUThrottlingRate(@ParamName("rate") Double rate);
/**
* Sets or clears an override of the default background color of the frame. This override is used
* if the content does not specify one.
*/
void setDefaultBackgroundColorOverride();
/**
* Sets or clears an override of the default background color of the frame. This override is used
* if the content does not specify one.
*
* @param color RGBA of the default background color. If not specified, any existing override will
* be cleared.
*/
void setDefaultBackgroundColorOverride(@Optional @ParamName("color") RGBA color);
/**
* Overrides the values of device screen dimensions (window.screen.width, window.screen.height,
* window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media
* query results).
*
* @param width Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the
* override.
* @param height Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the
* override.
* @param deviceScaleFactor Overriding device scale factor value. 0 disables the override.
* @param mobile Whether to emulate mobile device. This includes viewport meta tag, overlay
* scrollbars, text autosizing and more.
*/
void setDeviceMetricsOverride(
@ParamName("width") Integer width,
@ParamName("height") Integer height,
@ParamName("deviceScaleFactor") Double deviceScaleFactor,
@ParamName("mobile") Boolean mobile);
/**
* Overrides the values of device screen dimensions (window.screen.width, window.screen.height,
* window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media
* query results).
*
* @param width Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the
* override.
* @param height Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the
* override.
* @param deviceScaleFactor Overriding device scale factor value. 0 disables the override.
* @param mobile Whether to emulate mobile device. This includes viewport meta tag, overlay
* scrollbars, text autosizing and more.
* @param scale Scale to apply to resulting view image.
* @param screenWidth Overriding screen width value in pixels (minimum 0, maximum 10000000).
* @param screenHeight Overriding screen height value in pixels (minimum 0, maximum 10000000).
* @param positionX Overriding view X position on screen in pixels (minimum 0, maximum 10000000).
* @param positionY Overriding view Y position on screen in pixels (minimum 0, maximum 10000000).
* @param dontSetVisibleSize Do not set visible view size, rely upon explicit setVisibleSize call.
* @param screenOrientation Screen orientation override.
* @param viewport If set, the visible area of the page will be overridden to this viewport. This
* viewport change is not observed by the page, e.g. viewport-relative elements do not change
* positions.
* @param displayFeature If set, the display feature of a multi-segment screen. If not set,
* multi-segment support is turned-off.
*/
void setDeviceMetricsOverride(
@ParamName("width") Integer width,
@ParamName("height") Integer height,
@ParamName("deviceScaleFactor") Double deviceScaleFactor,
@ParamName("mobile") Boolean mobile,
@Experimental @Optional @ParamName("scale") Double scale,
@Experimental @Optional @ParamName("screenWidth") Integer screenWidth,
@Experimental @Optional @ParamName("screenHeight") Integer screenHeight,
@Experimental @Optional @ParamName("positionX") Integer positionX,
@Experimental @Optional @ParamName("positionY") Integer positionY,
@Experimental @Optional @ParamName("dontSetVisibleSize") Boolean dontSetVisibleSize,
@Optional @ParamName("screenOrientation") ScreenOrientation screenOrientation,
@Experimental @Optional @ParamName("viewport") Viewport viewport,
@Experimental @Optional @ParamName("displayFeature") DisplayFeature displayFeature);
/** @param hidden Whether scrollbars should be always hidden. */
@Experimental
void setScrollbarsHidden(@ParamName("hidden") Boolean hidden);
/** @param disabled Whether document.coookie API should be disabled. */
@Experimental
void setDocumentCookieDisabled(@ParamName("disabled") Boolean disabled);
/** @param enabled Whether touch emulation based on mouse input should be enabled. */
@Experimental
void setEmitTouchEventsForMouse(@ParamName("enabled") Boolean enabled);
/**
* @param enabled Whether touch emulation based on mouse input should be enabled.
* @param configuration Touch/gesture events configuration. Default: current platform.
*/
@Experimental
void setEmitTouchEventsForMouse(
@ParamName("enabled") Boolean enabled,
@Optional @ParamName("configuration") SetEmitTouchEventsForMouseConfiguration configuration);
/** Emulates the given media type or media feature for CSS media queries. */
void setEmulatedMedia();
/**
* Emulates the given media type or media feature for CSS media queries.
*
* @param media Media type to emulate. Empty string disables the override.
* @param features Media features to emulate.
*/
void setEmulatedMedia(
@Optional @ParamName("media") String media,
@Optional @ParamName("features") List<MediaFeature> features);
/**
* Emulates the given vision deficiency.
*
* @param type Vision deficiency to emulate. Order: best-effort emulations come first, followed by
* any physiologically accurate emulations for medically recognized color vision deficiencies.
*/
@Experimental
void setEmulatedVisionDeficiency(@ParamName("type") SetEmulatedVisionDeficiencyType type);
/**
* Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position
* unavailable.
*/
void setGeolocationOverride();
/**
* Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position
* unavailable.
*
* @param latitude Mock latitude
* @param longitude Mock longitude
* @param accuracy Mock accuracy
*/
void setGeolocationOverride(
@Optional @ParamName("latitude") Double latitude,
@Optional @ParamName("longitude") Double longitude,
@Optional @ParamName("accuracy") Double accuracy);
/**
* Overrides the Idle state.
*
* @param isUserActive Mock isUserActive
* @param isScreenUnlocked Mock isScreenUnlocked
*/
@Experimental
void setIdleOverride(
@ParamName("isUserActive") Boolean isUserActive,
@ParamName("isScreenUnlocked") Boolean isScreenUnlocked);
/** Clears Idle state overrides. */
@Experimental
void clearIdleOverride();
/**
* Overrides value returned by the javascript navigator object.
*
* @param platform The platform navigator.platform should return.
*/
@Deprecated
@Experimental
void setNavigatorOverrides(@ParamName("platform") String platform);
/**
* Sets a specified page scale factor.
*
* @param pageScaleFactor Page scale factor.
*/
@Experimental
void setPageScaleFactor(@ParamName("pageScaleFactor") Double pageScaleFactor);
/**
* Switches script execution in the page.
*
* @param value Whether script execution should be disabled in the page.
*/
void setScriptExecutionDisabled(@ParamName("value") Boolean value);
/**
* Enables touch on platforms which do not support them.
*
* @param enabled Whether the touch event emulation should be enabled.
*/
void setTouchEmulationEnabled(@ParamName("enabled") Boolean enabled);
/**
* Enables touch on platforms which do not support them.
*
* @param enabled Whether the touch event emulation should be enabled.
* @param maxTouchPoints Maximum touch points supported. Defaults to one.
*/
void setTouchEmulationEnabled(
@ParamName("enabled") Boolean enabled,
@Optional @ParamName("maxTouchPoints") Integer maxTouchPoints);
/**
* Turns on virtual time for all frames (replacing real-time with a synthetic time source) and
* sets the current virtual time policy. Note this supersedes any previous time budget.
*
* @param policy
*/
@Experimental
@Returns("virtualTimeTicksBase")
Double setVirtualTimePolicy(@ParamName("policy") VirtualTimePolicy policy);
/**
* Turns on virtual time for all frames (replacing real-time with a synthetic time source) and
* sets the current virtual time policy. Note this supersedes any previous time budget.
*
* @param policy
* @param budget If set, after this many virtual milliseconds have elapsed virtual time will be
* paused and a virtualTimeBudgetExpired event is sent.
* @param maxVirtualTimeTaskStarvationCount If set this specifies the maximum number of tasks that
* can be run before virtual is forced forwards to prevent deadlock.
* @param initialVirtualTime If set, base::Time::Now will be overridden to initially return this
* value.
*/
@Experimental
@Returns("virtualTimeTicksBase")
Double setVirtualTimePolicy(
@ParamName("policy") VirtualTimePolicy policy,
@Optional @ParamName("budget") Double budget,
@Optional @ParamName("maxVirtualTimeTaskStarvationCount")
Integer maxVirtualTimeTaskStarvationCount,
@Optional @ParamName("initialVirtualTime") Double initialVirtualTime);
/** Overrides default host system locale with the specified one. */
@Experimental
void setLocaleOverride();
/**
* Overrides default host system locale with the specified one.
*
* @param locale ICU style C locale (e.g. "en_US"). If not specified or empty, disables the
* override and restores default host system locale.
*/
@Experimental
void setLocaleOverride(@Optional @ParamName("locale") String locale);
/**
* Overrides default host system timezone with the specified one.
*
* @param timezoneId The timezone identifier. If empty, disables the override and restores default
* host system timezone.
*/
@Experimental
void setTimezoneOverride(@ParamName("timezoneId") String timezoneId);
/**
* Resizes the frame/viewport of the page. Note that this does not affect the frame's container
* (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported
* on Android.
*
* @param width Frame width (DIP).
* @param height Frame height (DIP).
*/
@Deprecated
@Experimental
void setVisibleSize(@ParamName("width") Integer width, @ParamName("height") Integer height);
/** @param imageTypes Image types to disable. */
@Experimental
void setDisabledImageTypes(@ParamName("imageTypes") List<DisabledImageType> imageTypes);
/** @param hardwareConcurrency Hardware concurrency to report */
@Experimental
void setHardwareConcurrencyOverride(
@ParamName("hardwareConcurrency") Integer hardwareConcurrency);
/**
* Allows overriding user agent with the given string.
*
* @param userAgent User agent to use.
*/
void setUserAgentOverride(@ParamName("userAgent") String userAgent);
/**
* Allows overriding user agent with the given string.
*
* @param userAgent User agent to use.
* @param acceptLanguage Browser langugage to emulate.
* @param platform The platform navigator.platform should return.
* @param userAgentMetadata To be sent in Sec-CH-UA-* headers and returned in
* navigator.userAgentData
*/
void setUserAgentOverride(
@ParamName("userAgent") String userAgent,
@Optional @ParamName("acceptLanguage") String acceptLanguage,
@Optional @ParamName("platform") String platform,
@Experimental @Optional @ParamName("userAgentMetadata") UserAgentMetadata userAgentMetadata);
/**
* Allows overriding the automation flag.
*
* @param enabled Whether the override should be enabled.
*/
@Experimental
void setAutomationOverride(@ParamName("enabled") Boolean enabled);
/**
* Notification sent after the virtual time budget for the current VirtualTimePolicy has run out.
*/
@EventName("virtualTimeBudgetExpired")
@Experimental
EventListener onVirtualTimeBudgetExpired(EventHandler<VirtualTimeBudgetExpired> eventListener);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.